agentscope-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Understanding AgentScope

了解AgentScope

What is AgentScope?

什么是AgentScope?

AgentScope is a production-ready, enterprise-grade open-source framework for building multi-agent applications with large language models. Its functionalities cover:
  • Development: ReAct agent, context compression, short/long-term memory, tool use, human-in-the-loop, multi-agent orchestration, agent hooks, structured output, planning, integration with MCP, agent skill, LLMs API, voice interaction (TTS/Realtime), RAG
  • Evaluation: Evaluate multistep agentic applications with statistical analysis
  • Training: Agentic reinforcement learning
  • Deployment: Session/state management, sandbox, local/serverless/Kubernetes deployment
AgentScope是一款可用于生产环境的企业级开源框架,用于基于大语言模型构建多智能体应用。其功能涵盖:
  • 开发:ReAct agent、上下文压缩、短期/长期记忆、工具调用、人在回路、多智能体编排、智能体钩子、结构化输出、规划、与MCP集成、智能体技能、LLMs API、语音交互(TTS/实时)、RAG
  • 评估:通过统计分析评估多步骤智能体应用
  • 训练:智能体强化学习
  • 部署:会话/状态管理、沙箱、本地/无服务器/Kubernetes部署

Installation

安装

bash
pip install agentscope
bash
pip install agentscope

or

or

uv pip install agentscope
undefined
uv pip install agentscope
undefined

Core Concepts

核心概念

  • Message: The core abstraction for information exchange between agents. Supports heterogeneous content blocks (text, images, tool calls, tool results).
python
from agentscope.message import Msg, TextBlock, ImageBlock, URLSource

msg = Msg(
    name="user",
    content=[TextBlock("Hello world"), ImageBlock(type="image", source=URLSource(type="url", url="..."))],
    role="user"
)
  • Agent: LLM-empowered agent that can reason, use tools, and generate responses through iterative thinking and action loops.
  • Toolkit: Register and manage tools (Python functions, MCP, agent skills) that agents can call.
  • Memory: Store
    Msg
    objects as conversation history/context with a marking mechanism for advanced memory management (compression, retrieval).
  • ChatModel: Unified interface across different providers (OpenAI, Anthropic, DashScope, Ollama, etc.) with support for tool use and streaming.
  • Formatter: Convert
    Msg
    objects to LLM API-specific formats. Must be used with the corresponding ChatModel. Supports multi-agent conversations with different agent identifiers.
  • Message:智能体间信息交换的核心抽象,支持异构内容块(文本、图片、工具调用、工具结果)。
python
from agentscope.message import Msg, TextBlock, ImageBlock, URLSource

msg = Msg(
    name="user",
    content=[TextBlock("Hello world"), ImageBlock(type="image", source=URLSource(type="url", url="..."))],
    role="user"
)
  • Agent:由大语言模型驱动的智能体,可通过迭代思考与行动循环进行推理、使用工具并生成响应。
  • Toolkit:注册并管理智能体可调用的工具(Python函数、MCP、智能体技能)。
  • Memory:存储
    Msg
    对象作为对话历史/上下文,带有标记机制以实现高级内存管理(压缩、检索)。
  • ChatModel:不同提供商(OpenAI、Anthropic、DashScope、Ollama等)的统一接口,支持工具调用与流式输出。
  • Formatter:将
    Msg
    对象转换为特定LLM API格式,必须与对应的ChatModel配合使用,支持带有不同智能体标识符的多智能体对话。

Basic Usage Examples

基础使用示例

Example 1: Simple Chatbot

示例1:简单聊天机器人

python
from agentscope.agent import ReActAgent, UserAgent
from agentscope.model import DashScopeChatModel
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.tool import Toolkit, execute_python_code, execute_shell_command
import os, asyncio

async def main():
    # Initialize toolkit with tools
    toolkit = Toolkit()
    toolkit.register_tool_function(execute_python_code)
    toolkit.register_tool_function(execute_shell_command)

    # Create ReActAgent with model, memory, formatter, and toolkit
    agent = ReActAgent(
        name="Friday",
        sys_prompt="You're a helpful assistant named Friday.",
        model=DashScopeChatModel(
            model_name="qwen-max",
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            stream=True,
        ),
        memory=InMemoryMemory(),
        formatter=DashScopeChatFormatter(),
        toolkit=toolkit,
    )

    # Create user agent for terminal input
    user = UserAgent(name="user")

    # Conversation loop
    msg = None
    while True:
        msg = await agent(msg)  # Agent processes and replies
        msg = await user(msg)   # User inputs next message
        if msg.get_text_content() == "exit":
            break

