llm: replace Ollama with CommandCode API
parent
406cd48782
commit
d2e543dfca
@ -0,0 +1,164 @@
|
||||
"""CommandCode chat client — OpenAI-compatible API for offline LLM helpers.
|
||||
|
||||
Only used outside the collection/verification path: role-audit term proposals
|
||||
and optional Korean report summaries. Runtime scraping stays pure Python
|
||||
(CLAUDE.md). Credentials come from the environment (``.env``):
|
||||
|
||||
COMMANDCODE_API_KEY required
|
||||
COMMANDCODE_BASE_URL default https://api.commandcode.ai/provider/v1
|
||||
COMMANDCODE_MODEL fallback when the caller does not pass a model
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
DEFAULT_BASE_URL = "https://api.commandcode.ai/provider/v1"
|
||||
DEFAULT_MODEL = "deepseek/deepseek-v4.1-flash"
|
||||
DEFAULT_TIMEOUT = 180.0
|
||||
_USER_AGENT = "gimme-job/1.0"
|
||||
_MAX_ATTEMPTS = 3
|
||||
_RETRY_STATUS = {429, 500, 502, 503, 504}
|
||||
|
||||
|
||||
class LlmError(RuntimeError):
|
||||
"""Raised when the CommandCode API is unreachable or returns no content."""
|
||||
|
||||
|
||||
def _load_env() -> None:
|
||||
"""Load .env without overriding already-exported variables."""
|
||||
try:
|
||||
import dotenv
|
||||
|
||||
dotenv.load_dotenv()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def api_key() -> Optional[str]:
|
||||
_load_env()
|
||||
key = (os.environ.get("COMMANDCODE_API_KEY") or "").strip()
|
||||
return key or None
|
||||
|
||||
|
||||
def resolve_base_url(explicit: Optional[str] = None) -> str:
|
||||
_load_env()
|
||||
value = os.environ.get("COMMANDCODE_BASE_URL") or explicit or DEFAULT_BASE_URL
|
||||
return value.strip().rstrip("/")
|
||||
|
||||
|
||||
def resolve_model(explicit: Optional[str] = None) -> str:
|
||||
_load_env()
|
||||
value = explicit or os.environ.get("COMMANDCODE_MODEL") or DEFAULT_MODEL
|
||||
return value.strip()
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return api_key() is not None
|
||||
|
||||
|
||||
def _extract_content(payload: dict) -> str:
|
||||
choices = payload.get("choices") or []
|
||||
if not choices:
|
||||
raise LlmError("response contained no choices")
|
||||
message = choices[0].get("message") or {}
|
||||
content = message.get("content")
|
||||
if isinstance(content, list):
|
||||
content = "".join(
|
||||
part.get("text", "") for part in content if isinstance(part, dict)
|
||||
)
|
||||
text = (content or "").strip()
|
||||
if not text:
|
||||
raise LlmError("response contained no text content")
|
||||
return text
|
||||
|
||||
|
||||
def _post(payload: dict, url: str, key: str, timeout: float) -> str:
|
||||
headers = {
|
||||
"Authorization": f"Bearer {key}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"User-Agent": _USER_AGENT,
|
||||
}
|
||||
with httpx.Client(timeout=timeout) as client:
|
||||
response = client.post(url, json=payload, headers=headers)
|
||||
response.raise_for_status()
|
||||
try:
|
||||
data = response.json()
|
||||
except Exception as e:
|
||||
raise LlmError(f"invalid JSON response: {e}") from e
|
||||
if not isinstance(data, dict):
|
||||
raise LlmError("unexpected response payload")
|
||||
if data.get("error"):
|
||||
raise LlmError(str(data["error"])[:300])
|
||||
return _extract_content(data)
|
||||
|
||||
|
||||
def chat(
|
||||
prompt: str,
|
||||
*,
|
||||
system: Optional[str] = None,
|
||||
model: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
temperature: float = 0.1,
|
||||
max_tokens: int = 2048,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
) -> str:
|
||||
"""Send one chat completion request and return the assistant text.
|
||||
|
||||
Retries transient failures (timeouts, 429, 5xx) up to three attempts.
|
||||
Raises :class:`LlmError` when the API is not configured or keeps failing.
|
||||
"""
|
||||
key = api_key()
|
||||
if not key:
|
||||
raise LlmError(
|
||||
"COMMANDCODE_API_KEY is not set — add it to .env or the environment"
|
||||
)
|
||||
|
||||
url = f"{resolve_base_url(base_url)}/chat/completions"
|
||||
messages = []
|
||||
if system:
|
||||
messages.append({"role": "system", "content": system})
|
||||
messages.append({"role": "user", "content": prompt})
|
||||
payload = {
|
||||
"model": resolve_model(model),
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": False,
|
||||
}
|
||||
|
||||
last_error: Optional[Exception] = None
|
||||
for attempt in range(1, _MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _post(payload, url, key, timeout)
|
||||
except httpx.HTTPStatusError as e:
|
||||
last_error = e
|
||||
status = e.response.status_code
|
||||
if status in _RETRY_STATUS and attempt < _MAX_ATTEMPTS:
|
||||
delay = 2 ** (attempt - 1)
|
||||
logger.warning(
|
||||
f"[llm] HTTP {status} — retrying in {delay}s "
|
||||
f"({attempt}/{_MAX_ATTEMPTS})"
|
||||
)
|
||||
time.sleep(delay)
|
||||
continue
|
||||
detail = (e.response.text or "")[:200]
|
||||
raise LlmError(f"HTTP {status}: {detail}") from e
|
||||
except (httpx.TimeoutException, httpx.TransportError) as e:
|
||||
last_error = e
|
||||
if attempt < _MAX_ATTEMPTS:
|
||||
delay = 2 ** (attempt - 1)
|
||||
logger.warning(
|
||||
f"[llm] {type(e).__name__} — retrying in {delay}s "
|
||||
f"({attempt}/{_MAX_ATTEMPTS})"
|
||||
)
|
||||
time.sleep(delay)
|
||||
continue
|
||||
raise LlmError(f"request failed: {e}") from e
|
||||
|
||||
raise LlmError(f"request failed after {_MAX_ATTEMPTS} attempts: {last_error}")
|
||||
@ -0,0 +1,103 @@
|
||||
"""Tests for the CommandCode chat client (mock HTTP — no network)."""
|
||||
import pytest
|
||||
|
||||
from gimme_job import llm
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, payload, status=200, text=""):
|
||||
self._payload = payload
|
||||
self.status_code = status
|
||||
self.text = text
|
||||
|
||||
def raise_for_status(self):
|
||||
if self.status_code >= 400:
|
||||
import httpx
|
||||
|
||||
raise httpx.HTTPStatusError(
|
||||
"error",
|
||||
request=httpx.Request("POST", "https://api.test"),
|
||||
response=httpx.Response(self.status_code, text=self.text),
|
||||
)
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
class _Client:
|
||||
def __init__(self, response, seen):
|
||||
self.response = response
|
||||
self.seen = seen
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def post(self, url, json=None, headers=None):
|
||||
self.seen.update(url=url, json=json, headers=headers)
|
||||
return self.response
|
||||
|
||||
|
||||
def _patch(monkeypatch, payload):
|
||||
seen = {}
|
||||
monkeypatch.setattr(
|
||||
"httpx.Client", lambda *a, **k: _Client(_Resp(payload), seen)
|
||||
)
|
||||
return seen
|
||||
|
||||
|
||||
def test_chat_uses_openai_compatible_endpoint(monkeypatch):
|
||||
monkeypatch.setattr(llm, "api_key", lambda: "tok")
|
||||
monkeypatch.setenv("COMMANDCODE_BASE_URL", "https://api.test/provider/v1")
|
||||
seen = _patch(
|
||||
monkeypatch,
|
||||
{
|
||||
"choices": [
|
||||
{"message": {"role": "assistant", "content": "hello"}}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
out = llm.chat("hi", model="test/model", max_tokens=32)
|
||||
|
||||
assert out == "hello"
|
||||
assert seen["url"] == "https://api.test/provider/v1/chat/completions"
|
||||
assert seen["headers"]["Authorization"] == "Bearer tok"
|
||||
assert seen["headers"]["User-Agent"] == "gimme-job/1.0"
|
||||
assert seen["json"]["model"] == "test/model"
|
||||
assert seen["json"]["max_tokens"] == 32
|
||||
assert seen["json"]["messages"][-1] == {"role": "user", "content": "hi"}
|
||||
|
||||
|
||||
def test_chat_adds_system_message(monkeypatch):
|
||||
monkeypatch.setattr(llm, "api_key", lambda: "tok")
|
||||
seen = _patch(
|
||||
monkeypatch, {"choices": [{"message": {"content": "ok"}}]}
|
||||
)
|
||||
llm.chat("hi", system="be terse")
|
||||
assert seen["json"]["messages"][0] == {
|
||||
"role": "system",
|
||||
"content": "be terse",
|
||||
}
|
||||
|
||||
|
||||
def test_chat_requires_api_key(monkeypatch):
|
||||
monkeypatch.setattr(llm, "api_key", lambda: None)
|
||||
with pytest.raises(llm.LlmError):
|
||||
llm.chat("hi")
|
||||
|
||||
|
||||
def test_chat_rejects_empty_content(monkeypatch):
|
||||
monkeypatch.setattr(llm, "api_key", lambda: "tok")
|
||||
_patch(monkeypatch, {"choices": [{"message": {"content": " "}}]})
|
||||
with pytest.raises(llm.LlmError):
|
||||
llm.chat("hi")
|
||||
|
||||
|
||||
def test_is_configured(monkeypatch):
|
||||
monkeypatch.setattr(llm, "api_key", lambda: "tok")
|
||||
assert llm.is_configured() is True
|
||||
monkeypatch.setattr(llm, "api_key", lambda: None)
|
||||
assert llm.is_configured() is False
|
||||
@ -0,0 +1,43 @@
|
||||
"""Tests for the CommandCode-backed digest summarizer."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from gimme_job.runtime import summarizer as summarizer_module
|
||||
from gimme_job.runtime.summarizer import PostingSummarizer
|
||||
|
||||
|
||||
def _posting():
|
||||
return SimpleNamespace(
|
||||
site_id="ihs",
|
||||
title="Dentist, Orthodontist",
|
||||
company="Indian Health Service",
|
||||
location="Anchorage, AK",
|
||||
posted_text="",
|
||||
job_url="https://www.ihs.gov/.../vid=2829",
|
||||
)
|
||||
|
||||
|
||||
def test_summarize_uses_commandcode(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
summarizer_module.llm, "chat", lambda *a, **k: "요약 결과"
|
||||
)
|
||||
out = PostingSummarizer().summarize([_posting()])
|
||||
assert out == "요약 결과"
|
||||
|
||||
|
||||
def test_summarize_falls_back_on_error(monkeypatch):
|
||||
def boom(*a, **k):
|
||||
raise RuntimeError("api down")
|
||||
|
||||
monkeypatch.setattr(summarizer_module.llm, "chat", boom)
|
||||
out = PostingSummarizer().summarize([_posting()])
|
||||
assert "# 오늘의 신규 채용 공고" in out
|
||||
assert "Dentist, Orthodontist" in out
|
||||
|
||||
|
||||
def test_summarize_empty():
|
||||
assert PostingSummarizer().summarize([]) == "오늘 신규 채용 공고가 없습니다."
|
||||
|
||||
|
||||
def test_is_available_delegates_to_llm(monkeypatch):
|
||||
monkeypatch.setattr(summarizer_module.llm, "is_configured", lambda: True)
|
||||
assert PostingSummarizer().is_available() is True
|
||||
Loading…
Reference in New Issue