-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsiliconflow_api.py
More file actions
51 lines (43 loc) · 1.89 KB
/
siliconflow_api.py
File metadata and controls
51 lines (43 loc) · 1.89 KB
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 requests
import logging
from typing import Optional
class SiliconflowAPIWrapper:
"""封装硅基流动API的调用逻辑"""
BASE_URL = "https://api.siliconflow.cn/v1/chat/completions"
def __init__(self, api_key: str):
self.api_key = api_key
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
def generate_content(self, model: str, prompt: str, system_instruction: Optional[str],
temperature: float, max_tokens: int, top_p: float,
top_k: int, frequency_penalty: float, min_p: float) -> str:
if not self.api_key:
return "错误:未设置硅基流动API密钥。"
messages = []
if system_instruction and system_instruction.strip():
messages.append({"role": "system", "content": system_instruction.strip()})
messages.append({"role": "user", "content": prompt})
data = {
"model": model,
"messages": messages,
"stream": False,
"max_tokens": max_tokens,
"min_p": min_p,
"temperature": temperature,
"top_p": top_p,
"top_k": top_k,
"frequency_penalty": frequency_penalty,
}
try:
response = requests.post(self.BASE_URL, headers=self.headers, json=data)
response.raise_for_status()
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
return result["choices"][0]["message"]["content"]
else:
logging.error(f"硅基流动API返回异常数据: {result}")
return "错误:API返回结果格式异常。"
except requests.exceptions.RequestException as e:
return f"错误:调用硅基流动API失败 - {str(e)}"