107 lines
4.1 KiB
Python
107 lines
4.1 KiB
Python
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
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
|
|
|
|
def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
|
|
if not self.config.api_key:
|
|
raise DeepSeekError("未配置 AI_API_KEY。")
|
|
|
|
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
|
|
body = json.dumps({
|
|
"model": self.config.audio_model,
|
|
"messages": [
|
|
{"role": "system", "content": system_prompt},
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": user_text},
|
|
{
|
|
"type": "input_audio",
|
|
"input_audio": {
|
|
"data": f"data:audio/wav;base64,{audio_data}",
|
|
"format": "wav",
|
|
},
|
|
},
|
|
],
|
|
},
|
|
],
|
|
"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"Qwen 音频识别请求失败:{error.code} {detail}") from error
|
|
except Exception as error:
|
|
raise DeepSeekError(f"Qwen 音频识别请求失败:{error}") from error
|
|
|
|
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
|
try:
|
|
return json.loads(content)
|
|
except json.JSONDecodeError as error:
|
|
raise DeepSeekError("Qwen 音频识别返回内容不是有效 JSON。") from error
|