qwen_client.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import dashscope
  2. class QwenClient:
  3. def __init__(self):
  4. self.api_key = "sk-fef6289a33024fcca98edf6fae3afbcc"
  5. def chat(self, model="qwen3-max", system_prompt="You are a helpful assistant.", user_prompt=""):
  6. """
  7. 普通聊天,不使用搜索功能
  8. Args:
  9. model: 模型名称,默认为qwen3-max
  10. system_prompt: 系统提示词
  11. user_prompt: 用户提示词
  12. Returns:
  13. str: AI回复内容
  14. """
  15. try:
  16. messages = [
  17. {"role": "system", "content": system_prompt},
  18. {"role": "user", "content": user_prompt},
  19. ]
  20. response = dashscope.Generation.call(
  21. api_key=self.api_key,
  22. model=model,
  23. messages=messages,
  24. result_format="message"
  25. )
  26. if response.status_code != 200:
  27. raise Exception(f"API调用失败: {response.message}")
  28. return response["output"]["choices"][0]["message"]["content"]
  29. except Exception as e:
  30. raise Exception(f"QwenClient chat失败: {str(e)}")
  31. def search_and_chat(self, model="qwen3-max", system_prompt="You are a helpful assistant.", user_prompt="", search_strategy="max"):
  32. """
  33. 搜索并聊天
  34. Args:
  35. model: 模型名称,默认为qwen3-max
  36. system_prompt: 系统提示词
  37. user_prompt: 用户提示词
  38. search_strategy: 搜索策略,可选值: turbo, max, agent
  39. Returns:
  40. dict: 包含回复内容和搜索结果
  41. """
  42. try:
  43. messages = [
  44. {"role": "system", "content": system_prompt},
  45. {"role": "user", "content": user_prompt},
  46. ]
  47. response = dashscope.Generation.call(
  48. api_key=self.api_key,
  49. model=model,
  50. messages=messages,
  51. enable_search=True,
  52. search_options={
  53. "forced_search": True,
  54. "enable_source": True,
  55. "search_strategy": search_strategy
  56. },
  57. result_format="message"
  58. )
  59. if response.status_code != 200:
  60. raise Exception(f"API调用失败: {response.message}")
  61. content = response["output"]["choices"][0]["message"]["content"]
  62. search_results = []
  63. if hasattr(response.output, 'search_info') and response.output.search_info:
  64. search_results = response.output.search_info.get("search_results", [])
  65. return {
  66. "content": content,
  67. "search_results": search_results
  68. }
  69. except Exception as e:
  70. raise Exception(f"QwenClient search_and_chat失败: {str(e)}")
  71. if __name__ == "__main__":
  72. client = QwenClient()
  73. # 测试
  74. try:
  75. # prompt = """请将工具 [小红书] 的 [帖子详情] 功能翻译为英文,并返回翻译后的英文名称
  76. # 要求:
  77. # 1. 要将工具和功能一起翻译,如果没有合适的翻译,用中文拼音替代
  78. # 2. 翻译返回的英文名称所有单词用下划线拼接,不能出现空格。比如: chatgpt_ai_search
  79. # 3. 仅输出以下 JSON,不添加任何其他文字、注释或解释:
  80. # {
  81. # "english_name": ""
  82. # }"""
  83. # result = client.chat(user_prompt=prompt)
  84. # print(result)
  85. user_prompt = """明星宠物 造型元素 规律"""
  86. # user_prompt = "请搜索 白瓜AI 官网"
  87. result = client.search_and_chat(user_prompt=user_prompt, search_strategy="agent")
  88. print("="*20 + "搜索结果" + "="*20)
  89. for web in result["search_results"]:
  90. print(f"[{web['index']}]: [{web['title']}]({web['url']})")
  91. print("="*20 + "回复内容" + "="*20)
  92. print(result["content"])
  93. except Exception as e:
  94. print(f"错误: {e}")