MetaGPT 架构详解
整体架构
MetaGPT 采用分层架构设计,将多智能体协作系统分解为可管理的组件:
text
┌─────────────────────────────────────────────────────────────┐
│ Team │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Environment │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Role │ │ Role │ │ Role │ ... │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ Action │ │ Action │ │ Action │ │ │
│ │ │ Memory │ │ Memory │ │ Memory │ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ │ │
│ │ │ │
│ │ Message Queue (Pub/Sub) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Context (Config, LLM, Cost Manager) │
└─────────────────────────────────────────────────────────────┘核心概念
1. Team(团队)
Team 是 MetaGPT 的顶层容器,负责:
- 管理多个 Role(角色)
- 协调角色之间的协作
- 控制执行轮次和预算
python
from metagpt.team import Team
from metagpt.context import Context
# 创建团队
ctx = Context(config=config)
company = Team(context=ctx)
# 雇用角色
company.hire([
ProductManager(),
Architect(),
Engineer(),
])
# 设置预算并运行
company.invest(3.0)
await company.run(n_round=5, idea="Create a 2048 game")2. Environment(环境)
Environment 是角色运行的环境,提供:
- 角色注册和管理
- 消息发布/订阅机制
- 共享状态管理
python
from metagpt.environment import Environment
env = Environment(context=ctx)
env.add_roles([role1, role2])
env.publish_message(Message(content="Start task"))MetaGPT 还提供了 MGXEnv,这是一个增强版环境,支持更复杂的协作模式。
3. Role(角色)
Role 是 MetaGPT 的核心抽象,代表一个具有特定职责的智能体:
python
from metagpt.roles import Role
from metagpt.actions import Action
class CustomRole(Role):
name: str = "CustomRole"
profile: str = "A custom role"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([CustomAction()])
self._watch([SomeOtherAction]) # 订阅其他角色的动作4. Action(动作)
Action 是角色执行的具体任务单元:
python
from metagpt.actions import Action
class CustomAction(Action):
name: str = "CustomAction"
async def run(self, *args, **kwargs):
# 调用 LLM 执行任务
result = await self._aask(prompt)
return result5. Message(消息)
Message 是角色之间通信的载体:
python
from metagpt.schema import Message
msg = Message(
content="Task completed",
role="Engineer",
cause_by=WriteCode,
send_to="QAEngineer"
)目录结构
text
metagpt/
├── actions/ # 动作定义
│ ├── action.py
│ ├── write_code.py
│ ├── write_prd.py
│ └── ...
├── roles/ # 角色定义
│ ├── role.py
│ ├── product_manager.py
│ ├── architect.py
│ ├── engineer.py
│ └── ...
├── environment/ # 环境实现
├── memory/ # 记忆系统
├── provider/ # LLM 提供者
├── tools/ # 工具集
├── utils/ # 工具函数
├── team.py # 团队管理
├── context.py # 上下文管理
├── schema.py # 数据模型
└── config2.py # 配置管理消息流转机制
MetaGPT 使用发布/订阅模式实现角色间通信:
text
ProductManager Architect Engineer
│ │ │
│ WritePRD │ │
├──────────────────────────▶ │ │
│ │ WriteDesign │
│ ├───────────────────────────▶│
│ │ │
│ │ │ WriteCode
│ │ ├─────────▶订阅机制
每个角色通过 _watch() 方法订阅感兴趣的 Action:
python
class Architect(Role):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([WriteDesign()])
self._watch([WritePRD]) # 监听 PM 的输出消息触发
当某个 Action 完成后,系统会自动通知所有订阅该 Action 的角色:
- ProductManager 执行 WritePRD
- 输出消息发布到环境
- Architect(订阅了 WritePRD)被触发
- Architect 执行 WriteDesign
- Engineer(订阅了 WriteDesign)被触发
- ...
执行流程
标准软件开发流程
text
用户需求
│
▼
┌─────────────┐
│ 分析需求 │ ProductManager
│ 撰写 PRD │
└─────────────┘
│
▼
┌─────────────┐
│ 系统设计 │ Architect
│ API 设计 │
└─────────────┘
│
▼
┌─────────────┐
│ 任务分解 │ ProjectManager (可选)
│ 项目计划 │
└─────────────┘
│
▼
┌─────────────┐
│ 代码实现 │ Engineer
│ 编写代码 │
└─────────────┘
│
▼
┌─────────────┐
│ 质量保证 │ QAEngineer (可选)
│ 编写测试 │
└─────────────┘
│
▼
完整项目输出执行控制参数
bash
metagpt "Create a game" \
--investment 3.0 \ # 预算(美元)
--n-round 5 \ # 最大执行轮次
--code-review \ # 启用代码审查
--run-tests # 启用测试状态持久化
MetaGPT 支持项目状态的序列化和恢复:
python
# 保存状态
company.serialize(stg_path=Path("./storage/team"))
# 恢复状态
company = Team.deserialize(stg_path=Path("./storage/team"), context=ctx)这使得长时间运行的任务可以中断后继续执行。
Context 管理
Context 是 MetaGPT 的全局配置中心:
python
from metagpt.context import Context
from metagpt.config2 import config
ctx = Context(config=config)
# 访问配置
llm = ctx.config.llm
cost_manager = ctx.cost_manager
# 跟踪成本
print(f"Total cost: ${cost_manager.total_cost}")预算控制
MetaGPT 内置预算控制机制,防止 API 调用超支:
python
company.invest(3.0) # 设置最大预算为 $3.00
# 执行过程中会自动检查
# 如果超出预算,抛出 NoMoneyException增量开发模式
MetaGPT 支持增量开发,可以基于现有代码库进行迭代:
bash
metagpt "Add user authentication" \
--inc \
--project-path ./existing-project这使得 MetaGPT 不仅能从零创建项目,还能维护和扩展现有项目。
下一节:16.2 角色与动作