deepseek_official.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(
  31. api_key=api_key, base_url="https://api.deepseek.com"
  32. )
  33. if output_type == "json":
  34. kwargs["response_format"] = {"type": "json_object"}
  35. try:
  36. response = client.chat.completions.create(**kwargs)
  37. choice = response.choices[0]
  38. if output_type == "text":
  39. return choice.message.content # 只返回文本
  40. elif output_type == "json":
  41. return json.loads(choice.message.content)
  42. else:
  43. raise ValueError(f"Invalid output_type: {output_type}")
  44. except Exception as e:
  45. print(f"[ERROR] fetch_deepseek_completion failed: {e}")
  46. return None