feat(agent): 增加 LLM 路由与诊断日志
This commit is contained in:
@@ -53,6 +53,47 @@ def generate_reply(conversation, user_message: str) -> str:
|
||||
raise LLMRequestError("模型接口返回格式不符合预期。") from exc
|
||||
|
||||
|
||||
def generate_completion(messages: list[dict[str, str]], *, temperature: float = 0.0) -> str:
|
||||
"""Calls the configured chat endpoint with explicit messages and returns assistant text."""
|
||||
|
||||
if not settings.LLM_API_KEY:
|
||||
raise LLMConfigurationError("缺少 LLM_API_KEY 配置。")
|
||||
if not settings.LLM_MODEL:
|
||||
raise LLMConfigurationError("缺少 LLM_MODEL 配置。")
|
||||
|
||||
payload = {
|
||||
"model": settings.LLM_MODEL,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
}
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
endpoint = f"{settings.LLM_BASE_URL.rstrip('/')}/chat/completions"
|
||||
|
||||
http_request = request.Request(
|
||||
endpoint,
|
||||
data=body,
|
||||
headers={
|
||||
"Authorization": f"Bearer {settings.LLM_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with request.urlopen(http_request, timeout=60) as response:
|
||||
data = json.loads(response.read().decode("utf-8"))
|
||||
except error.HTTPError as exc:
|
||||
details = exc.read().decode("utf-8", errors="ignore")
|
||||
raise LLMRequestError(f"模型接口调用失败:HTTP {exc.code} {details}") from exc
|
||||
except error.URLError as exc:
|
||||
raise LLMRequestError(f"模型接口调用失败:{exc.reason}") from exc
|
||||
|
||||
try:
|
||||
return data["choices"][0]["message"]["content"].strip()
|
||||
except (KeyError, IndexError, TypeError) as exc:
|
||||
raise LLMRequestError("模型接口返回格式不符合预期。") from exc
|
||||
|
||||
|
||||
def stream_reply(conversation, user_message: str):
|
||||
"""Streams incremental assistant text from the SiliconFlow chat endpoint."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user