asyncio.run(main())
python
from agentscope.agent import ReActAgent, UserAgent
from agentscope.model import DashScopeChatModel
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.tool import Toolkit, execute_python_code, execute_shell_command
import os, asyncio

async def main():
    # Initialize toolkit with tools
    toolkit = Toolkit()
    toolkit.register_tool_function(execute_python_code)
    toolkit.register_tool_function(execute_shell_command)

    # Create ReActAgent with model, memory, formatter, and toolkit
    agent = ReActAgent(
        name="Friday",
        sys_prompt="You're a helpful assistant named Friday.",
        model=DashScopeChatModel(
            model_name="qwen-max",
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            stream=True,
        ),
        memory=InMemoryMemory(),
        formatter=DashScopeChatFormatter(),
        toolkit=toolkit,
    )

    # Create user agent for terminal input
    user = UserAgent(name="user")

    # Conversation loop
    msg = None
    while True:
        msg = await agent(msg)  # Agent processes and replies
        msg = await user(msg)   # User inputs next message
        if msg.get_text_content() == "exit":
            break

asyncio.run(main())

Example 2: Multi-Agent Conversation

示例2:多智能体对话

AgentScope adopts explicit message passing for multi-agent conversations (PyTorch-like dynamic graph), allowing flexible information flow control.
python
alice, bob, carol, david = ReActAgent(...), ReActAgent(...), ReActAgent(...), ReActAgent(...)

msg_alice = await alice()
msg_bob = await bob(msg_alice)  # Bob receives Alice's message and generate a reply. Alice doesn't receive Bob's message unless explicitly passed back.
msg_carol = await carol(msg_alice)  # Similarly, the agent cannot receive messages from other agents unless explicitly passed.
AgentScope采用显式消息传递实现多智能体对话(类似PyTorch的动态图),允许灵活控制信息流。
python
alice, bob, carol, david = ReActAgent(...), ReActAgent(...), ReActAgent(...), ReActAgent(...)

msg_alice = await alice()
msg_bob = await bob(msg_alice)  # Bob receives Alice's message and generate a reply. Alice doesn't receive Bob's message unless explicitly passed back.
msg_carol = await carol(msg_alice)  # Similarly, the agent cannot receive messages from other agents unless explicitly passed.

Broadcasting with MsgHub, a syntactic sugar for message broadcasting within a group of agents

Broadcasting with MsgHub, a syntactic sugar for message broadcasting within a group of agents

from agentscope.pipeline import MsgHub
async with MsgHub( participants=[alice, bob, carol], announcement=Msg("Host", "Let's discuss", "user") ) as hub: await alice() # Bob and Carol receive this await bob() # Alice and Carol receive this
# Manual broadcast
await hub.broadcast(Msg("Host", "New topic", "user"))

# Dynamic participant management
hub.add(david)
hub.delete(bob)
undefined
from agentscope.pipeline import MsgHub
async with MsgHub( participants=[alice, bob, carol], announcement=Msg("Host", "Let's discuss", "user") ) as hub: await alice() # Bob and Carol receive this await bob() # Alice and Carol receive this
# Manual broadcast
await hub.broadcast(Msg("Host", "New topic", "user"))

# Dynamic participant management
hub.add(david)
hub.delete(bob)
undefined

Example 3: Master-Worker Pattern

示例3:主从模式

Wrap worker agents as tools for the master agent.
python
from agentscope.tool import ToolResponse, Toolkit

async def create_worker(task: str) -> ToolResponse:
    """Create a worker agent for the given task.

    Args:
        task (`str`): The given task, which should be specific and concise.
    """
    task_msg = Msg(name="master", content=task, role="user") # Use the input task or wrap it into a more complex prompt
    worker = ReActAgent(...)
    res = await worker(task_msg)
    return ToolResponse(content=res.content) # Return the worker's response as the tool response

toolkit = Toolkit()
toolkit.register_tool_function(create_worker)
将工作智能体包装为主智能体的工具。
python
from agentscope.tool import ToolResponse, Toolkit

async def create_worker(task: str) -> ToolResponse:
    """Create a worker agent for the given task.

    Args:
        task (`str`): The given task, which should be specific and concise.
    """
    task_msg = Msg(name="master", content=task, role="user") # Use the input task or wrap it into a more complex prompt
    worker = ReActAgent(...)
    res = await worker(task_msg)
    return ToolResponse(content=res.content) # Return the worker's response as the tool response

