Qwen-Agent:通义千问官方智能体框架完整中文说明
官方信息
| 项目 | 说明 |
|---|---|
| 项目名称 | Qwen-Agent |
| 开源仓库 | QwenLM/Qwen-Agent |
| 所属团队 | 阿里巴巴通义千问(Qwen)团队 |
| 开源协议 | Apache License 2.0 |
| 安装方式 | PyPI 包 qwen-agent,或源码 pip install -e |
| 模型服务 | 阿里云 DashScope 云端 API,或自建 OpenAI 兼容服务(vLLM / Ollama) |
| 官方文档 | Qwen-Agent 文档站 |
| 在线体验 | Qwen Chat(Qwen-Agent 即其后端) |

项目背景
Qwen-Agent 是通义千问团队官方推出的智能体开发框架,它充分利用 Qwen 系列大模型在指令遵循、工具调用、任务规划和长期记忆四个方面的能力,帮助开发者快速搭建基于大语言模型的应用。框架开箱即用地内置了多个示例应用:浏览器助手(Browser Assistant / BrowserQwen)、代码解释器(Code Interpreter)以及可高度自定义的自定义助手(Custom Assistant)。目前,Qwen Chat 的智能体后端正是由 Qwen-Agent 承担,说明该框架已经在大规模生产环境中经过验证。
除了面向终端用户的应用,Qwen-Agent 还提供了一整套原子组件与高层组件:底层包括继承自 BaseChatModel 的各类大模型封装(内置函数调用能力)和继承自 BaseTool 的工具基类;高层则提供继承自 Agent 的现成智能体实现,开发者可以直接组装,也可以自行继承扩展。
从能力覆盖上看,Qwen-Agent 打通了智能体应用的完整链路:在模型层,它同时支持 DashScope 云端 API 和任何 OpenAI 兼容的自建服务,你既可以零部署直接用通义千问官方模型起步,也可以用 vLLM、Ollama 把开源 Qwen 模型部署在自己的显卡或本机上;在工具层,它内置了代码解释器、文件读取、RAG 检索等常用工具,同时支持通过 MCP 协议接入社区的海量工具服务器;在交互层,它提供了从命令行聊天循环到 Gradio Web UI 的多种运行方式;在评测层,团队还开源了 DeepPlanning 智能体评测基准,帮助你量化自己搭建的智能体到底好不好用。换句话说,这个框架既是一个可以直接上手做应用的工具包,也是一套让你理解"大模型智能体该怎么搭"的参考实现。
近期动态(News)
- 2026 年 2 月 16 日:开源 Qwen3.5 模型,对应示例见
examples/assistant_qwen3.5.py。 - 2026 年 1 月 27 日:开源智能体评测基准 DeepPlanning,并上线 Qwen-Agent 官方文档。
- 2025 年 9 月 23 日:新增 Qwen3-VL 工具调用示例
examples/cookbook_think_with_images.ipynb,支持图片放大、以图搜图、网页搜索等多模态工具。 - 2025 年 7 月 23 日:新增 Qwen3-Coder 工具调用示例
examples/assistant_qwen3_coder.py;支持原生 API 工具调用接口,例如直接使用 vLLM 内置的工具调用解析。 - 2025 年 5 月 1 日:新增 Qwen3 工具调用示例
examples/assistant_qwen3.py,并补充 MCP 系列 cookbook。 - 2025 年 3 月 18 日:支持
reasoning_content字段;默认函数调用模板调整为nous_fncall_prompt.py,适用于 Qwen2.5 系列通用模型与 QwQ-32B。 - 2025 年 3 月 7 日:新增 QwQ-32B 工具调用示例
examples/assistant_qwq.py,支持并行、多步、多轮工具调用。 - 2024 年 12 月 3 日:GUI 升级为基于 Gradio 5 的版本,注意 GUI 要求 Python 3.10 及以上。
- 2024 年 9 月 18 日:新增 Qwen2.5-Math 示例
examples/tir_math.py,展示工具集成推理(Tool-Integrated Reasoning)能力;注意其 Python 执行器未做沙箱隔离,仅限本地测试,不可用于生产。
环境要求与安装
安装稳定版(PyPI)
从 PyPI 安装稳定版本,可选依赖通过方括号指定:
pip install -U "qwen-agent[gui,rag,code_interpreter,mcp]"
# 或者仅安装最小依赖:
# pip install -U qwen-agent
双括号内的可选依赖含义如下:
[gui]:基于 Gradio 的图形界面支持;[rag]:检索增强生成(RAG)支持;[code_interpreter]:代码解释器支持;[mcp]:Model Context Protocol 支持。
安装开发版(源码)
从源码安装最新开发版本:
git clone https://github.com/QwenLM/Qwen-Agent.git
cd Qwen-Agent
pip install -e ."[gui,rag,code_interpreter,mcp]"
# 或者仅安装最小依赖:
# pip install -e ./
模型服务准备
使用 Qwen-Agent 之前必须先准备好模型服务,有两种路径:
路径一:使用阿里云 DashScope 云端模型服务。 请先注册并开通阿里云 DashScope 服务,然后把环境变量 DASHSCOPE_API_KEY 设置为你自己的 DashScope API Key。具体开通步骤参考 DashScope 快速开始文档。
路径二:部署并使用自己的开源模型服务。 按照 Qwen2 仓库 README 的指引部署 OpenAI 兼容的 API 服务即可:高吞吐 GPU 场景参考 vLLM 部署章节,本地 CPU(+GPU)部署参考 Ollama 章节。
一个重要的版本参数注意事项:对于 QwQ 与 Qwen3 系列模型,使用 vLLM 时建议不要添加 --enable-auto-tool-choice 和 --tool-call-parser hermes 这两个参数,因为 Qwen-Agent 会自行解析 vLLM 返回的工具调用输出;而对于 Qwen3-Coder,则建议同时开启上述两个参数、使用 vLLM 内置的工具解析,并配合 use_raw_api 参数使用。
这里需要解释一下背后的原因:Qwen-Agent 历史上是通过自己维护的函数调用模板(即 prompt 拼装方式)来让模型输出工具调用的,因此用 vLLM 启动 Qwen3 时,不能让 vLLM 再用它自己的 hermes 模板去二次解析,否则两边解析逻辑会冲突;而 Qwen3-Coder 这类模型训练时就遵循了原生工具调用格式,所以反而应该打开 vLLM 的自动工具选择与解析,再把 use_raw_api 设为 True,让框架直接透传模型 API 的原生 tool_calls 字段。这也是上面 FAQ 中 use_raw_api 配置项的实际用途。
部署与开发你的第一个智能体
Qwen-Agent 的组件体系可以分为两层:原子组件包括 LLM(继承自 BaseChatModel,自带函数调用能力)和工具(继承自 BaseTool);高层组件是继承自 Agent 的各类智能体。下面的完整示例演示了如何创建一个能读取 PDF、使用工具、并挂接自定义工具的智能体。
第一步(可选):注册自定义工具
通过 @register_tool 装饰器把一个自定义工具注册到框架中。每个工具需要声明 description(告诉智能体这个工具做什么)和 parameters(告诉智能体工具需要哪些入参),并实现 call 方法:
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
# Step 1 (Optional): Add a custom tool named `my_image_gen`.
@register_tool('my_image_gen')
class MyImageGen(BaseTool):
# The `description` tells the agent the functionality of this tool.
description = 'AI painting (image generation) service, input text description, and return the image URL drawn based on text information.'
# The `parameters` tell the agent what input parameters the tool has.
parameters = [{
'name': 'prompt',
'type': 'string',
'description': 'Detailed description of the desired image content, in English',
'required': True
}]
def call(self, params: str, **kwargs) -> str:
# `params` are the arguments generated by the LLM agent.
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)
在这个例子里,my_image_gen 工具接收一段英文描述,返回根据描述生成的图片 URL。
第二步:配置大模型
用字典配置你正在使用的 LLM。既可以接 DashScope 云端服务,也可以接 OpenAI 兼容的自建服务(如 vLLM、Ollama):
llm_cfg = {
# Use the model service provided by DashScope:
'model': 'qwen-max-latest',
'model_type': 'qwen_dashscope',
# 'api_key': 'YOUR_DASHSCOPE_API_KEY',
# It will use the `DASHSCOPE_API_KEY' environment variable if 'api_key' is not set here.
# Use a model service compatible with the OpenAI API, such as vLLM or Ollama:
# 'model': 'Qwen2.5-7B-Instruct',
# 'model_server': 'http://localhost:8000/v1', # base_url, also known as api_base
# 'api_key': 'EMPTY',
# (Optional) LLM hyperparameters for generation:
'generate_cfg': {
'top_p': 0.8
}
}
要点:如果不写 api_key,框架会自动读取 DASHSCOPE_API_KEY 环境变量;自建服务时把 model_server 指向你的 OpenAI 兼容地址,api_key 随便填一个字符串即可(如 EMPTY)。
第三步:创建智能体
这里以内置的 Assistant 智能体为例,它具备使用工具和读取文件的能力。通过 system_message 写系统指令,通过 function_list 指定可用工具,通过 files 给它一份要读的文件:
# Step 3: Create an agent. Here we use the `Assistant` agent as an example, which is capable of using tools and reading files.
system_instruction = '''After receiving the user's request, you should:
- first draw an image and obtain the image url,
- then run code `request.get(image_url)` to download the image,
- and finally select an image operation from the given document to process the image.
Please show the image using `plt.show()`.'''
tools = ['my_image_gen', 'code_interpreter'] # `code_interpreter` is a built-in tool for executing code. For configuration details, please refer to the FAQ.
files = ['./examples/resource/doc.pdf'] # Give the bot a PDF file to read.
bot = Assistant(llm=llm_cfg,
system_message=system_instruction,
function_list=tools,
files=files)
第四步:以聊天机器人方式运行
下面是一个最小的命令行对话循环:messages 保存聊天历史,每轮把用户提问追加进去,然后遍历 bot.run(messages=messages) 的流式输出来打印回复,最后把模型回复追加回历史:
# Step 4: Run the agent as a chatbot.
messages = [] # This stores the chat history.
while True:
# For example, enter the query "draw a dog and rotate it 90 degrees".
query = input('\nuser query: ')
# Append the user query to the chat history.
messages.append({'role': 'user', 'content': query})
response = []
response_plain_text = ''
print('bot response:')
for response in bot.run(messages=messages):
# Streaming output.
response_plain_text = typewriter_print(response, response_plain_text)
# Append the bot responses to the chat history.
messages.extend(response)
例如输入 "draw a dog and rotate it 90 degrees",智能体会先调用 my_image_gen 生成图片,再调用内置的 code_interpreter 工具下载图片并旋转 90 度,最后用 plt.show() 展示。
第五步(可选):一键启动 Gradio Web UI
除了用 Assistant 等现成实现,你也可以继承 Agent 类开发自己的智能体。框架还提供了便捷的 GUI 接口,一行代码即可把上面的智能体包装成 Gradio Web Demo:
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.
启动后在浏览器里即可与智能体对话。更多用法示例请参阅仓库的 examples 目录。
examples 目录是 Qwen-Agent 官方维护的"活文档",除了本文用到的基础示例,还包括:assistant_qwen3.py、assistant_qwen3_coder.py、assistant_qwen3.5.py 等各代模型的工具调用演示;assistant_qwq.py 展示 QwQ-32B 的并行、多步、多轮工具调用;tir_math.py 展示 Qwen2.5-Math 的工具集成推理;cookbook_think_with_images.ipynb 展示 Qwen3-VL 的多模态工具调用;assistant_rag.py 与 parallel_doc_qa.py 展示超长文档问答;assistant_mcp_sqlite_bot.py 展示 MCP 接入。建议读者在实际开发时,先在 examples 里找到与自己需求最接近的一个,再在其基础上改造,而不是从零开始写。
FAQ(常见问题)
如何使用代码解释器工具?
Qwen-Agent 基于本地 Docker 容器实现了一个代码解释器工具。为智能体开启内置的 code_interpreter 工具后,它就能根据具体场景自主编写代码、在隔离沙箱中安全执行,并把执行结果返回给你。这个工具的价值在于:大模型本身只能输出文本,但有了代码解释器之后,它可以像数据分析师一样,自己写 Python 去下载文件、处理图片、画图表、做数学计算,并把中间结果再喂回给模型做下一步推理,从而把"语言模型"升级成"会动手的模型"。
注意:使用该工具前请确保本机已安装并启动 Docker,首次构建容器镜像所需时间取决于你的网络情况。Docker 安装与配置请参考 Docker 官方文档。另外需要特别提醒:基于 Docker 的代码解释器只挂载指定工作目录、仅做了基础沙箱隔离,生产环境中仍需谨慎使用。
如何使用 MCP?
你可以在开源的 MCP servers 仓库上挑选需要的工具服务器,并在 Qwen-Agent 中按如下格式配置。MCP(Model Context Protocol)是一套让大模型应用统一接入外部工具与数据源的开放协议,接入它之后,Qwen-Agent 就能直接复用社区现成的记忆、文件系统、SQLite、GitHub、Slack 等上百种工具服务器,而不必自己重新实现。
{
"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"
]
}
}
}
更多细节参考官方示例 examples/assistant_mcp_sqlite_bot.py。运行该示例所需依赖为:Node.js(从官网下载最新版)、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
是否支持函数调用(工具调用)?
支持。所有 LLM 类都提供函数调用能力;此外部分智能体类本身就构建在函数调用之上,例如 FnCallAgent 和 ReActChat。当前默认的工具调用模板原生支持并行函数调用,即一轮回复中同时发起多个工具调用。
如何把 LLM 参数传给智能体?
完整的 llm_cfg 配置项说明如下:
llm_cfg = {
# The model name being used:
'model': 'qwen3-32b',
# The model service being used:
'model_type': 'qwen_dashscope',
# If 'api_key' is not set here, it will default to reading the `DASHSCOPE_API_KEY` environment variable:
'api_key': 'YOUR_DASHSCOPE_API_KEY',
# Using an OpenAI API compatible model service, such as vLLM or Ollama:
# 'model': 'qwen3-32b',
# 'model_server': 'http://localhost:8000/v1', # base_url, also known as api_base
# 'api_key': 'EMPTY',
# (Optional) LLM hyperparameters:
'generate_cfg': {
# This parameter will affect the tool-call parsing logic. Default is False:
# Set to True: when content is `<think>this is the thought</think>this is the answer`
# Set to False: when response consists of reasoning_content and content
# 'thought_in_content': True,
# tool-call template: default is nous (recommended for qwen3):
# 'fncall_prompt_type': 'nous'
# Maximum input length, messages will be truncated if they exceed this length, please adjust according to model API:
# 'max_input_tokens': 58000
# Parameters that will be passed directly to the model API, such as top_p, enable_thinking, etc., according to the API specifications:
# 'top_p': 0.8
# Using the API's native tool call interface
# 'use_raw_api': True,
}
}
逐项解释:thought_in_content 控制思维链放在 content 里还是单独的 reasoning_content 字段;fncall_prompt_type 选择工具调用模板,默认 nous(推荐配 Qwen3);max_input_tokens 限制最大输入长度,超出后消息会被截断,需按模型 API 调整;generate_cfg 里其余键会原样透传给模型 API(如 top_p、enable_thinking);use_raw_api 表示直接使用模型 API 的原生工具调用接口。
如何在 100 万 token 级超长文档上做问答?
Qwen 团队为此发布了两套方案:一套是快速 RAG 方案,另一套是成本更高但效果更强的并行文档问答智能体。在两个有挑战性的基准上,它们的效果都超过了原生长上下文模型,且效率更高;在涉及 100 万 token 上下文的"大海捞针"压力测试中表现完美。技术细节见官方博客。
这两套方案的思路差别在于:快速 RAG 方案沿用传统检索增强的路子,先把超长文档切块、做向量检索,再把相关片段喂给模型,成本低、延迟小,适合文档量大但问题比较聚焦的场景;并行文档问答方案则是让多个智能体并行地通读文档的不同部分,再汇总答案,效果更好但调用量大、成本更高。官方数据显示,二者在不依赖原生长上下文窗口的前提下,都能在百万 token 级的文档上稳定定位到"埋针"位置,这对于企业内部手册、法律法规、技术规范等超长文档问答场景有直接参考价值。
应用:浏览器助手 BrowserQwen
BrowserQwen 是基于 Qwen-Agent 构建的浏览器助手,能够代你操作网页、自动填表、抓取网页信息等。它的完整说明见仓库中的 browser_qwen.md 文档。和普通的"问答机器人"不同,浏览器助手类应用面对的是真实网页:它需要理解页面结构、点击按钮、输入表单、处理弹窗,并且每一步操作都可能失败,因此对工具调用的可靠性、多步规划能力要求更高。Qwen-Agent 把这一整套浏览器操作封装成了框架自带的示例应用,开发者可以在此基础上快速搭建自己的网页自动化智能体。
跳转链接
- 开源仓库:QwenLM/Qwen-Agent
- 官方文档:qwenlm.github.io/Qwen-Agent
- 在线聊天:chat.qwen.ai
- 模型下载:Hugging Face Qwen | ModelScope Qwen
- 评测基准:DeepPlanning
- 技术博客:Qwen-Agent 长上下文方案
- 社区:Discord