deep_seek_official_api.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 applications.config import deep_seek_official_model
  9. from applications.config import deep_seek_official_api_key
  10. def fetch_deepseek_completion(
  11. model: str,
  12. prompt: str,
  13. output_type: str = "text",
  14. tool_calls: bool = False,
  15. tools: List[Dict] = None,
  16. ) -> Optional[Dict]:
  17. messages = [{"role": "user", "content": prompt}]
  18. kwargs = {
  19. "model": deep_seek_official_model.get(model, "deepseek-chat"),
  20. "messages": messages,
  21. }
  22. # add tool calls
  23. if tool_calls and tools:
  24. kwargs["tools"] = tools
  25. kwargs["tool_choice"] = "auto"
  26. client = OpenAI(
  27. api_key=deep_seek_official_api_key, base_url="https://api.deepseek.com"
  28. )
  29. if output_type == "json":
  30. kwargs["response_format"] = {"type": "json_object"}
  31. try:
  32. response = client.chat.completions.create(**kwargs)
  33. choice = response.choices[0]
  34. if output_type == "text":
  35. return choice.message.content # 只返回文本
  36. elif output_type == "json":
  37. return json.loads(choice.message.content)
  38. else:
  39. raise ValueError(f"Invalid output_type: {output_type}")
  40. except Exception as e:
  41. print(f"[ERROR] fetch_deepseek_completion failed: {e}")
  42. return None