qwen.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import dashscope
  2. class QwenClient:
  3. def __init__(self):
  4. self.api_key = "sk-1022fe8e15ff4e0e9abc20541b281165"
  5. def chat(
  6. self,
  7. model="qwen3-max",
  8. system_prompt="You are a helpful assistant.",
  9. user_prompt="",
  10. ):
  11. """
  12. 普通聊天,不使用搜索功能
  13. Args:
  14. model: 模型名称,默认为qwen3-max
  15. system_prompt: 系统提示词
  16. user_prompt: 用户提示词
  17. Returns:
  18. str: AI回复内容
  19. """
  20. try:
  21. messages = [
  22. {"role": "system", "content": system_prompt},
  23. {"role": "user", "content": user_prompt},
  24. ]
  25. response = dashscope.Generation.call(
  26. api_key=self.api_key,
  27. model=model,
  28. messages=messages,
  29. result_format="message",
  30. )
  31. if response.status_code != 200:
  32. raise Exception(f"API调用失败: {response.message}")
  33. return response["output"]["choices"][0]["message"]["content"]
  34. except Exception as e:
  35. raise Exception(f"QwenClient chat失败: {str(e)}")
  36. def search_and_chat(
  37. self,
  38. model="qwen3-max",
  39. system_prompt="You are a helpful assistant.",
  40. user_prompt="",
  41. search_strategy="max",
  42. ):
  43. """
  44. 搜索并聊天
  45. Args:
  46. model: 模型名称,默认为qwen3-max
  47. system_prompt: 系统提示词
  48. user_prompt: 用户提示词
  49. search_strategy: 搜索策略,可选值: turbo, max, agent
  50. Returns:
  51. dict: 包含回复内容和搜索结果
  52. """
  53. try:
  54. messages = [
  55. {"role": "system", "content": system_prompt},
  56. {"role": "user", "content": user_prompt},
  57. ]
  58. response = dashscope.Generation.call(
  59. api_key=self.api_key,
  60. model=model,
  61. messages=messages,
  62. enable_search=True,
  63. search_options={
  64. "forced_search": True,
  65. "enable_source": True,
  66. "search_strategy": search_strategy,
  67. },
  68. result_format="message",
  69. )
  70. if response.status_code != 200:
  71. raise Exception(f"API调用失败: {response.message}")
  72. content = response["output"]["choices"][0]["message"]["content"]
  73. search_results = []
  74. if hasattr(response.output, "search_info") and response.output.search_info:
  75. search_results = response.output.search_info.get("search_results", [])
  76. return {"content": content, "search_results": search_results}
  77. except Exception as e:
  78. raise Exception(f"QwenClient search_and_chat失败: {str(e)}")
  79. if __name__ == "__main__":
  80. client = QwenClient()
  81. # 测试
  82. try:
  83. # result = client.chat(user_prompt="hello")
  84. # print(result)
  85. user_prompt = """你是一个专业的信息搜索专家,负责从网络中搜索某个工具的页面操作路径
  86. **名词解释**
  87. 页面操作路径:表示在网页上使用某个工具完成某个功能需要进行的必要操作。通常是分步骤操作,最后形成一个完整的页面操作路径。
  88. 比如:1. 打开xxx网站, 2. 输入xxx提示词, 3. 点击确认按钮, 4. 等待图片生成完成, 5. 返回图片的url
  89. **任务目标**
  90. 搜索并整理 新红热搜词榜单功能 的页面操作路径
  91. **数据要求**
  92. - 操作页面必须是官方网站,排除任何第三方网站、移动端APP、PC软件
  93. - 页面操作路径数据最好有详细的操作步骤,如果没有,也可以是简单的操作步骤描述。步骤中如果包含账号注册/登录,需要去除,我们假设网站已经成功登录了
  94. - 页面操作路径数据要排除关于API的调用数据
  95. - 保留原始链接用于追溯,输出在 content_link 字段
  96. - 整理工具的核心功能名称和功能描述
  97. - 如果有多份数据,保留和任务目标最相关的一份数据即可
  98. **输出要求:**
  99. 严格按照以下JSON格式输出,不添加任何其他文字说明:
  100. {
  101. "content_link": "原始链接地址",
  102. "功能名称": "具体功能名称",
  103. "功能描述": "功能用途和作用描述",
  104. "页面操作路径": "完整的页面操作路径"
  105. }"""
  106. # user_prompt = "请搜索 白瓜AI 官网"
  107. result = client.search_and_chat(
  108. user_prompt=user_prompt, search_strategy="agent"
  109. )
  110. print("=" * 20 + "搜索结果" + "=" * 20)
  111. for web in result["search_results"]:
  112. print(f"[{web['index']}]: [{web['title']}]({web['url']})")
  113. print("=" * 20 + "回复内容" + "=" * 20)
  114. print(result["content"])
  115. except Exception as e:
  116. print(f"错误: {e}")