












请关注公众号【碳硅化合物AI】
作为多智能体框架的典型代表,AgentScope 以其"透明、模块化、高度可定制"的设计理念吸引了众多开发者。本文将带你从框架入口开始,深入理解 AgentScope 的整体架构、模块划分和核心设计理念。我们会从 agentscope.init() 这个入口函数出发,逐步揭示框架的初始化流程、模块组织方式,以及"乐高式"组件设计的精髓。无论你是想要深入源码学习,还是计划基于 AgentScope 进行二次开发,这篇文章都会为你提供一个清晰的路线图。
agentscope.init()AgentScope 的入口非常简单直接,就是 agentscope.init() 函数。让我们先看看这个函数做了什么:
def init(
project: str | None = None,
name: str | None = None,
run_id: str | None = None,
logging_path: str | None = None,
logging_level: str = "INFO",
studio_url: str | None = None,
tracing_url: str | None = None,
) -> None:
"""Initialize the agentscope library."""
if project:
_config.project = project
if name:
_config.name = name
if run_id:
_config.run_id = run_id
setup_logger(logging_level, logging_path)
if studio_url:
# 注册运行实例到 AgentScope Studio
# ...
_equip_as_studio_hooks(studio_url)
if tracing_url:
from .tracing import setup_tracing
setup_tracing(endpoint=endpoint)
_config.trace_enabled = True
这个函数主要做了三件事:
_config 这个线程安全的全局配置对象中你会发现,AgentScope 的初始化非常轻量,不会强制加载所有模块,这体现了"懒加载"的设计原则。
在 __init__.py 中,我们可以看到框架导入了哪些核心模块:
from . import exception
from . import module
from . import message
from . import model
from . import tool
from . import formatter
from . import memory
from . import agent
from . import session
from . import embedding
from . import token
from . import evaluate
from . import pipeline
from . import tracing
from . import rag
这些模块构成了 AgentScope 的核心骨架,每个模块都有明确的职责。
让我们用 PlantUML 类图来展示框架的核心模块及其关系:

从这个图可以看出,AgentScope 采用了清晰的层次结构:
StateModule 提供状态管理能力,Message 提供统一的数据结构AgentBase 定义智能体的基本行为,ReActAgent 实现具体的推理-行动循环ChatModelBase、FormatterBase、Toolkit、MemoryBase 为智能体提供各种能力Pipeline 负责多智能体的协调和编排让我们用一个时序图来展示智能体的典型执行流程:

这个流程展示了 ReAct 模式的核心:推理(Reasoning)和行动(Acting)的循环。智能体先通过模型进行推理,如果需要调用工具,就执行工具,然后把结果加入记忆,继续下一轮推理。
AgentScope 的第一个设计原则是"透明"。这意味着框架不会做"黑盒"封装,所有关键环节都对开发者可见:
这种透明性让开发者能够精确控制智能体的行为,而不是被框架"绑架"。
"乐高式"构建是 AgentScope 的另一个核心设计理念。每个组件都是独立的模块:
# 你可以自由组合这些组件
agent = ReActAgent(
name="Friday",
sys_prompt="You're a helpful assistant.",
model=DashScopeChatModel(...), # 模型可以替换
formatter=DashScopeChatFormatter(...), # 格式化器可以替换
toolkit=Toolkit(...), # 工具集可以替换
memory=InMemoryMemory(...), # 记忆可以替换
)
这种设计让你可以:
AgentScope 通过 ChatModelBase 抽象接口实现了模型无关:
class ChatModelBase:
@abstractmethod
async def __call__(
self,
*args: Any,
**kwargs: Any,
) -> ChatResponse | AsyncGenerator[ChatResponse, None]:
pass
所有模型提供商(OpenAI、DashScope、Gemini 等)都实现这个接口,这样你写一次代码,就能适配所有模型。
AgentScope 1.0 完全拥抱异步编程,几乎所有核心操作都是异步的:
# 异步调用模型
response = await model(messages)
# 异步执行工具
result = await tool_function(args)
# 异步智能体回复
msg = await agent(msg)
这种设计让框架能够:
让我们看一个最简单的使用示例:
import asyncio
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
async def main():
# 创建工具集
toolkit = Toolkit()
toolkit.register_tool_function(execute_python_code)
# 创建智能体
agent = ReActAgent(
name="Friday",
sys_prompt="You're a helpful assistant.",
model=DashScopeChatModel(
model_name="qwen-max",
api_key=os.environ["DASHSCOPE_API_KEY"],
),
formatter=DashScopeChatFormatter(),
toolkit=toolkit,
memory=InMemoryMemory(),
)
# 创建用户智能体
user = UserAgent(name="user")
# 对话循环
msg = None
while True:
msg = await user(msg)
if msg.get_text_content() == "exit":
break
msg = await agent(msg)
asyncio.run(main())
state_dict() 和 load_state_dict() 保存和恢复智能体状态AgentScope 的状态管理非常巧妙。StateModule 基类通过 __setattr__ 魔法方法自动追踪子模块:
def __setattr__(self, key: str, value: Any) -> None:
"""Set attributes and record state modules."""
if isinstance(value, StateModule):
if not hasattr(self, "_module_dict"):
raise AttributeError(...)
self._module_dict[key] = value
super().__setattr__(key, value)
这样,当你给 Agent 设置 Memory 或 Toolkit 时,它们会自动被纳入状态管理,支持嵌套序列化。
Msg 类是框架的核心数据结构,它统一了:
这种统一设计避免了数据格式转换的复杂性。
AgentScope 支持实时中断智能体的执行:
# 智能体执行过程中
agent._reply_task # 当前回复任务
agent.handle_interrupt() # 处理中断
这个机制让开发者可以在智能体"思考"时进行干预,这在调试和演示场景中非常有用。
AgentScope 通过清晰的模块划分、透明的设计理念和强大的扩展能力,为多智能体应用开发提供了一个优秀的框架。它的核心优势在于:
在后续的文章中,我们会深入分析各个核心组件的实现细节,包括智能体、记忆系统、工具系统等。如果你想要深入理解某个特定组件,可以继续阅读相应的专题文章。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。