qianwen_chat.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import os
  2. from openai import OpenAI
  3. from .base_llm_chat import BaseLLMChat
  4. class QianWenChat(BaseLLMChat):
  5. """千问AI聊天实现"""
  6. def __init__(self, client=None, config=None):
  7. print("...QianWenChat init...")
  8. super().__init__(config=config)
  9. if "api_type" in config:
  10. raise Exception(
  11. "Passing api_type is now deprecated. Please pass an OpenAI client instead."
  12. )
  13. if "api_base" in config:
  14. raise Exception(
  15. "Passing api_base is now deprecated. Please pass an OpenAI client instead."
  16. )
  17. if "api_version" in config:
  18. raise Exception(
  19. "Passing api_version is now deprecated. Please pass an OpenAI client instead."
  20. )
  21. if client is not None:
  22. self.client = client
  23. return
  24. if config is None and client is None:
  25. self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
  26. return
  27. if "api_key" in config:
  28. if "base_url" not in config:
  29. self.client = OpenAI(api_key=config["api_key"],
  30. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")
  31. else:
  32. self.client = OpenAI(api_key=config["api_key"],
  33. base_url=config["base_url"])
  34. def submit_prompt(self, prompt, **kwargs) -> str:
  35. if prompt is None:
  36. raise Exception("Prompt is None")
  37. if len(prompt) == 0:
  38. raise Exception("Prompt is empty")
  39. # Count the number of tokens in the message log
  40. # Use 4 as an approximation for the number of characters per token
  41. num_tokens = 0
  42. for message in prompt:
  43. num_tokens += len(message["content"]) / 4
  44. # 从配置和参数中获取enable_thinking设置
  45. # 优先使用参数中传入的值,如果没有则从配置中读取,默认为False
  46. enable_thinking = kwargs.get("enable_thinking", self.config.get("enable_thinking", False))
  47. # 公共参数
  48. common_params = {
  49. "messages": prompt,
  50. "stop": None,
  51. "temperature": self.temperature,
  52. }
  53. # 如果启用了thinking,则使用流式处理,但不直接传递enable_thinking参数
  54. if enable_thinking:
  55. common_params["stream"] = True
  56. # 千问API不接受enable_thinking作为参数,可能需要通过header或其他方式传递
  57. # 也可能它只是默认启用stream=True时的thinking功能
  58. model = None
  59. # 确定使用的模型
  60. if kwargs.get("model", None) is not None:
  61. model = kwargs.get("model", None)
  62. common_params["model"] = model
  63. elif kwargs.get("engine", None) is not None:
  64. engine = kwargs.get("engine", None)
  65. common_params["engine"] = engine
  66. model = engine
  67. elif self.config is not None and "engine" in self.config:
  68. common_params["engine"] = self.config["engine"]
  69. model = self.config["engine"]
  70. elif self.config is not None and "model" in self.config:
  71. common_params["model"] = self.config["model"]
  72. model = self.config["model"]
  73. else:
  74. if num_tokens > 3500:
  75. model = "qwen-long"
  76. else:
  77. model = "qwen-plus"
  78. common_params["model"] = model
  79. print(f"\nUsing model {model} for {num_tokens} tokens (approx)")
  80. if enable_thinking:
  81. # 流式处理模式
  82. print("使用流式处理模式,启用thinking功能")
  83. # 检查是否需要通过headers传递enable_thinking参数
  84. response_stream = self.client.chat.completions.create(**common_params)
  85. # 收集流式响应
  86. collected_thinking = []
  87. collected_content = []
  88. for chunk in response_stream:
  89. # 处理thinking部分
  90. if hasattr(chunk, 'thinking') and chunk.thinking:
  91. collected_thinking.append(chunk.thinking)
  92. # 处理content部分
  93. if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
  94. collected_content.append(chunk.choices[0].delta.content)
  95. # 可以在这里处理thinking的展示逻辑,如保存到日志等
  96. if collected_thinking:
  97. print("Model thinking process:", "".join(collected_thinking))
  98. # 返回完整的内容
  99. return "".join(collected_content)
  100. else:
  101. # 非流式处理模式
  102. print("使用非流式处理模式")
  103. response = self.client.chat.completions.create(**common_params)
  104. # Find the first response from the chatbot that has text in it (some responses may not have text)
  105. for choice in response.choices:
  106. if "text" in choice:
  107. return choice.text
  108. # If no response with text is found, return the first response's content (which may be empty)
  109. return response.choices[0].message.content