deepseek_official.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """
  2. @author: luojunhui
  3. @description: deepseek 官方api
  4. """
  5. import json
  6. from typing import Dict, List, Optional
  7. from openai import OpenAI
  8. from app.core.config import GlobalConfigSettings
  9. config = GlobalConfigSettings()
  10. model_map = config.deepseek.get_model_map()
  11. api_key = config.deepseek.api_key
  12. chat_model = config.deepseek.chat_model
  13. reasoner_model = config.deepseek.reasoner_model
  14. def fetch_deepseek_completion(
  15. model: str,
  16. prompt: str,
  17. output_type: str = "text",
  18. tool_calls: bool = False,
  19. tools: List[Dict] = None,
  20. ) -> Optional[Dict | List]:
  21. messages = [{"role": "user", "content": prompt}]
  22. kwargs = {
  23. "model": model_map.get(model, chat_model),
  24. "messages": messages,
  25. }
  26. # add tool calls
  27. if tool_calls and tools:
  28. kwargs["tools"] = tools
  29. kwargs["tool_choice"] = "auto"
  30. client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
  31. if output_type == "json":
  32. kwargs["response_format"] = {"type": "json_object"}
  33. try:
  34. response = client.chat.completions.create(**kwargs)
  35. choice = response.choices[0]
  36. if output_type == "text":
  37. return choice.message.content # 只返回文本
  38. elif output_type == "json":
  39. return json.loads(choice.message.content)
  40. else:
  41. raise ValueError(f"Invalid output_type: {output_type}")
  42. except Exception as e:
  43. print(f"[ERROR] fetch_deepseek_completion failed: {e}")
  44. return None