from __future__ import annotations import base64 import json import re 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("未配置 AI_API_KEY。") if self.config.protocol == "anthropic": return self._anthropic_chat_json(system_prompt, user_payload) return self._openai_chat_json(system_prompt, user_payload) 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。") if self.config.protocol == "anthropic": return self._anthropic_audio_json(system_prompt, audio_path, user_text) return self._openai_audio_json(system_prompt, audio_path, user_text) def _openai_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]: body = { "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"}, } payload = self._post_json("/chat/completions", body, self._openai_headers(), "AI 请求失败") content = payload.get("choices", [{}])[0].get("message", {}).get("content", "") return self._parse_json_text(content, "AI 返回内容不是有效 JSON。") def _openai_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii") body = { "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"}, } payload = self._post_json("/chat/completions", body, self._openai_headers(), "音频识别请求失败") content = payload.get("choices", [{}])[0].get("message", {}).get("content", "") return self._parse_json_text(content, "音频识别返回内容不是有效 JSON。") def _anthropic_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]: body = { "model": self.config.model, "max_tokens": 4096, "system": system_prompt, "messages": [ { "role": "user", "content": [ { "type": "text", "text": ( "Return only one valid JSON object. Do not use markdown fences or extra text.\n" f"{json.dumps(user_payload, ensure_ascii=False)}" ), } ], } ], } payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 请求失败") return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 返回内容不是有效 JSON。") def _anthropic_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]: audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii") body = { "model": self.config.audio_model, "max_tokens": 1024, "system": system_prompt, "messages": [ { "role": "user", "content": [ {"type": "text", "text": user_text}, { "type": "input_audio", "source": { "type": "base64", "media_type": "audio/wav", "data": audio_data, }, }, ], } ], } payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 音频识别请求失败") return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 音频识别返回内容不是有效 JSON。") def _post_json( self, path: str, body: dict[str, object], headers: dict[str, str], error_prefix: str, ) -> dict[str, object]: request = urllib.request.Request( f"{self.config.base_url}{path}", data=json.dumps(body).encode("utf-8"), headers=headers, method="POST", ) try: with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response: return json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as error: detail = error.read().decode("utf-8", errors="replace") raise DeepSeekError(f"{error_prefix}:{error.code} {detail}") from error except Exception as error: raise DeepSeekError(f"{error_prefix}:{error}") from error def _openai_headers(self) -> dict[str, str]: return { "Authorization": f"Bearer {self.config.api_key}", "Content-Type": "application/json", } def _anthropic_headers(self) -> dict[str, str]: return { "x-api-key": self.config.api_key, "anthropic-version": "2023-06-01", "Content-Type": "application/json", } def _extract_anthropic_text(self, payload: dict[str, object]) -> str: blocks = payload.get("content", []) if not isinstance(blocks, list): return "" texts = [ str(block.get("text", "")) for block in blocks if isinstance(block, dict) and block.get("type") == "text" ] return "\n".join(texts).strip() def _parse_json_text(self, content: str, error_message: str) -> dict[str, object]: json_text = self._extract_json_text(content) try: return json.loads(json_text) except json.JSONDecodeError as error: raise DeepSeekError(error_message) from error def _extract_json_text(self, content: str) -> str: text = str(content or "").strip() if not text: return text fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.IGNORECASE | re.DOTALL) if fenced: return fenced.group(1).strip() start = text.find("{") if start < 0: return text decoder = json.JSONDecoder() try: _, end = decoder.raw_decode(text[start:]) except json.JSONDecodeError: return text return text[start:start + end].strip()