deepseek_chat.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. # 方案1:通过 system prompt 控制中文输出(DeepSeek 不支持 language 参数)
  60. # 检查配置中的语言设置,并在 system prompt 中添加中文指令
  61. # language_setting = self.config.get("language", "").lower() if self.config else ""
  62. # print(f"DEBUG: language_setting='{language_setting}', model='{model}', enable_thinking={enable_thinking}")
  63. # if language_setting == "chinese" and enable_thinking:
  64. # print("DEBUG: ✅ 触发中文指令添加")
  65. # # 为推理模型添加中文思考指令
  66. # chinese_instruction = {"role": "system", "content": "请用中文进行思考和回答。在推理过程中,请使用中文进行分析和思考。<think></think>之间也请使用中文"}
  67. # # 如果第一条消息不是 system 消息,则添加中文指令
  68. # if not prompt or prompt[0].get("role") != "system":
  69. # prompt = [chinese_instruction] + prompt
  70. # else:
  71. # # 如果已有 system 消息,则在其内容中添加中文指令
  72. # existing_content = prompt[0]["content"]
  73. # prompt[0]["content"] = f"{existing_content}\n\n请用中文进行思考和回答。在推理过程中,请使用中文进行分析和思考。<think></think>之间也请使用中文"
  74. # else:
  75. # print(f"DEBUG: ❌ 未触发中文指令 - language_setting==chinese: {language_setting == 'chinese'}, model==deepseek-reasoner: {model == 'deepseek-reasoner'}, enable_thinking: {enable_thinking}")
  76. # 构建 API 调用参数
  77. api_params = {
  78. "model": model,
  79. "messages": prompt,
  80. "stop": None,
  81. "temperature": self.temperature,
  82. "stream": stream_mode,
  83. }
  84. # 过滤掉自定义参数,避免传递给 API
  85. # 注意:保留 language 参数,让 DeepSeek API 自己处理
  86. filtered_kwargs = {k: v for k, v in kwargs.items()
  87. if k not in ['model', 'engine', 'enable_thinking', 'stream']}
  88. # 根据模型过滤不支持的参数
  89. if model == "deepseek-reasoner":
  90. # deepseek-reasoner 不支持的参数
  91. unsupported_params = ['top_p', 'presence_penalty', 'frequency_penalty', 'logprobs', 'top_logprobs']
  92. for param in unsupported_params:
  93. if param in filtered_kwargs:
  94. print(f"警告:deepseek-reasoner 不支持参数 {param},已忽略")
  95. filtered_kwargs.pop(param, None)
  96. else:
  97. # deepseek-chat 等其他模型,只过滤明确会导致错误的参数
  98. # 目前 deepseek-chat 支持大部分标准参数,暂不过滤
  99. pass
  100. # 添加其他参数
  101. api_params.update(filtered_kwargs)
  102. if stream_mode:
  103. # 流式处理模式
  104. if model == "deepseek-reasoner" and enable_thinking:
  105. print("使用流式处理模式,启用推理功能")
  106. else:
  107. print("使用流式处理模式,常规聊天")
  108. response_stream = self.client.chat.completions.create(**api_params)
  109. if model == "deepseek-reasoner" and enable_thinking:
  110. # 推理模型的流式处理
  111. collected_reasoning = []
  112. collected_content = []
  113. for chunk in response_stream:
  114. if hasattr(chunk, 'choices') and chunk.choices:
  115. delta = chunk.choices[0].delta
  116. # 收集推理内容
  117. if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
  118. collected_reasoning.append(delta.reasoning_content)
  119. # 收集最终答案
  120. if hasattr(delta, 'content') and delta.content:
  121. collected_content.append(delta.content)
  122. # 可选:打印推理过程
  123. if collected_reasoning:
  124. reasoning_text = "".join(collected_reasoning)
  125. print("Model reasoning process:\n", reasoning_text)
  126. # 方案2:返回包含 <think></think> 标签的完整内容,与 QianWen 保持一致
  127. final_content = "".join(collected_content)
  128. if collected_reasoning:
  129. reasoning_text = "".join(collected_reasoning)
  130. return f"<think>{reasoning_text}</think>\n\n{final_content}"
  131. else:
  132. return final_content
  133. else:
  134. # 其他模型的流式处理(如 deepseek-chat)
  135. collected_content = []
  136. for chunk in response_stream:
  137. if hasattr(chunk, 'choices') and chunk.choices:
  138. delta = chunk.choices[0].delta
  139. if hasattr(delta, 'content') and delta.content:
  140. collected_content.append(delta.content)
  141. return "".join(collected_content)
  142. else:
  143. # 非流式处理模式
  144. if model == "deepseek-reasoner" and enable_thinking:
  145. print("使用非流式处理模式,启用推理功能")
  146. else:
  147. print("使用非流式处理模式,常规聊天")
  148. response = self.client.chat.completions.create(**api_params)
  149. if model == "deepseek-reasoner" and enable_thinking:
  150. # 推理模型的非流式处理
  151. message = response.choices[0].message
  152. # 可选:打印推理过程
  153. reasoning_content = ""
  154. if hasattr(message, 'reasoning_content') and message.reasoning_content:
  155. reasoning_content = message.reasoning_content
  156. print("Model reasoning process:\n", reasoning_content)
  157. # 方案2:返回包含 <think></think> 标签的完整内容,与 QianWen 保持一致
  158. final_content = message.content
  159. if reasoning_content:
  160. return f"<think>{reasoning_content}</think>\n\n{final_content}"
  161. else:
  162. return final_content
  163. else:
  164. # 其他模型的非流式处理(如 deepseek-chat)
  165. return response.choices[0].message.content