Qwen-Agent README

The project's README from github.com/QwenLM/Qwen-Agent. As one markdown file: README.md.

中文 | English


💜 Qwen Chat   |   🤗 Hugging Face   |   🤖 ModelScope   |    📑 Blog    |   📖 Documentation
📊 Benchmark   |   💬 WeChat (微信)   |   🫨 Discord  

Qwen-Agent is a framework for developing LLM applications based on the instruction following, tool usage, planning, and memory capabilities of Qwen. It also comes with example applications such as Browser Assistant, Code Interpreter, and Custom Assistant. Now Qwen-Agent plays as the backend of Qwen Chat.

News

Getting Started

Installation

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.

Preparation: Model Service

You can either use the model service provided by Alibaba Cloud's DashScope, or deploy and use your own model service using the open-source Qwen models.

Developing Your Own Agent

Qwen-Agent offers atomic components, such as LLMs (which inherit from class BaseChatModel and come with function calling) and Tools (which inherit from class BaseTool), along with high-level components like Agents (derived from class Agent).

The following example illustrates the process of creating an agent capable of reading PDF files and utilizing tools, as well as incorporating a custom tool:

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)

In addition to using built-in agent implementations such as class Assistant, you can also develop your own agent implemetation by inheriting from class Agent.

The framework also provides a convenient GUI interface, supporting the rapid deployment of Gradio Demos for Agents. For example, in the case above, you can quickly launch a Gradio Demo using the following code:

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.

Now you can chat with the Agent in the web UI. Please refer to the examples directory for more usage examples.

FAQ

How to Use the Code Interpreter Tool?

We implement a code interpreter tool based on local Docker containers. You can enable the built-in code interpreter tool for your agent, allowing it to autonomously write code according to specific scenarios, execute it securely within an isolated sandbox environment, and return the execution results.

⚠️ Note: Before using this tool, please ensure that Docker is installed and running on your local operating system. The time required to build the container image for the first time depends on your network conditions. For Docker installation and setup instructions, please refer to the official documentation.

How to Use MCP?

You can select the required tools on the open-source MCP server website and configure the relevant environment.

Example of MCP invocation format:

{
    "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"
            ]
        }
    }
}

For more details, you can refer to the MCP usage example

The dependencies required to run this example are as follows:

# 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

Do you have function calling (aka tool calling)?

Yes. The LLM classes provide function calling. Additionally, some Agent classes also are built upon the function calling capability, e.g., FnCallAgent and ReActChat.

The current default tool calling template natively supports Parallel Function Calls.

How to pass LLM parameters to the Agent?

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,
    }
}

How to do question-answering over super-long documents involving 1M tokens?

We have released a fast RAG solution, as well as an expensive but competitive agent, for doing question-answering over super-long documents. They have managed to outperform native long-context models on two challenging benchmarks while being more efficient, and perform perfectly in the single-needle "needle-in-the-haystack" pressure test involving 1M-token contexts. See the blog for technical details.

Application: BrowserQwen

BrowserQwen is a browser assistant built upon Qwen-Agent. Please refer to its documentation for details.

Disclaimer

The Docker container-based code interpreter mounts only the specified working directory and implements basic sandbox isolation, but it should still be used with caution in production environments.

Qwen-Agent (QwenLM/Qwen-Agent)

Searching Database…

这是什么?Qwen-Agent 是一个基于 Qwen 模型构建大语言模型应用的框架,可以利用其指令遵循、工具调用、规划和记忆能力。它自带 Browser Assistant、Code Interpreter 等示例应用,并且是驱动 Qwen Chat 的后端。
这是框架还是现成的应用?它是一个框架:你可以用 LLM 类(内置函数调用)和 Tool 类等基础组件构建智能体,再把它们组合成更高层的 Agent 类,比如 Assistant。仓库还附带了用同样组件构建的现成示例应用,例如 Browser Assistant。
我该如何安装并让智能体运行起来?可以从 PyPI 安装稳定版,也可以从源码安装最新的开发版。然后使用 Assistant 这样的内置类定义一个智能体,还可以选择启动 Gradio 网页演示,与它对话。
使用它一定需要 DashScope API 密钥吗?只有在选择阿里云 DashScope 模型服务时才需要,此时需要设置 DASHSCOPE_API_KEY 环境变量。否则,你可以通过 vLLM(需要 GPU)或 Ollama(CPU/GPU)自行部署提供 OpenAI 兼容 API 的 Qwen 模型。
内置的代码解释器可以安全地用于生产环境吗?不太行。它在本地 Docker 容器中执行代码,且只挂载了工作目录,因此只有基本的沙箱隔离效果。README 明确提醒要谨慎使用,并表示它并非为生产环境设计。
开箱即用支持 MCP 服务器吗?支持。你可以从任意开源 MCP 服务器中选择工具、配置连接,智能体就会与其他工具一起调用它们。
什么是 BrowserQwen?BrowserQwen 是基于 Qwen-Agent 构建的浏览器助手应用,以 Chrome 扩展程序的形式发布,并附有独立的文档。
它能处理超大文档的问答吗?可以。它包含一个快速的检索增强生成(RAG)方案,以及一个成本更高的竞争式智能体流程,用于处理最多 100 万 token 的文档问答。在一项“大海捞针”压力测试中,该流程的表现优于原生长上下文模型。
图形界面演示需要什么 Python 版本?由于图形界面已升级到 Gradio 5,运行基于 Gradio 的演示需要 Python 3.10 或更高版本。
Creator
QwenLM
Size
19.2 MB
Stars
17.2K
Age
3y
Commits · 90 Days