toolkit = Toolkit()
toolkit.register_tool_function(create_worker)

Working with AgentScope

AgentScope使用实操

This section provides guidance on how to effectively answer questions about AgentScope or coding with the framework.
本节提供如何有效解答AgentScope相关问题或基于该框架编码的指导。

Step 1: Clone the Repository First

步骤1:先克隆仓库

CRITICAL: Before doing anything else, clone or update the AgentScope repository. The repository contains essential examples and references.
bash
undefined
关键:在进行任何操作前,先克隆或更新AgentScope仓库。仓库包含重要的示例与参考资料。
bash
undefined

Clone into this skill directory so that you can refer to it across different sessions

Clone into this skill directory so that you can refer to it across different sessions

cd /path/to/this/skill/directory git clone -b main https://github.com/agentscope-ai/agentscope.git
cd /path/to/this/skill/directory git clone -b main https://github.com/agentscope-ai/agentscope.git

Or update if already cloned

Or update if already cloned

cd /path/to/this/skill/directory/agentscope git pull

**Why this matters**: The repository contains working examples, complete API documentation in source code, and implementation patterns that are more reliable than guessing.
cd /path/to/this/skill/directory/agentscope git pull

**重要性**:仓库包含可运行的示例、源代码中的完整API文档,以及比猜测更可靠的实现模式。

Step 2: Understand the Repository Structure

步骤2:了解仓库结构

The cloned repository is organized as follows. Note this may be outdated as the project evolves, you should always check the actual structure after cloning.
agentscope/
├── src/agentscope/          # Main library source code
│   ├── agent/               # Agent implementations (ReActAgent, etc.)
│   ├── model/               # LLM API wrappers (OpenAI, Anthropic, DashScope, etc.)
│   ├── formatter/           # Message formatters for different models
│   ├── memory/              # Memory implementations
│   ├── tool/                # Tool management and built-in tools
│   ├── message/             # Msg class and content blocks
│   ├── pipeline/            # Multi-agent orchestration (MsgHub, etc.)
│   ├── session/             # Session/state management
│   ├── mcp/                 # MCP integration
│   ├── rag/                 # RAG functionality
│   ├── realtime/            # Realtime voice interaction
│   ├── tts/                 # Text-to-speech
│   ├── evaluate/            # Evaluation tools
│   └── ...                  # Other modules
├── examples/                # Working examples organized by category
│   ├── agent/               # Different agent types
│   │   └── ...
│   ├── workflows/           # Multi-agent workflows
│   │   └── ...
│   ├── functionality/       # Specific features
│   │   └── ...
│   ├── deployment/          # Deployment patterns
│   ├── integration/         # Third-party integrations
│   ├── evaluation/          # Evaluation examples
│   └── game/                # Game examples (e.g., werewolves)
├── docs/                    # Documentation
│   ├── tutorial/            # Tutorial markdown files
│   ├── changelog.md         # Version history
│   └── roadmap.md           # Development roadmap
└── tests/                   # Test files
克隆后的仓库结构如下。请注意,随着项目发展,该结构可能过时,克隆后请务必检查实际结构。
agentscope/
├── src/agentscope/          # 主库源代码
│   ├── agent/               # 智能体实现(ReActAgent等)
│   ├── model/               # LLM API封装(OpenAI、Anthropic、DashScope等)
│   ├── formatter/           # 适配不同模型的消息格式化器
│   ├── memory/              # 内存实现
│   ├── tool/                # 工具管理与内置工具
│   ├── message/             # Msg类与内容块
│   ├── pipeline/            # 多智能体编排(MsgHub等)
│   ├── session/             # 会话/状态管理
│   ├── mcp/                 # MCP集成
│   ├── rag/                 # RAG功能
│   ├── realtime/            # 实时语音交互
│   ├── tts/                 # 文本转语音
│   ├── evaluate/            # 评估工具
│   └── ...                  # 其他模块
├── examples/                # 按类别组织的可运行示例
│   ├── agent/               # 不同类型的智能体
│   │   └── ...
│   ├── workflows/           # 多智能体工作流
│   │   └── ...
│   ├── functionality/       # 特定功能
│   │   └── ...
│   ├── deployment/          # 部署模式
│   ├── integration/         # 第三方集成
│   ├── evaluation/          # 评估示例
│   └── game/                # 游戏示例(如狼人杀)
├── docs/                    # 文档
│   ├── tutorial/            # 教程Markdown文件
│   ├── changelog.md         # 版本历史
│   └── roadmap.md           # 开发路线图
└── tests/                   # 测试文件

