| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- """
- @author: luojunhui
- @description: deepseek 官方api
- """
- import json
- from typing import Dict, List, Optional
- from openai import OpenAI
- from app.core.config import GlobalConfigSettings
- config = GlobalConfigSettings()
- model_map = config.deepseek.get_model_map()
- api_key = config.deepseek.api_key
- chat_model = config.deepseek.chat_model
- reasoner_model = config.deepseek.reasoner_model
- def fetch_deepseek_completion(
- model: str,
- prompt: str,
- output_type: str = "text",
- tool_calls: bool = False,
- tools: List[Dict] = None,
- ) -> Optional[Dict | List]:
- messages = [{"role": "user", "content": prompt}]
- kwargs = {
- "model": model_map.get(model, chat_model),
- "messages": messages,
- }
- # add tool calls
- if tool_calls and tools:
- kwargs["tools"] = tools
- kwargs["tool_choice"] = "auto"
- client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
- if output_type == "json":
- kwargs["response_format"] = {"type": "json_object"}
- try:
- response = client.chat.completions.create(**kwargs)
- choice = response.choices[0]
- if output_type == "text":
- return choice.message.content # 只返回文本
- elif output_type == "json":
- return json.loads(choice.message.content)
- else:
- raise ValueError(f"Invalid output_type: {output_type}")
- except Exception as e:
- print(f"[ERROR] fetch_deepseek_completion failed: {e}")
- return None
|