41 lines
1.3 KiB
Python
41 lines
1.3 KiB
Python
from openai import OpenAI
|
|
import aiohttp
|
|
import json
|
|
|
|
# DeepSeek API Configuration
|
|
DEEPSEEK_API_KEY = "sk-3027fb3c810b4e17985fa397d41250b9"
|
|
DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1"
|
|
|
|
client = OpenAI(
|
|
base_url=DEEPSEEK_BASE_URL,
|
|
api_key=DEEPSEEK_API_KEY
|
|
)
|
|
|
|
async def get_aiohttp_session():
|
|
"""获取异步HTTP会话"""
|
|
return aiohttp.ClientSession(
|
|
base_url=f"{DEEPSEEK_BASE_URL}/",
|
|
headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"}
|
|
)
|
|
|
|
async def call_deepseek(messages: list) -> dict:
|
|
"""异步调用DeepSeek API"""
|
|
async with await get_aiohttp_session() as session:
|
|
async with session.post("/chat/completions", json={
|
|
"model": "deepseek-chat",
|
|
"messages": messages,
|
|
"response_format": {"type": "json_object"}
|
|
}) as response:
|
|
if response.status == 200:
|
|
data = await response.json()
|
|
return json.loads(data["choices"][0]["message"]["content"])
|
|
else:
|
|
raise Exception(f"API调用失败: {await response.text()}")
|
|
|
|
async def call_deepseek_sync(messages: list) -> str:
|
|
"""同步调用DeepSeek API"""
|
|
response = client.chat.completions.create(
|
|
model="deepseek-chat",
|
|
messages=messages
|
|
)
|
|
return response.choices[0].message.content |