Step 3: Browse Examples by Category

步骤3:按类别浏览示例

When looking for similar implementations, browse the examples directory by category rather than searching by keywords alone:
  1. Start with the category that matches your use case:
    • Building a specific agent type? →
      examples/agent/
    • Multi-agent system? →
      examples/workflows/
    • Need a specific feature (MCP, RAG, session)? →
      examples/functionality/
    • Deployment patterns? →
      examples/deployment/
  2. List the subdirectories to see what's available:
    • Use file listing tools to explore directory structure
    • Read directory names to understand what each example covers
  3. Read example files to understand implementation patterns:
    • Most examples contain a main script and supporting files
    • Look for README files in subdirectories for explanations
  4. Combine with text search when needed:
    • After identifying relevant directories, search within them for specific patterns
    • Search for class names, method calls, or specific functionality
Example workflow:
User asks: "Build a FastAPI app with AgentScope"
→ Browse: List files in examples/deployment/
→ Check: Are there any web service examples?
→ Search: Look for "fastapi", "flask", "api", "server" in examples/
→ Read: Found examples and adapt to user's needs
当寻找类似实现时,按类别浏览examples目录,而非仅通过关键词搜索:
  1. 从匹配你用例的类别开始
    • 构建特定类型的智能体?→
      examples/agent/
    • 多智能体系统?→
      examples/workflows/
    • 需要特定功能(MCP、RAG、会话)?→
      examples/functionality/
    • 部署模式?→
      examples/deployment/
  2. 列出子目录查看可用内容:
    • 使用文件列表工具探索目录结构
    • 通过目录名称了解每个示例的覆盖范围
  3. 阅读示例文件理解实现模式:
    • 大多数示例包含主脚本与支持文件
    • 查看子目录中的README文件获取说明
  4. 必要时结合文本搜索
    • 确定相关目录后,在其中搜索特定模式
    • 搜索类名、方法调用或特定功能
示例工作流:
User asks: "Build a FastAPI app with AgentScope"
→ 浏览:列出examples/deployment/中的文件
→ 检查:是否有Web服务示例?
→ 搜索:在examples/中查找"fastapi"、"flask"、"api"、"server"
→ 阅读:找到示例并根据用户需求调整

Step 4: Verify Functionality Exists

步骤4:验证功能是否存在

Before implementing custom solutions, verify if AgentScope already provides the functionality:
  1. List required functionalities (e.g., session management, MCP integration, RAG)
  2. Check if provided:
    • Browse
      examples
      for examples
    • Search tutorial documentation in
      docs/tutorial/
    • Use the provided scripts (see Part 3) to explore API structure
    • Read source code in
      src/agentscope/
      for implementation details
  3. If not provided: Check how to customize by reading base classes and inheritance patterns in source code
在实现自定义解决方案前,先验证AgentScope是否已提供该功能:
  1. 列出所需功能(如会话管理、MCP集成、RAG)
  2. 检查是否已提供:
    • examples
      中查找相关示例
    • 搜索
      docs/tutorial/
      中的教程文档
    • 使用提供的脚本(见第3部分)探索API结构
    • 阅读
      src/agentscope/
      中的源代码获取实现细节
  3. 若未提供:通过阅读源代码中的基类与继承模式了解如何自定义

Step 5: Make a Plan

步骤5:制定计划

Always create a plan before coding:
  1. Identify what AgentScope components you'll use
  2. Determine what needs custom implementation
  3. Outline the architecture and data flow
  4. Consider edge cases and error handling
编码前务必制定计划:
  1. 确定将使用哪些AgentScope组件
  2. 明确需要自定义实现的部分
  3. 概述架构与数据流
  4. 考虑边缘情况与错误处理

Step 6: Code with API Reference

步骤6:结合API参考编码

When writing code:
  1. Check docstrings and arguments before using any class/method
    • Read source code files to see signatures and documentation, or
    • Use the provided scripts to view module/class structures
    • NEVER make up classes, methods, or arguments
  2. Check parent classes - A class's functionality includes inherited methods
  3. Manage lifecycle - Clean up resources when needed (close connections, release memory)
编写代码时:
  1. 使用任何类/方法前先检查文档字符串与参数
    • 阅读源代码文件查看签名与文档,或
    • 使用提供的脚本查看模块/类结构
    • 绝对不要凭空捏造类、方法或参数
  2. 检查父类 - 类的功能包括继承的方法
  3. 管理生命周期 - 必要时清理资源(关闭连接、释放内存)

