个人随笔
目录
Agent学习(6):Qwen-Agent 使用
2026-02-04 20:34:41

Qwen-Agent 是阿里通义千问团队开源的基于 Qwen 大语言模型的 Agent 开发框架,为开发者提供构建具备指令遵循、工具调用、任务规划与记忆管理能力的 AI 智能体应用的完整能力栈,也是 Qwen Chat 的后端支撑框架。

之前我们用LangChain搭建了一个简单的RAG例子,下面用Qwen-Agent来搭建RAG,这里举了两个例子。

1、环境安装

这里用conda新建一个环境

  1. conda create -n qwen-agent python=3.11
  2. conda activate qwen-agent

然后安装依赖

  1. pip install -U "qwen-agent[rag,code_interpreter,gui,mcp]"

或者,使用 pip install -U qwen-agent 来安装最小依赖。

  1. 可使用双括号指定如下的可选依赖:
  2. [gui] 用于提供基于 Gradio GUI 支持;
  3. [rag] 用于支持 RAG
  4. [code_interpreter] 用于提供代码解释器相关支持;
  5. [mcp] 用于支持 MCP

这里只是简单使用,就直接安装全部依赖了。

2、例子1:简单的使用

  1. import logging
  2. import io
  3. import os
  4. from qwen_agent.agents import Assistant
  5. # 创建一个自定义的日志处理器来捕获日志输出
  6. class LogCapture:
  7. def __init__(self):
  8. self.log_capture_string = io.StringIO()
  9. self.log_handler = logging.StreamHandler(self.log_capture_string)
  10. self.log_handler.setLevel(logging.INFO)
  11. self.log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  12. self.log_handler.setFormatter(self.log_formatter)
  13. # 获取 qwen_agent 的日志记录器
  14. self.logger = logging.getLogger('qwen_agent_logger')
  15. self.logger.setLevel(logging.INFO)
  16. self.logger.addHandler(self.log_handler)
  17. # 也可以捕获根日志记录器的输出
  18. self.root_logger = logging.getLogger()
  19. self.root_logger.setLevel(logging.INFO)
  20. self.root_logger.addHandler(self.log_handler)
  21. def get_log(self):
  22. return self.log_capture_string.getvalue()
  23. def clear_log(self):
  24. self.log_capture_string.truncate(0)
  25. self.log_capture_string.seek(0)
  26. # 初始化日志捕获器
  27. log_capture = LogCapture()
  28. # 步骤 1:配置您所使用的 LLM。
  29. llm_cfg = {
  30. # 使用 DashScope 提供的模型服务:
  31. 'model': 'qwen-max',
  32. 'model_server': 'dashscope',
  33. 'api_key': os.getenv("DASHSCOPE_API_KEY"),
  34. 'generate_cfg': {
  35. 'top_p': 0.8
  36. }
  37. }
  38. # 步骤 2:创建一个智能体。这里我们以 `Assistant` 智能体为例,它能够使用工具并读取文件。
  39. system_instruction = ''
  40. tools = []
  41. files = ['G:\\AI\\workspace\\vscode\\202601\\123.pdf'] # 给智能体一个 PDF 文件阅读。
  42. # 清除之前的日志
  43. log_capture.clear_log()
  44. # 创建智能体
  45. bot = Assistant(llm=llm_cfg,
  46. system_message=system_instruction,
  47. function_list=tools,
  48. files=files)
  49. # 步骤 3:作为聊天机器人运行智能体。
  50. messages = [] # 这里储存聊天历史。
  51. query = "客户经理被客户投诉一次,扣多少分?"
  52. # 将用户请求添加到聊天历史。
  53. messages.append({'role': 'user', 'content': query})
  54. response = []
  55. current_index = 0
  56. # 运行智能体
  57. for response in bot.run(messages=messages):
  58. # 在第一次响应时,分析日志以查找召回的文档内容
  59. if current_index == 0:
  60. # 获取日志内容
  61. log_content = log_capture.get_log()
  62. print("\n===== 从日志中提取的检索信息 =====")
  63. # 查找与检索相关的日志行
  64. retrieval_logs = [line for line in log_content.split('\n')
  65. if any(keyword in line.lower() for keyword in
  66. ['retriev', 'search', 'chunk', 'document', 'ref', 'token'])]
  67. # 打印检索相关的日志
  68. for log_line in retrieval_logs:
  69. print(log_line)
  70. # 尝试从日志中提取文档内容
  71. # 通常在日志中会有类似 "retrieved document: ..." 或 "content: ..." 的行
  72. content_logs = [line for line in log_content.split('\n')
  73. if any(keyword in line.lower() for keyword in
  74. ['content', 'text', 'document', 'chunk'])]
  75. print("\n===== 可能包含文档内容的日志 =====")
  76. for log_line in content_logs:
  77. print(log_line)
  78. print("===========================\n")
  79. current_response = response[0]['content'][current_index:]
  80. current_index = len(response[0]['content'])
  81. print(current_response, end='')
  82. # 将机器人的回应添加到聊天历史。
  83. messages.extend(response)
  84. # 运行结束后,分析完整的日志
  85. print("\n\n===== 运行结束后的完整日志分析 =====")
  86. log_content = log_capture.get_log()
  87. # 尝试从日志中提取更多信息
  88. print("\n1. 关键词提取:")
  89. keyword_logs = [line for line in log_content.split('\n') if 'keywords' in line.lower()]
  90. for log_line in keyword_logs:
  91. print(log_line)
  92. print("\n2. 文档处理:")
  93. doc_logs = [line for line in log_content.split('\n') if 'doc' in line.lower() or 'chunk' in line.lower()]
  94. for log_line in doc_logs:
  95. print(log_line)
  96. print("\n3. 检索相关:")
  97. retrieval_logs = [line for line in log_content.split('\n') if 'retriev' in line.lower() or 'search' in line.lower() or 'ref' in line.lower()]
  98. for log_line in retrieval_logs:
  99. print(log_line)
  100. print("\n4. 可能包含文档内容的日志:")
  101. content_logs = [line for line in log_content.split('\n') if 'content:' in line.lower() or 'text:' in line.lower()]
  102. for log_line in content_logs:
  103. print(log_line)
  104. print("===========================\n")

