안녕하세요? 이번 글에서는 QGIS 파이썬 콘솔에서 Gemma 3 LLM과 대화하는 코드를 소개해 보겠습니다. Gemma 3 LLM 설치 방법은 앞서 작성한 아래 글을 참고하시면 됩니다.
Ollama(올라마): 로컬에서 LLM(Gemma 3 모델) 실행하기
안녕하세요? 이번 글에서는 로컬에서 대규모 언어 모델(LLMs: Large Language Models)을 바로 시작해볼 수 있는 Ollama(올라마)를 이용해, Google의 Gemma(젬마) 3 모델 실행 방법을 학습해 보겠습니다. Ollama는
foss4g.tistory.com
아래 코드는 로컬 Ollama 서버에서 Gemma 모델을 통해 질문에 실시간으로 응답을 받아 출력하는 비동기 함수입니다. 이를 통해 명령어 입력 후 즉시 응답을 받아볼 수 있습니다.
import requests
import json
import sys
import threading
def ask_gemma(prompt):
def _worker():
url = "http://localhost:11434/api/generate" # 로컬 서버의 Gemma 모델 API 주소
payload = {
"model": "gemma3:4b", # 사용할 모델 이름
"prompt": prompt, # 사용자 입력 프롬프트
"stream": True # 스트리밍 응답 요청
}
try:
# 스트리밍 응답 시작
with requests.post(url, json=payload, stream=True, timeout=60) as response:
response.raise_for_status()
buffer = b"" # 응답 버퍼 초기화
for chunk in response.iter_content(chunk_size=512):
if not chunk:
continue
buffer += chunk
# 버퍼에 줄바꿈 문자가 있을 때까지 처리
while b"\n" in buffer:
line, buffer = buffer.split(b"\n", 1)
if not line.strip():
continue
try:
data = json.loads(line.decode("utf-8")) # JSON 파싱
text = data.get("response", "") # 응답 텍스트 추출
if text:
sys.stdout.write(text) # 출력
sys.stdout.flush()
except json.JSONDecodeError:
continue
except requests.exceptions.RequestException as e:
print(f"[연결 오류] {e}") # 연결 오류 출력
# 백그라운드 스레드로 실행
threading.Thread(target=_worker, daemon=True).start()
이제 Gemma 3 LLM과 대화를 나눠볼까요?
ask_gemma("QGIS에서 벡터 데이터를 GeoPackage로 저장하는 방법은?")