55 lines
1.9 KiB
Python
55 lines
1.9 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
from .ai_config import DeepSeekConfig
|
|
|
|
|
|
class DeepSeekError(RuntimeError):
|
|
pass
|
|
|
|
|
|
class DeepSeekClient:
|
|
def __init__(self, config: DeepSeekConfig, timeout_seconds: int = 60):
|
|
self.config = config
|
|
self.timeout_seconds = timeout_seconds
|
|
|
|
def chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
|
if not self.config.api_key:
|
|
raise DeepSeekError("未配置 DEEPSEEK_API_KEY。")
|
|
|
|
body = json.dumps({
|
|
"model": self.config.model,
|
|
"messages": [
|
|
{"role": "system", "content": system_prompt},
|
|
{"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)},
|
|
],
|
|
"response_format": {"type": "json_object"},
|
|
}).encode("utf-8")
|
|
request = urllib.request.Request(
|
|
f"{self.config.base_url}/chat/completions",
|
|
data=body,
|
|
headers={
|
|
"Authorization": f"Bearer {self.config.api_key}",
|
|
"Content-Type": "application/json",
|
|
},
|
|
method="POST",
|
|
)
|
|
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
|
|
payload = json.loads(response.read().decode("utf-8"))
|
|
except urllib.error.HTTPError as error:
|
|
detail = error.read().decode("utf-8", errors="replace")
|
|
raise DeepSeekError(f"DeepSeek 请求失败:{error.code} {detail}") from error
|
|
except Exception as error:
|
|
raise DeepSeekError(f"DeepSeek 请求失败:{error}") from error
|
|
|
|
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
|
try:
|
|
return json.loads(content)
|
|
except json.JSONDecodeError as error:
|
|
raise DeepSeekError("DeepSeek 返回内容不是有效 JSON。") from error
|