Call local llm
In [ ]:
Copied!
"""14주 실습: OpenAI 호환 주소로 로컬 LLM 에 질문하기 (표준 라이브러리만 써요, 설치 없음).
환경 변수
LLM_BASE_URL 필수. 서버의 OpenAI 호환 주소. 예) http://127.0.0.1:11434/v1
LLM_MODEL 필수. 서버에 있는 모델 이름. 예) Ollama 에서 받은 이름
LLM_API_KEY 선택. 로컬 서버는 보통 필요 없어요.
실행
LLM_BASE_URL=http://127.0.0.1:11434/v1 LLM_MODEL=<모델이름> \
uv run --no-project call_local_llm.py "한 문장으로 자기소개 해 줘"
"""
"""14주 실습: OpenAI 호환 주소로 로컬 LLM 에 질문하기 (표준 라이브러리만 써요, 설치 없음).
환경 변수
LLM_BASE_URL 필수. 서버의 OpenAI 호환 주소. 예) http://127.0.0.1:11434/v1
LLM_MODEL 필수. 서버에 있는 모델 이름. 예) Ollama 에서 받은 이름
LLM_API_KEY 선택. 로컬 서버는 보통 필요 없어요.
실행
LLM_BASE_URL=http://127.0.0.1:11434/v1 LLM_MODEL=<모델이름> \
uv run --no-project call_local_llm.py "한 문장으로 자기소개 해 줘"
"""
In [ ]:
Copied!
import json
import os
import sys
import time
import urllib.error
import urllib.request
import json
import os
import sys
import time
import urllib.error
import urllib.request
In [ ]:
Copied!
HELP = """\
LLM_BASE_URL 환경 변수가 없어요. 아직 로컬 LLM 서버를 안 켰거나 주소를 알려 주지 않았어요.
1) 서버를 켜세요 (아래 중 하나, 14주 쪽의 3절 참고)
- Ollama: ollama serve (보통 이미 켜져 있어요)
- llama.cpp: llama-server -m 모델.gguf
2) 주소와 모델 이름을 알려 주고 다시 실행하세요
LLM_BASE_URL=http://127.0.0.1:11434/v1 LLM_MODEL=<모델이름> \\
uv run --no-project call_local_llm.py "안녕하세요"
(llama-server 의 주소와 포트는 서버를 켤 때 나오는 로그에서 확인하세요.)
"""
HELP = """\
LLM_BASE_URL 환경 변수가 없어요. 아직 로컬 LLM 서버를 안 켰거나 주소를 알려 주지 않았어요.
1) 서버를 켜세요 (아래 중 하나, 14주 쪽의 3절 참고)
- Ollama: ollama serve (보통 이미 켜져 있어요)
- llama.cpp: llama-server -m 모델.gguf
2) 주소와 모델 이름을 알려 주고 다시 실행하세요
LLM_BASE_URL=http://127.0.0.1:11434/v1 LLM_MODEL=<모델이름> \\
uv run --no-project call_local_llm.py "안녕하세요"
(llama-server 의 주소와 포트는 서버를 켤 때 나오는 로그에서 확인하세요.)
"""
In [ ]:
Copied!
def ask(base_url: str, model: str, question: str, api_key: str = "") -> dict:
"""POST {base_url}/chat/completions — OpenAI 호환 서버라면 어디나 같은 모양이에요."""
body = {
"model": model,
"messages": [{"role": "user", "content": question}],
"temperature": 0.2,
}
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
req = urllib.request.Request(
base_url.rstrip("/") + "/chat/completions",
data=json.dumps(body).encode("utf-8"),
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
return json.loads(resp.read())
def ask(base_url: str, model: str, question: str, api_key: str = "") -> dict:
"""POST {base_url}/chat/completions — OpenAI 호환 서버라면 어디나 같은 모양이에요."""
body = {
"model": model,
"messages": [{"role": "user", "content": question}],
"temperature": 0.2,
}
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
req = urllib.request.Request(
base_url.rstrip("/") + "/chat/completions",
data=json.dumps(body).encode("utf-8"),
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
return json.loads(resp.read())
In [ ]:
Copied!
def main() -> int:
base_url = os.environ.get("LLM_BASE_URL", "").strip()
model = os.environ.get("LLM_MODEL", "").strip()
if not base_url:
print(HELP)
return 0 # 안내만 하고 정상 종료: 오류가 아니라 "아직 준비 전"이에요.
if not model:
print("LLM_MODEL 환경 변수(모델 이름)도 필요해요. 모델 목록은 `ollama list` 로 볼 수 있어요.")
return 0
question = " ".join(sys.argv[1:]) or "한 문장으로 자기소개 해 줘."
t0 = time.perf_counter()
try:
data = ask(base_url, model, question, os.environ.get("LLM_API_KEY", ""))
except urllib.error.HTTPError as e:
print(f"서버가 오류를 돌려줬어요(상태 {e.code}). 모델 이름이 맞는지 확인하세요.")
return 1
except (urllib.error.URLError, TimeoutError) as e:
print(f"서버에 연결하지 못했어요: {e}\n서버가 켜져 있는지, LLM_BASE_URL 이 맞는지 확인하세요.")
return 1
sec = time.perf_counter() - t0
print(data["choices"][0]["message"]["content"])
usage = data.get("usage") or {}
out_tokens = usage.get("completion_tokens")
if out_tokens:
print(f"\n[{sec:.1f}초 · 출력 {out_tokens}토큰 · 약 {out_tokens / sec:.1f}토큰/초]")
else:
print(f"\n[{sec:.1f}초]")
return 0
def main() -> int:
base_url = os.environ.get("LLM_BASE_URL", "").strip()
model = os.environ.get("LLM_MODEL", "").strip()
if not base_url:
print(HELP)
return 0 # 안내만 하고 정상 종료: 오류가 아니라 "아직 준비 전"이에요.
if not model:
print("LLM_MODEL 환경 변수(모델 이름)도 필요해요. 모델 목록은 `ollama list` 로 볼 수 있어요.")
return 0
question = " ".join(sys.argv[1:]) or "한 문장으로 자기소개 해 줘."
t0 = time.perf_counter()
try:
data = ask(base_url, model, question, os.environ.get("LLM_API_KEY", ""))
except urllib.error.HTTPError as e:
print(f"서버가 오류를 돌려줬어요(상태 {e.code}). 모델 이름이 맞는지 확인하세요.")
return 1
except (urllib.error.URLError, TimeoutError) as e:
print(f"서버에 연결하지 못했어요: {e}\n서버가 켜져 있는지, LLM_BASE_URL 이 맞는지 확인하세요.")
return 1
sec = time.perf_counter() - t0
print(data["choices"][0]["message"]["content"])
usage = data.get("usage") or {}
out_tokens = usage.get("completion_tokens")
if out_tokens:
print(f"\n[{sec:.1f}초 · 출력 {out_tokens}토큰 · 약 {out_tokens / sec:.1f}토큰/초]")
else:
print(f"\n[{sec:.1f}초]")
return 0
In [ ]:
Copied!
if __name__ == "__main__":
sys.exit(main())
if __name__ == "__main__":
sys.exit(main())