【LLM】Qwen-Agent框架使用和源码解读
核心功能:函数调用、代码解释器、多模态处理、记忆能力Qwen-Agent接入MCP的原理采用stdio开发模式,将mcp服务作为Qwen-Agent应用的子进程, Qwen-Agent作为客户端与子进程服务通信。文章目录note一、Qwen-Agent框架1、框架介绍2、相关实践和应用场景二、MCP的使用栗子1、sqlite数据库小助手2、旅行规划3、思维导图生成三、Qwen-Agent框架源码解
note
- 核心功能:函数调用、代码解释器、多模态处理、记忆能力
- Qwen-Agent接入MCP的原理采用
stdio
开发模式,将mcp服务作为Qwen-Agent应用的子进程, Qwen-Agent作为客户端与子进程服务通信。
文章目录
一、Qwen-Agent框架
1、框架介绍
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(表示思考的符号或字符串),从而支持推理类模型和对话模型的不同输入输出形式。
2、相关实践和应用场景
链接: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_print
def 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 bot
def 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"]
}
}
}]
三、Qwen-Agent框架源码解读
1、整体架构图
- 工具系统:
- 核心工具 :用于 Python 执行的 CodeInterpreter、用于 RAG 的内存 、文档处理工具
- 外部集成 :用于外部工具服务器的 MCP(模型上下文协议)
- 自定义工具 :可通过
BaseTool
继承和@register_tool
装饰器进行扩展
相关核心类介绍:
FnCallAgent
类是大多数实用代理的基础,通过 Memory 类qwen_agent/agents/fncall_agent.py
提供工具集成和内存功能- 通过
BaseChatModel
抽象为各种 LLM 提供者提供了统一的接口:
Agent Type (代理类型) | Purpose (目的) | Key Features (主要特点) |
---|---|---|
Agent | Base abstract class (基本抽象类) | Message handling, tool detection (消息处理、工具检测) |
FnCallAgent | Function calling agent (函数调用代理) | Tool integration, memory management (工具集成、内存管理) |
Assistant | RAG-enabled agent (启用RAG的代理) | Document processing, knowledge retrieval (文档处理、知识检索) |
MultiAgentHub | Multi-agent coordination (多智能体协调) | Agent orchestration, communication (代理编排、通信) |
2、Agent基类
(1)Agent
基类的作用如下图:Agent基类及其子类的关系、Agent基类和其他模块的关系
(2)Agent
基类和其他agent子类的关系图:
(3)Agent Lifecycle生命周期和消息处理:
UML图,虚线返回箭头表示返回结果
3、函数调用和工具集成
Qwen-Agent 通过可自定义的提示模板为并行函数调用提供原生支持。系统使用基于注册表的方法进行工具管理 qwen_agent/agents/fncall_agent.py,83-120
fc涉及的prompt参考:qwen_agent/llm/fncall_prompts
4、RAG 和内存系统
Memory 类提供文档处理和检索功能,自动与文件访问工具
集成 qwen_agent/agents/fncall_agent.py 114-120
文件:qwen_agent/memory/memory.py
- 使用可配置的页面大小进行文档解析和分块
- 结合关键词和向量搜索的混合搜索
- 自动处理具有启用 file_access 工具的代理
5、多代理协调
通过 MultiAgentHub 和专门的实现(如 GroupChat 示例/group_chat_demo.py
87-160)支持复杂的多代理场景:
- 基于mention-based通信进行agent编排
- 具有人机交互支持的基于角色的代理配置
- 动态agent创建和配置管理
其他:
为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
[16] 使用Qwen-Agent将上下文记忆扩展到百万量级. Qwen官方技术博客
[17] Generalizing an LLM from 8k to 1M Context using Qwen-Agent
更多推荐
所有评论(0)