File size: 2,000 Bytes
61fd574
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import json
import logging
import os

import httpx

logger = logging.getLogger(__name__)


class BaseAgent:
    name = "base"

    async def call_llm(self, system_prompt: str, user_input: dict) -> dict:
        api_key = os.getenv("DEEPSEEK_API_KEY")
        if not api_key:
            logger.warning("DEEPSEEK_API_KEY not set, agent=%s cannot call LLM", self.name)
            return {"error": "no_api_key", "agent": self.name}
        try:
            async with httpx.AsyncClient(timeout=60.0) as client:
                resp = await client.post(
                    "https://api.deepseek.com/chat/completions",
                    headers={
                        "Authorization": f"Bearer {api_key}",
                        "Content-Type": "application/json",
                    },
                    json={
                        "model": "deepseek-chat",
                        "response_format": {"type": "json_object"},
                        "messages": [
                            {"role": "system", "content": system_prompt},
                            {"role": "user", "content": json.dumps(user_input, ensure_ascii=False)},
                        ],
                    },
                )
                resp.raise_for_status()
                body = resp.json()
                content = body["choices"][0]["message"]["content"]
                return json.loads(content)
        except httpx.TimeoutException:
            logger.error("LLM call timeout for agent=%s", self.name)
            return {"error": "timeout", "agent": self.name}
        except json.JSONDecodeError:
            logger.error("LLM response parse error for agent=%s", self.name)
            return {"error": "format_error", "agent": self.name}
        except Exception:
            logger.exception("LLM call failed for agent=%s", self.name)
            return {"error": "unknown", "agent": self.name}

    def build_prompt(self, **kwargs) -> tuple[str, dict]:
        raise NotImplementedError