deepseek.py 1.4 KB

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