qwen.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import dashscope
  2. class QwenClient:
  3. def __init__(self):
  4. self.api_key = "sk-1022fe8e15ff4e0e9abc20541b281165"
  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. # result = client.chat(user_prompt="hello")
  76. # print(result)
  77. user_prompt = """你是一个专业的信息搜索专家,负责从网络中搜索某个工具的页面操作路径
  78. **名词解释**
  79. 页面操作路径:表示在网页上使用某个工具完成某个功能需要进行的必要操作。通常是分步骤操作,最后形成一个完整的页面操作路径。
  80. 比如:1. 打开xxx网站, 2. 输入xxx提示词, 3. 点击确认按钮, 4. 等待图片生成完成, 5. 返回图片的url
  81. **任务目标**
  82. 搜索并整理 新红热搜词榜单功能 的页面操作路径
  83. **数据要求**
  84. - 操作页面必须是官方网站,排除任何第三方网站、移动端APP、PC软件
  85. - 页面操作路径数据最好有详细的操作步骤,如果没有,也可以是简单的操作步骤描述。步骤中如果包含账号注册/登录,需要去除,我们假设网站已经成功登录了
  86. - 页面操作路径数据要排除关于API的调用数据
  87. - 保留原始链接用于追溯,输出在 content_link 字段
  88. - 整理工具的核心功能名称和功能描述
  89. - 如果有多份数据,保留和任务目标最相关的一份数据即可
  90. **输出要求:**
  91. 严格按照以下JSON格式输出,不添加任何其他文字说明:
  92. {
  93. "content_link": "原始链接地址",
  94. "功能名称": "具体功能名称",
  95. "功能描述": "功能用途和作用描述",
  96. "页面操作路径": "完整的页面操作路径"
  97. }"""
  98. # user_prompt = "请搜索 白瓜AI 官网"
  99. result = client.search_and_chat(user_prompt=user_prompt, search_strategy="agent")
  100. print("="*20 + "搜索结果" + "="*20)
  101. for web in result["search_results"]:
  102. print(f"[{web['index']}]: [{web['title']}]({web['url']})")
  103. print("="*20 + "回复内容" + "="*20)
  104. print(result["content"])
  105. except Exception as e:
  106. print(f"错误: {e}")