【LLM-Agent】Qwen-Agent智能体框架使用
note
- 核心功能:函数调用、代码解释器、多模态处理、记忆能力
- Qwen-Agent接入MCP的原理采用
stdio
开发模式,将mcp服务作为Qwen-Agent应用的子进程, Qwen-Agent作为客户端与子进程服务通信。
文章目录
- note
- 一、Qwen-Agent框架
- 二、相关实践
- 三、应用场景
- 四、MCP的使用栗子
- 1、sqlite数据库小助手
- 2、旅行规划
- 3、思维导图生成
- 五、为Agent快速部署Gradio Demo
- Reference
一、Qwen-Agent框架
Qwen-Agent是一个专门设计用于开发基于大型语言模型(LLM)的应用程序的框架。它不仅支持指令遵循、工具使用、规划和记忆能力,还能够处理从8K到100万tokens的文档,超越了传统长上下文模型的限制。这意味着开发者可以利用Qwen-Agent构建出能够理解和生成自然语言、执行复杂任务的智能代理应用。
核心功能:
- 更强的工具调用(Function Calling)能力:框架支持智能体自动调用外部工具或函数,包括内置的代码解释器、浏览器助手等,也支持开发者自定义工具,扩展智能体的能力。
- 便捷的MCP工具接入流程:最新版的Qwen-Agent已经集成了MCP工具接入流程,我们仅需写入MCP配置,即可在Qwen-Agent中调用MCP工具
- 规划与记忆能力: 智能体具备任务规划能力,能够根据用户需求自动制定执行步骤。同时,具备上下文记忆功能,能在对话中保持状态,提供连贯的交互体验。
- 长文本处理与 RA: Qwen-Agent 集成了检索增强生成(RAG)机制,支持处理从 8K 到 100 万 tokens 的长文档,通过文档分块和相关性检索,提升上下互与展示
- UI前端交互与展示
代码示例如下,定义一个图像生成工具my_image_gen
,然后定义智能体后进行对话:
import pprint
import urllib.parse
import json5
from qwen_agent.agents import Assistant
from qwen_agent.tools.base import BaseTool, register_tool
from qwen_agent.utils.output_beautify import typewriter_print# 步骤 1(可选):添加一个名为 `my_image_gen` 的自定义工具。
@register_tool('my_image_gen')
class MyImageGen(BaseTool):# `description` 用于告诉智能体该工具的功能。description = 'AI 绘画(图像生成)服务,输入文本描述,返回基于文本信息绘制的图像 URL。'# `parameters` 告诉智能体该工具有哪些输入参数。parameters = [{'name': 'prompt','type': 'string','description': '期望的图像内容的详细描述','required': True}]def call(self, params: str, **kwargs) -> str:# `params` 是由 LLM 智能体生成的参数。prompt = json5.loads(params)['prompt']prompt = urllib.parse.quote(prompt)return json5.dumps({'image_url': f'https://image.pollinations.ai/prompt/{prompt}'},ensure_ascii=False)# 步骤 2:配置您所使用的 LLM。
llm_cfg = {# 使用 DashScope 提供的模型服务:'model': 'qwen-max-latest','model_type': 'qwen_dashscope',# 'api_key': 'YOUR_DASHSCOPE_API_KEY',# 如果这里没有设置 'api_key',它将读取 `DASHSCOPE_API_KEY` 环境变量。'api_key': 'xxx',# 使用与 OpenAI API 兼容的模型服务,例如 vLLM 或 Ollama:# 'model': 'Qwen2.5-7B-Instruct',# 'model_server': 'http://localhost:8000/v1', # base_url,也称为 api_base# 'api_key': 'EMPTY',# (可选) LLM 的超参数:'generate_cfg': {'top_p': 0.8}
}# 步骤 3:创建一个智能体。这里我们以 `Assistant` 智能体为例,它能够使用工具并读取文件。
system_instruction = '''在收到用户的请求后,你应该:
- 首先绘制一幅图像,得到图像的url,
- 然后运行代码`request.get`以下载该图像的url,
- 最后从给定的文档中选择一个图像操作进行图像处理。
用 `plt.show()` 展示图像。
你总是用中文回复用户。'''
tools = ['my_image_gen', 'code_interpreter'] # `code_interpreter` 是框架自带的工具,用于执行代码。
# files = ['./examples/resource/doc.pdf'] # 给智能体一个 PDF 文件阅读。
files = ['/Users/guomiansheng/Desktop/LLM/llm_app/Qwen-Agent/examples/resource/doc.pdf'] # 给智能体一个 PDF 文件阅读。bot = Assistant(llm=llm_cfg,system_message=system_instruction,function_list=tools,files=files)# 步骤 4:作为聊天机器人运行智能体。
messages = [] # 这里储存聊天历史。
while True:# 例如,输入请求 "绘制一只狗并将其旋转 90 度"。query = input('\n用户请求: ')# 将用户请求添加到聊天历史。messages.append({'role': 'user', 'content': query})response = []response_plain_text = ''print('机器人回应:')for response in bot.run(messages=messages):# 流式输出。response_plain_text = typewriter_print(response, response_plain_text)# 将机器人的回应添加到聊天历史。messages.extend(response)
注意:typewriter_print
用于格式化和打印消息,会处理函数调用和普通对话的不同执行逻辑(Function Calling),同时对于推理类模型,会判断消息中是否包含 reasoning_content,如果存在,则将其添加到 content 列表中,并在前面加上 THOUGHT_S(表示思考的符号或字符串),从而支持推理类模型和对话模型的不同输入输出形式。
二、相关实践
链接:https://github.com/QwenLM/Qwen-Agent
通过三个基于Qwen-Agent的CookBook示例,全面展示Qwen3的Agent能力:
(1)1️⃣cookbook_database_manipulation实现自然语言驱动的数据库操作闭环(文件解析→数据入库→智能查询)
https://github.com/QwenLM/Qwen-Agent/blob/main/examples/cookbook_database_manipulation.ipynb
(2)2️⃣cookbook_drive_guide深度融合云端高德API提供实时地理智能服务(路径规划/旅游推荐)
https://github.com/QwenLM/Qwen-Agent/blob/main/examples/cookbook_drive_guide.ipynb
(3)3️⃣cookbook_mind_map则能一键将文档转化为结构化思维导图。
https://github.com/QwenLM/Qwen-Agent/blob/main/examples/cookbook_mind_map.ipynb
cookbook对应的内容:
Qwen-Agent:https://github.com/QwenLM/Qwen-Agent
三、应用场景
客户服务:作为聊天机器人,提供24/7的客户咨询服务,处理常见问题和查询。
个人助理:帮助用户管理日程、提醒事项、预订服务等日常任务。
教育和学习:作为虚拟助教,提供个性化学习建议,解答学生问题。
内容创作:辅助写作、编辑和内容生成,包括文章、报告和创意写作。
技术支持:提供技术问题的解决方案,帮助用户解决软件或硬件问题。
数据分析:帮助分析和解释复杂的数据集,提供商业洞察。
四、MCP的使用栗子
选择所需要的工具:https://github.com/modelcontextprotocol/servers
配置对应环境。
Qwen-Agent接入MCP的原理采用stdio
开发模式,将mcp服务作为Qwen-Agent应用的子进程, Qwen-Agent作为客户端与子进程服务通信。
Qwen-Agent中MCP调用格式:
{"mcpServers": {"memory": {"command": "npx","args": ["-y", "@modelcontextprotocol/server-memory"]},"filesystem": {"command": "npx","args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]},"sqlite" : {"command": "uvx","args": ["mcp-server-sqlite","--db-path","test.db"]}}
}
运行下面例子需要额外安装的依赖有:
# Node.js(访问 Node.js 官网下载并安装最新版本, https://nodejs.org/)
# uv 0.4.18 或更高版本 (使用 uv --version 检查)
# Git (git --version 检查)
# SQLite (sqlite3 --version 检查)# 对于 macOS 用户,可以使用 Homebrew 安装这些组件:
brew install uv git sqlite3# 对于 Windows 用户,可以使用 winget 安装这些组件:
winget install --id=astral-sh.uv -e
winget install git.git sqlite.sqlite
1、sqlite数据库小助手
【栗子】Qwen-Agent+Qwen3开发一个sqlite数据库小助手,Qwen-Agent接入mcp-server-sqliteMCP服务器,能够理解自然语言并依据语言内容调用mcp-server-sqlite服务端的功能函数完成对sqlite数据库的相关操作。
(1)安装MCP服务:pip install uvx
(2)导入相关包并初始化Assistant类,同时接入mcp-server-sqliteMCP服务端, 接入mcp需要先定义一个tools数组存放json schema格式的mcp服务器配置
(3)Qwen-Agent检测到用户请求中要创建学生表并插入数据,Qwen3模型对mcp-server-sqlite服务端的函数理解生成思考过程,利用sqlite-create_table
创建表,并使用sqlite-write_query插入数据。
from qwen_agent.agents import Assistant
from qwen_agent.utils.output_beautify import typewriter_printdef init_agent_service():llm_cfg={'model': 'qwen3-235b-a22b','model_server': 'dashscope','api_key': 'xxx','generate_cfg':{'top_p': 0.8}}# 定义MCP服务配置,优点类似Function Calling调用的JSON Schema格式tools = [{"mcpServers": {"sqlite": {"command": "uvx","args": ["mcp-server-sqlite","--db-path","test.db"]}}}]bot = Assistant(llm=llm_cfg,name='数据库管理员',description='你是一位数据库管理员,具有对本地数据库的增删改查能力',system_message='你扮演一个数据库助手,你具有查询数据库的能力',function_list=tools,)return botdef run_query(query=None):# 定义数据库助手bot = init_agent_service()# 执行对话逻辑messages = []messages.append({'role': 'user', 'content': [{'text': query}]})# 跟踪前一次的输出,用于增量打印previous_text = ""print('数据库管理员: ', end='', flush=True)for response in bot.run(messages):previous_text = typewriter_print(response, previous_text)if __name__ == '__main__':query = '帮我创建一个学生表,表名是students,包含id, name, age, gender, score字段,然后插入一条数据,id为1,name为张三,age为20,gender为男,score为95'run_query(query)
从下面结果中看使用了sqlite-create_table
工具建表,sqlite-write_query
往表中插入数据:
2、旅行规划
使用高德MCP:
tools = [{"mcpServers": {# enumeration of mcp server configs"amap-amap-sse": {"https://mcp.amap.com/sse?key=YOUR_KEY" # **fill your amap mcp key**}}}
]
3、思维导图生成
tools = [{"mcpServers": {"filesystem": {"command": "npx","args": ["-y","@modelcontextprotocol/server-filesystem",'.',]},"mindmap": {"command": "uvx","args": ["mindmap-mcp-server", "--return-type", "filePath"]}}
}]
五、为Agent快速部署Gradio Demo
使用GUI接口:
from qwen_agent.gui import WebUI
WebUI(bot).run() # bot is the agent defined in the above code, we do not repeat the definition here for saving space.
Reference
[1] https://github.com/QwenLM/Qwen-Agent
[2] 解锁 Qwen3 的Agent能力,CookBook
[3] 阿里 Qwen-Agent:开源Agent开发框架简介
[4] 官方技术文档:https://qwen.readthedocs.io/zh-cn/latest/framework/qwen_agent.html
[5] Qwen3+Qwen Agent +MCP智能体开发实战(二)—10分钟打造"MiniManus"
[6] Qwen3+Qwen Agent 智能体开发实战,打开大模型MCP工具新方式!(一)
[7] 百度搜索开放平台网址:https://sai.baidu.com
[8] MCP工具集合:https://github.com/modelcontextprotocol/servers
[9] Qwen Agent | MCP & Function Calling流程解读
[10] Qwen Agent | 将思考「工具化」提升规划能力
[11] 为什么说Agent是一场持久战?Kimi技术大牛的深入分析
[12] https://github.com/YuChenSSR/mindmap-mcp-server
[13] 用 AI + 高德地图 MCP,3 小时做出杭州美食地图
[14] qwen框架官方文档
[15] qwen-agent官方开发文档:https://github.com/QwenLM/Qwen-Agent/tree/main/docs