|
| 1 | +import json |
| 2 | +import os |
| 3 | +import requests |
| 4 | +from typing import Dict, List, Optional, Any |
| 5 | + |
| 6 | +from mem0.configs.llms.base import BaseLlmConfig |
| 7 | +from mem0.llms.base import LLMBase |
| 8 | +from mem0.memory.utils import extract_json |
| 9 | + |
| 10 | + |
| 11 | +class SiliconFlowLLM(LLMBase): |
| 12 | + """ |
| 13 | + SiliconFlow chat completion provider. |
| 14 | + Docs: |
| 15 | + https://docs.siliconflow.com/en/api-reference/chat-completions/chat-completions |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, config: Optional[BaseLlmConfig] = None): |
| 19 | + super().__init__(config) |
| 20 | + |
| 21 | + if not self.config.model: |
| 22 | + self.config.model = "Qwen/Qwen2.5-7B-Instruct" |
| 23 | + |
| 24 | + self.api_key = self.config.api_key or os.getenv("SILICONFLOW_API_KEY") |
| 25 | + if not self.api_key: |
| 26 | + raise ValueError("SiliconFlow API key not found. Set SILICONFLOW_API_KEY or pass via config.api_key.") |
| 27 | + |
| 28 | + # Allow override of base URL via config or environment (docs show .com domain) |
| 29 | + self.base_url = ( |
| 30 | + getattr(self.config, "base_url", None) |
| 31 | + or os.getenv("SILICONFLOW_BASE_URL") |
| 32 | + or "https://api.siliconflow.com/v1" |
| 33 | + ) |
| 34 | + |
| 35 | + # Pre-build headers |
| 36 | + self.headers = { |
| 37 | + "Authorization": f"Bearer {self.api_key}", |
| 38 | + "Content-Type": "application/json", |
| 39 | + } |
| 40 | + |
| 41 | + def _endpoint(self) -> str: |
| 42 | + return f"{self.base_url}/chat/completions" |
| 43 | + |
| 44 | + def _parse_response(self, data: Dict[str, Any], tools: Optional[List[Dict]]) -> Any: |
| 45 | + """ |
| 46 | + Matches structure similar to OpenAI-like responses. |
| 47 | + """ |
| 48 | + try: |
| 49 | + choice = data["choices"][0] |
| 50 | + message = choice.get("message", {}) |
| 51 | + except (KeyError, IndexError): |
| 52 | + raise ValueError(f"Unexpected SiliconFlow response format: {data}") |
| 53 | + |
| 54 | + if tools: |
| 55 | + processed = {"content": message.get("content"), "tool_calls": []} |
| 56 | + # If SiliconFlow returns tool_calls similar to OpenAI: |
| 57 | + for tc in message.get("tool_calls", []) or []: |
| 58 | + try: |
| 59 | + name = tc["function"]["name"] |
| 60 | + raw_args = tc["function"].get("arguments", "{}") |
| 61 | + # Ensure JSON object parsing |
| 62 | + args = json.loads(extract_json(raw_args)) |
| 63 | + processed["tool_calls"].append({"name": name, "arguments": args}) |
| 64 | + except Exception: |
| 65 | + # Fallback raw |
| 66 | + processed["tool_calls"].append( |
| 67 | + { |
| 68 | + "name": tc.get("function", {}).get("name"), |
| 69 | + "arguments": tc.get("function", {}).get("arguments"), |
| 70 | + } |
| 71 | + ) |
| 72 | + return processed |
| 73 | + else: |
| 74 | + return message.get("content") |
| 75 | + |
| 76 | + def generate_response( |
| 77 | + self, |
| 78 | + messages: List[Dict[str, str]], |
| 79 | + response_format=None, |
| 80 | + tools: Optional[List[Dict]] = None, |
| 81 | + tool_choice: str = "auto", |
| 82 | + ): |
| 83 | + """ |
| 84 | + Create chat completion via SiliconFlow. |
| 85 | + Adjust request body keys if docs differ. |
| 86 | + """ |
| 87 | + payload: Dict[str, Any] = { |
| 88 | + "model": self.config.model, |
| 89 | + "messages": messages, |
| 90 | + "temperature": self.config.temperature, |
| 91 | + "top_p": self.config.top_p, |
| 92 | + "max_tokens": self.config.max_tokens, |
| 93 | + } |
| 94 | + |
| 95 | + # Response format (if SiliconFlow supports 'response_format': {"type": "json_object"}) |
| 96 | + if response_format: |
| 97 | + payload["response_format"] = response_format |
| 98 | + |
| 99 | + # Tool / function calling (verify exact schema in docs; may differ) |
| 100 | + if tools: |
| 101 | + payload["tools"] = tools |
| 102 | + # Some APIs expect {"type":"function","function":{...}} structures |
| 103 | + # tool_choice might be "auto" / {"type":"function","function":{"name":"..."}} |
| 104 | + payload["tool_choice"] = tool_choice |
| 105 | + |
| 106 | + resp = requests.post(self._endpoint(), headers=self.headers, json=payload, timeout=60) |
| 107 | + if resp.status_code >= 400: |
| 108 | + extra_hint = "" |
| 109 | + if resp.status_code == 401: |
| 110 | + extra_hint = ( |
| 111 | + " (401 Unauthorized: Verify SILICONFLOW_API_KEY is correct and matches the domain " |
| 112 | + f"{self.base_url.split('/v1')[0]}; you can also set SILICONFLOW_BASE_URL if needed)" |
| 113 | + ) |
| 114 | + raise RuntimeError(f"SiliconFlow error {resp.status_code}: {resp.text}{extra_hint}") |
| 115 | + |
| 116 | + data = resp.json() |
| 117 | + return self._parse_response(data, tools) |
0 commit comments