deepseek_chat.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import os
  2. from openai import OpenAI
  3. from .base_llm_chat import BaseLLMChat
  4. class DeepSeekChat(BaseLLMChat):
  5. """DeepSeek AI聊天实现"""
  6. def __init__(self, config=None):
  7. print("...DeepSeekChat init...")
  8. super().__init__(config=config)
  9. if config is None:
  10. self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
  11. return
  12. if "api_key" in config:
  13. if "base_url" not in config:
  14. self.client = OpenAI(api_key=config["api_key"], base_url="https://api.deepseek.com")
  15. else:
  16. self.client = OpenAI(api_key=config["api_key"], base_url=config["base_url"])
  17. def submit_prompt(self, prompt, **kwargs) -> str:
  18. if prompt is None:
  19. raise Exception("Prompt is None")
  20. if len(prompt) == 0:
  21. raise Exception("Prompt is empty")
  22. # Count the number of tokens in the message log
  23. num_tokens = 0
  24. for message in prompt:
  25. num_tokens += len(message["content"]) / 4
  26. # 获取 stream 参数
  27. stream_mode = kwargs.get("stream", self.config.get("stream", False) if self.config else False)
  28. # 获取 enable_thinking 参数
  29. enable_thinking = kwargs.get("enable_thinking", self.config.get("enable_thinking", False) if self.config else False)
  30. # DeepSeek API约束:enable_thinking=True时建议使用stream=True
  31. # 如果stream=False但enable_thinking=True,则忽略enable_thinking
  32. if enable_thinking and not stream_mode:
  33. print("WARNING: enable_thinking=True 不生效,因为它需要 stream=True")
  34. enable_thinking = False
  35. # 确定使用的模型
  36. model = None
  37. if kwargs.get("model", None) is not None:
  38. model = kwargs.get("model", None)
  39. elif kwargs.get("engine", None) is not None:
  40. model = kwargs.get("engine", None)
  41. elif self.config is not None and "engine" in self.config:
  42. model = self.config["engine"]
  43. elif self.config is not None and "model" in self.config:
  44. model = self.config["model"]
  45. else:
  46. # 根据 enable_thinking 选择模型
  47. if enable_thinking:
  48. model = "deepseek-reasoner"
  49. else:
  50. if num_tokens > 3500:
  51. model = "deepseek-chat"
  52. else:
  53. model = "deepseek-chat"
  54. # 模型兼容性提示(但不强制切换)
  55. if enable_thinking and model not in ["deepseek-reasoner"]:
  56. print(f"提示:模型 {model} 可能不支持推理功能,推理相关参数将被忽略")
  57. print(f"\nUsing model {model} for {num_tokens} tokens (approx)")
  58. print(f"Enable thinking: {enable_thinking}, Stream mode: {stream_mode}")
  59. # 构建 API 调用参数
  60. api_params = {
  61. "model": model,
  62. "messages": prompt,
  63. "stop": None,
  64. "temperature": self.temperature,
  65. "stream": stream_mode,
  66. }
  67. # 过滤掉自定义参数,避免传递给 API
  68. filtered_kwargs = {k: v for k, v in kwargs.items()
  69. if k not in ['model', 'engine', 'enable_thinking', 'stream']}
  70. # 根据模型过滤不支持的参数
  71. if model == "deepseek-reasoner":
  72. # deepseek-reasoner 不支持的参数
  73. unsupported_params = ['top_p', 'presence_penalty', 'frequency_penalty', 'logprobs', 'top_logprobs']
  74. for param in unsupported_params:
  75. if param in filtered_kwargs:
  76. print(f"警告:deepseek-reasoner 不支持参数 {param},已忽略")
  77. filtered_kwargs.pop(param, None)
  78. else:
  79. # deepseek-chat 等其他模型,只过滤明确会导致错误的参数
  80. # 目前 deepseek-chat 支持大部分标准参数,暂不过滤
  81. pass
  82. # 添加其他参数
  83. api_params.update(filtered_kwargs)
  84. if stream_mode:
  85. # 流式处理模式
  86. if model == "deepseek-reasoner" and enable_thinking:
  87. print("使用流式处理模式,启用推理功能")
  88. else:
  89. print("使用流式处理模式,常规聊天")
  90. response_stream = self.client.chat.completions.create(**api_params)
  91. if model == "deepseek-reasoner" and enable_thinking:
  92. # 推理模型的流式处理
  93. collected_reasoning = []
  94. collected_content = []
  95. for chunk in response_stream:
  96. if hasattr(chunk, 'choices') and chunk.choices:
  97. delta = chunk.choices[0].delta
  98. # 收集推理内容
  99. if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
  100. collected_reasoning.append(delta.reasoning_content)
  101. # 收集最终答案
  102. if hasattr(delta, 'content') and delta.content:
  103. collected_content.append(delta.content)
  104. # 可选:打印推理过程
  105. if collected_reasoning:
  106. print("Model reasoning process:\n", "".join(collected_reasoning))
  107. return "".join(collected_content)
  108. else:
  109. # 其他模型的流式处理(如 deepseek-chat)
  110. collected_content = []
  111. for chunk in response_stream:
  112. if hasattr(chunk, 'choices') and chunk.choices:
  113. delta = chunk.choices[0].delta
  114. if hasattr(delta, 'content') and delta.content:
  115. collected_content.append(delta.content)
  116. return "".join(collected_content)
  117. else:
  118. # 非流式处理模式
  119. if model == "deepseek-reasoner" and enable_thinking:
  120. print("使用非流式处理模式,启用推理功能")
  121. else:
  122. print("使用非流式处理模式,常规聊天")
  123. response = self.client.chat.completions.create(**api_params)
  124. if model == "deepseek-reasoner" and enable_thinking:
  125. # 推理模型的非流式处理
  126. message = response.choices[0].message
  127. # 可选:打印推理过程
  128. if hasattr(message, 'reasoning_content') and message.reasoning_content:
  129. print("Model reasoning process:\n", message.reasoning_content)
  130. return message.content
  131. else:
  132. # 其他模型的非流式处理(如 deepseek-chat)
  133. return response.choices[0].message.content