Common Pitfalls to Avoid

需避免的常见陷阱

  • ❌ Guessing API signatures without checking documentation
  • ❌ Implementing features that already exist in AgentScope
  • ❌ Mixing incompatible Model and Formatter (e.g., OpenAI model with DashScope formatter)
  • ❌ Forgetting to await async agent calls
  • ❌ Not checking parent class methods when searching for functionality
  • ❌ Searching by keywords only without browsing the organized examples directory structure
  • ❌ 不查看文档就猜测API签名
  • ❌ 实现AgentScope已有的功能
  • ❌ 混用不兼容的Model与Formatter(如OpenAI模型搭配DashScope formatter)
  • ❌ 忘记await异步智能体调用
  • ❌ 查找功能时不检查父类方法
  • ❌ 仅通过关键词搜索,而非浏览组织有序的示例目录结构

Resources

资源

This section lists all available resources for working with AgentScope.
本节列出所有与AgentScope相关的可用资源。

Official Documentation

官方文档

  • Tutorial: Comprehensive step-by-step guide covering most functionalities in detail. This is the primary resource for learning AgentScope.
  • 教程:全面的分步指南,详细涵盖大多数功能。这是学习AgentScope的主要资源。

GitHub Resources

GitHub资源

Repository Structure

仓库结构

When the repository is cloned locally, the following structure is available for reference:
  • src/agentscope/
    : Main library source code
    • Read this for API implementation details
    • Check docstrings for parameter descriptions
    • Understand inheritance hierarchies
  • examples/
    : Working examples demonstrating features
    • Start here when building similar applications
    • Examples cover: basic agents, multi-agent systems, tool usage, deployment patterns
  • docs/tutorial/
    : Tutorial documentation source files
    • Markdown files explaining concepts and usage
    • More detailed than README files
当仓库克隆到本地后,可参考以下结构:
  • src/agentscope/
    :主库源代码
    • 阅读此处获取API实现细节
    • 查看文档字符串获取参数说明
    • 理解继承层次
  • examples/
    :演示功能的可运行示例
    • 构建类似应用时从这里开始
    • 示例涵盖:基础智能体、多智能体系统、工具使用、部署模式
  • docs/tutorial/
    :教程文档源文件
    • 解释概念与用法的Markdown文件
    • 比README文件更详细

Scripts

脚本

Located in
scripts/
directory of this skill.
  • view_pypi_latest_version.sh
    : View the latest version of AgentScope on PyPI.
bash
cd /path/to/this/skill/directory/scripts/
bash view_pypi_latest_version.sh
  • view_module_signature.py
    : Explore the structure of AgentScope modules, classes, and methods. Search strategy: Use deep-first search - start broad, then narrow down:
  1. agentscope
    → see all submodules
  2. agentscope.agent
    → see agent-related classes
  3. agentscope.agent.ReActAgent
    → see specific class methods
bash
cd /path/to/this/skill/directory/scripts/
位于本技能的
scripts/
目录中。
  • view_pypi_latest_version.sh
    :查看PyPI上AgentScope的最新版本。
bash
cd /path/to/this/skill/directory/scripts/
bash view_pypi_latest_version.sh
  • view_module_signature.py
    :探索AgentScope模块、类与方法的结构。 搜索策略:使用深度优先搜索 - 从宽泛到具体:
  1. agentscope
    → 查看所有子模块
  2. agentscope.agent
    → 查看智能体相关类
  3. agentscope.agent.ReActAgent
    → 查看特定类的方法
bash
cd /path/to/this/skill/directory/scripts/

View top-level module

View top-level module

python view_module_signature.py --module agentscope
python view_module_signature.py --module agentscope

View specific submodule

View specific submodule

python view_module_signature.py --module agentscope.agent
python view_module_signature.py --module agentscope.agent

View specific class

View specific class

python view_module_signature.py --module agentscope.agent.ReActAgent
undefined
python view_module_signature.py --module agentscope.agent.ReActAgent
undefined

Reference

参考

Located in
references/
directory of this skill.
  • multi_agent_orchestration.md
    : Multi-agent orchestration concepts and implementation
  • deployment_guide.md
    : Deployment patterns and best practices
位于本技能的
references/
目录中。
  • multi_agent_orchestration.md
    :多智能体编排概念与实现
  • deployment_guide.md
    :部署模式与最佳实践