分层 API 架构设计
分层 API 架构设计
学习目标
本章要解决什么问题:AutoGen 如何通过三层 API 架构兼顾灵活性与易用性。你将学到:
- Core、AgentChat、Extensions 三层的职责划分
- 层间依赖规则与设计决策
- 为什么 AgentChat 建立在 Core 之上而非独立
- 如何为不同用户群体提供合适的抽象级别
前置知识
本章涉及分层 API 架构的通用原理,建议先阅读:
下文假设你已理解分层架构的基本思想,直接聚焦 AutoGen 的具体实践。
项目实践
三层包结构
python/packages/├── autogen-core/ # Core API — 事件驱动的 Agent 运行时│ ├── agents/ # Agent 基类(RoutedAgent, ClosureAgent)│ ├── models/ # 模型抽象(ChatCompletionClient)│ ├── tools/ # 工具抽象(BaseTool, Workbench)│ ├── memory/ # 记忆抽象(Memory)│ ├── model_context/ # 对话上下文策略│ └── state/ # 状态模型├── autogen-agentchat/ # AgentChat API — 高层快速原型│ ├── agents/ # 具体 Agent(AssistantAgent, UserProxyAgent)│ ├── teams/ # 多 Agent 编排(RoundRobin, Selector, Swarm)│ ├── base/ # 基础接口(ChatAgent, Team, TerminationCondition)│ ├── messages/ # 消息类型│ └── ui/ # 终端输出工具├── autogen-ext/ # Extensions API — 插件扩展│ ├── models/ # 模型实现(OpenAI, Anthropic, Ollama)│ ├── tools/ # 工具实现(MCP, LangChain, Code Executor)│ ├── runtimes/ # 分布式运行时(GRPC)│ ├── cache_store/ # 缓存后端(Redis)│ └── memory/ # 记忆实现├── autogen-studio/ # 无代码 GUI(独立应用,依赖以上三层)└── agbench/ # 基准测试套件依赖关系
关键规则:Core 不引入任何 AgentChat 或 Extensions 的依赖。这确保了:
- 只使用 Core 的用户不需要安装 AgentChat 或 Extensions
- Extensions 的升级不影响 Core 的稳定性
- Core 可以作为独立的基础库被其他框架使用
典型用户路径
路径一:快速原型(仅 AgentChat + Extensions)
# 仅需 5 行代码即可构建多 Agent 应用from autogen_agentchat.agents import AssistantAgentfrom autogen_agentchat.teams import RoundRobinGroupChatfrom autogen_ext.models.openai import OpenAIChatCompletionClient
client = OpenAIChatCompletionClient(model="gpt-4.1")agent = AssistantAgent("assistant", model_client=client)result = await agent.run(task="Hello!")用户不需要理解 Runtime、Subscription、Topic 等 Core 概念。
路径二:自定义 Agent(Core)
from autogen_core import RoutedAgent, message_handler, DefaultSubscription
class CustomAgent(RoutedAgent): @message_handler async def handle(self, msg: MyMessage, ctx: MessageContext) -> MyResponse: # 直接操作消息路由 ...
await CustomAgent.register(runtime, "custom", lambda: CustomAgent())用户获得了完整的消息路由控制权。
问题与规避
API 版本耦合
陷阱:AgentChat 依赖 Core 的内部实现,Core 的破坏性变更会导致 AgentChat 同步失效。
规避策略:
- Core 的
AgentRuntime接口使用 Protocol(运行时类型检查),而非具体类 - AgentChat 通过 Core 的公开 API 交互,不访问
_前缀的私有成员 - Monorepo 中同步更新,确保发布版本的一致性
层间泄漏
陷阱:AgentChat 用户在调试时可能被迫进入 Core 层(如查看 Agent ID、Topic 等)。
规避策略:
- AgentChat 提供
name属性作为 Agent 的友好标识,隐藏 Core 的AgentId - 错误信息中同时提供 AgentChat 层和 Core 层的上下文
设计取舍
Core 为什么定义抽象而非实现?
Core 层的 ChatCompletionClient、BaseTool、Memory 都是抽象类(ABC),具体实现在 Extensions 中。
优势:
- Core 保持轻量,不依赖任何外部 SDK
- 新模型/工具提供商只需在 Extensions 中新增一个子类
- 用户可以选择性安装需要的 Extensions
代价:
- 初始安装后仍需要安装 Extensions 才能实际使用
- Extensions 的命名和接口需要与 Core 保持同步
参考来源
- AutoGen Architecture Overview — 官方架构说明
- 源码验证:
python/packages/目录结构(9 个独立包)