3、例子2:RAG助手

  1. import logging
  2. import io
  3. import os
  4. from qwen_agent.agents import Assistant
  5. def get_file_list(folder_path):
  6. # 初始化文件列表
  7. file_list = []
  8. # 遍历文件夹
  9. for root, dirs, files in os.walk(folder_path):
  10. for file in files:
  11. # 获取文件的完整路径
  12. file_path = os.path.join(root, file)
  13. # 将文件路径添加到列表中
  14. file_list.append(file_path)
  15. return file_list
  16. # 步骤 2:创建一个智能体。这里我们以 `Assistant` 智能体为例,它能够使用工具并读取文件。
  17. system_instruction = ''
  18. tools = []
  19. file_list = get_file_list('G:\\Video\\电影\\聚客第6期\\L1\\4_RAG高级技术\\第3章_RAG高级技术\\docs')
  20. print(file_list)
  21. # 步骤 1:配置您所使用的 LLM
  22. llm_cfg = {
  23. # 使用 DashScope 提供的模型服务:
  24. 'model': 'qwen-max',
  25. 'model_server': 'dashscope',
  26. 'api_key': os.getenv('DASHSCOPE_API_KEY'),
  27. # 如果这里没有设置 'api_key',它将读取 `DASHSCOPE_API_KEY` 环境变量。
  28. # 使用与 OpenAI API 兼容的模型服务,例如 vLLM 或 Ollama:
  29. # 'model': 'Qwen2-7B-Chat',
  30. # 'model_server': 'http://localhost:8000/v1', # base_url,也称为 api_base
  31. # 'api_key': 'EMPTY',
  32. # (可选) LLM 的超参数:
  33. 'generate_cfg': {
  34. 'top_p': 0.8
  35. }
  36. }
  37. # 步骤 2:创建一个智能体。这里我们以 `Assistant` 智能体为例,它能够使用工具并读取文件。
  38. system_instruction = '你是一位保险专家,根据你的经验来精准的回答用户提出的问题'
  39. tools = []
  40. bot = Assistant(llm=llm_cfg,
  41. system_message=system_instruction,
  42. function_list=tools,
  43. files=file_list)
  44. # 步骤 3:作为聊天机器人运行智能体。
  45. messages = [] # 这里储存聊天历史。
  46. while True:
  47. query = input('用户请求: ')
  48. if query == '-1':
  49. break
  50. # 将用户请求添加到聊天历史。
  51. messages.append({'role': 'user', 'content': query})
  52. response = []
  53. current_index = 0
  54. for response in bot.run(messages=messages):
  55. # 流式输出
  56. current_response = response[0]['content'][current_index:]
  57. current_index = len(response[0]['content'])
  58. print(current_response, end='')
  59. # 将机器人的回应添加到聊天历史。
  60. messages.extend(response)
 4

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2