中文 |英语
💜 Qwen Chat   |   🤗 Hugging Face   |   🤖 ModelScope   |    📑 Blog    |   📖 Documentation
📊 Benchmark   |   💬 WeChat (微信)   |   🫨 Discord  
Qwen Agent是一个基于指令遵循、工具使用、规划和 Qwen的存储能力。 它还附带了示例应用程序,如浏览器助手、代码解释器和自定义助手。 现在Qwen Agent作为后端 Qwen聊天.
新闻
- 🔥🔥🔥2026年2月16日:开源Qwen3.5。有关使用示例,请参阅 Qwen3.5代理演示.
- 2025年9月23日:新增 Qwen3 VL工具调用演示,支持放大、图像搜索和网络搜索等工具。
- 2025年7月23日:添加 Qwen3编码器工具调用演示;添加了本机API工具调用接口支持,例如使用vLLM内置的工具调用解析。
- 2025年5月1日:添加 Qwen3工具调用演示,并添加 MCP食谱.
- 2025年3月18日:支持
reasoning_content场;调整默认值 函数调用模板,适用于Qwen2.5系列通用机型和QwQ-32B。如果您需要使用旧版本的模板,请参阅 例子 用于传递参数。 - 2025年3月7日:新增 QwQ-32B工具调用演示。它支持并行、多步和多回转刀具调用。
- 2024年12月3日:将GUI升级到基于Gradio 5的版本。注意:GUI需要Python 3.10或更高版本。
- 2024年9月18日:已添加 Qwen2.5数学演示 展示Qwen2.5-Math的工具集成推理能力。注意:python执行器不是沙盒的,仅用于本地测试,不用于生产。
入门指南
安装
- 从PyPI安装稳定版本:
pip install -U "qwen-agent[gui,rag,code_interpreter,mcp]"
# Or use `pip install -U qwen-agent` for the minimal requirements.
# The optional requirements, specified in double brackets, are:
# [gui] for Gradio-based GUI support;
# [rag] for RAG support;
# [code_interpreter] for Code Interpreter support;
# [mcp] for MCP support.- 或者,您可以从源代码安装最新的开发版本:
git clone https://github.com/QwenLM/Qwen-Agent.git
cd Qwen-Agent
pip install -e ./"[gui,rag,code_interpreter,mcp]"
# Or `pip install -e ./` for minimal requirements.准备:模型服务
您可以使用阿里巴巴提供的模型服务 云的 达摩院,或部署和使用您自己的 使用开源Qwen模型的模型服务。
- 如果您选择使用DashScope提供的模型服务,请确保您设置了环境
变量 DASHSCOPE_API_KEY 到您唯一的DashScope API密钥。
- 或者,如果您更喜欢部署和使用自己的模型服务,请按照Qwen2的自述中提供的说明部署与OpenAI兼容的API服务。
对于QwQ和Qwen3型号,建议 不要 添加 --enable-auto-tool-choice 和 --tool-call-parser hermes 参数,因为Qwen Agent将自行解析来自vLLM的工具输出。 对于Qwen3 Coder,建议启用上述两个参数,使用vLLM的内置工具解析,并与 use_raw_api 参数 用法.
开发自己的代理
Qwen Agent提供原子组件,如LLM(继承自 class BaseChatModel 跟我来 函数调用)和工具(继承 从 class BaseTool),以及Agent等高级组件(源自 class Agent).
以下示例说明了创建能够读取PDF文件并使用工具的代理的过程,如 以及包含自定义工具:
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)
# Step 2: Configure the LLM you are using.
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
}
}
# 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)
# 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)除了使用内置代理实现,例如 class Assistant,您还可以通过继承来开发自己的代理实现 class Agent.
该框架还提供了一个方便的GUI界面,支持快速部署Gradio Demos for Agents。 例如,在上述情况下,您可以使用以下代码快速启动Gradio演示:
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.现在,您可以在web UI中与Agent聊天。请参阅 示例 目录以获取更多使用示例。
常见问题解答
如何使用代码解释器工具?
我们实现了一个基于本地Docker容器的代码解释器工具。您可以启用内置 code interpreter 代理的工具,允许它根据特定场景自主编写代码,在隔离的沙盒环境中安全执行,并返回执行结果。
⚠️ 备注:在使用此工具之前,请确保Docker已安装并在您的本地操作系统上运行。首次构建容器映像所需的时间取决于您的网络条件。有关Docker的安装和设置说明,请参阅 官方文档.
如何使用MCP?
您可以在开源上选择所需的工具 MCP服务器网站 并配置相关环境。
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"
]
}
}
}有关更多详细信息,请参阅 MCP使用示例
运行此示例所需的依赖关系如下:
# Node.js (Download and install the latest version from the Node.js official website)
# uv 0.4.18 or higher (Check with uv --version)
# Git (Check with git --version)
# SQLite (Check with sqlite3 --version)
# For macOS users, you can install these components using Homebrew:
brew install uv git sqlite3
# For Windows users, you can install these components using winget:
winget install --id=astral-sh.uv -e
winget install git.git sqlite.sqlite你有函数调用(又名工具调用)吗?
对。LLM课程提供 函数调用此外,一些Agent类也基于函数调用能力构建,例如FnCallAgent和ReActChat。
当前默认的工具调用模板本机支持 并行函数调用.
如何将LLM参数传递给代理?
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 `this is the thoughtthis 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,
}
}如何对涉及1M代币的超长文档进行问答?
应用:浏览器Qwen
BrowserQwen是基于Qwen Agent构建的浏览器助手。请参阅 文档 了解详情。
免责声明
基于Docker容器的代码解释器仅挂载指定的工作目录并实现基本的沙盒隔离,但在生产环境中仍应谨慎使用。
