MetaGPT 多角色 Agent¶
为什么要学 MetaGPT¶
MetaGPT 是一个多 Agent 框架,模拟软件公司的组织结构,让不同角色的 AI Agent(产品经理、架构师、工程师、QA)协作完成复杂任务。它的核心创新是将人类工作流程(SOP)编码为 Agent 间的协作协议,从而显著提高多 Agent 系统的输出质量。对于理解多 Agent 系统设计模式和构建复杂 AI 工作流来说,MetaGPT 提供了清晰的参考范式。
核心概念¶
| 概念 | 白话解释 | 用途 |
|---|---|---|
| Role | 角色 | 具有特定职责和能力的 Agent |
| Action | 动作 | 角色可执行的具体操作 |
| Message | 消息 | 角色间通信的载体 |
| Environment | 环境 | 所有角色共享的工作空间 |
| SOP (Standard Operating Procedure) | 标准流程 | 定义角色间协作顺序 |
| Memory | 记忆 | 角色的历史上下文 |
安装配置¶
安装¶
pip install metagpt
# 或从源码安装(推荐,获取最新功能)
git clone https://github.com/geekan/MetaGPT.git
cd MetaGPT
pip install -e .
配置¶
# ~/.metagpt/config2.yaml
llm:
api_type: "openai"
model: "gpt-4"
base_url: "https://api.openai.com/v1"
api_key: "sk-your-key"
# 或使用本地模型
# api_type: "ollama"
# model: "llama3"
# base_url: "http://localhost:11434/v1"
# 多模型配置
llm_for_code:
api_type: "openai"
model: "gpt-4"
api_key: "sk-your-key"
llm_for_planning:
api_type: "openai"
model: "gpt-3.5-turbo"
api_key: "sk-your-key"
快速上手¶
软件开发团队¶
import asyncio
from metagpt.roles import ProjectManager, Architect, Engineer
from metagpt.team import Team
async def main():
team = Team()
team.hire([
ProjectManager(),
Architect(),
Engineer(),
])
team.invest(investment=5.0) # 设置预算上限(美元)
team.run_project("开发一个命令行待办事项管理工具,支持增删改查和优先级排序")
await team.run(n_round=5)
asyncio.run(main())
单角色使用¶
import asyncio
from metagpt.roles import Engineer
async def main():
engineer = Engineer()
result = await engineer.run("写一个 Python 快速排序实现,包含单元测试")
print(result)
asyncio.run(main())
输出结构¶
workspace/
├── docs/
│ ├── prd.md # 产品需求文档
│ ├── system_design.md # 系统设计
│ └── api_spec.md # API 规范
├── src/
│ ├── main.py
│ └── utils.py
├── tests/
│ └── test_main.py
└── requirements.txt
进阶用法¶
自定义角色¶
from metagpt.roles import Role
from metagpt.actions import Action
from metagpt.schema import Message
class ReviewCode(Action):
"""代码审查动作"""
name: str = "ReviewCode"
async def run(self, code: str) -> str:
prompt = f"""请审查以下代码,指出问题并给出改进建议:
{code}
请从以下角度审查:
1. 代码质量和可读性
2. 潜在 bug
3. 性能问题
4. 安全隐患
"""
return await self._aask(prompt)
class CodeReviewer(Role):
"""代码审查员角色"""
name: str = "CodeReviewer"
profile: str = "Senior Code Reviewer"
goal: str = "Review code and provide improvement suggestions"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([ReviewCode])
# 监听 Engineer 的输出
self._watch([WriteCode])
自定义工作流¶
from metagpt.team import Team
from metagpt.roles import Role
class DataAnalyst(Role):
name: str = "DataAnalyst"
profile: str = "Data Analyst"
goal: str = "Analyze data and produce insights"
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_actions([CollectData, AnalyzeData, GenerateReport])
class DataTeam(Team):
def __init__(self):
super().__init__()
self.hire([
DataAnalyst(),
Visualizer(),
ReportWriter(),
])
async def run_analysis():
team = DataTeam()
team.run_project("分析公司上季度销售数据,找出增长最快的产品类别")
await team.run(n_round=4)
人机协作模式¶
from metagpt.roles import Role
from metagpt.utils.human_interaction import HumanInteraction
class InteractiveRole(Role):
async def _act(self):
# 执行任务
result = await self.todo.run()
# 在关键决策点请求人类确认
if self.needs_confirmation(result):
human_feedback = await HumanInteraction.ask(
f"Agent 计划执行以下操作,是否确认?\n{result}"
)
if human_feedback == "reject":
return await self._retry_with_feedback(human_feedback)
return result
记忆管理¶
from metagpt.memory import Memory
class SmartRole(Role):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# 配置记忆策略
self.memory = Memory(
max_length=20, # 保留最近 20 条消息
summary_threshold=15, # 超过 15 条时开始摘要
importance_threshold=0.7 # 重要性阈值
)
async def _observe(self):
# 自定义消息过滤
messages = self.rc.memory.get_by_role(self.profile)
relevant = [m for m in messages if self._is_relevant(m)]
return relevant
与外部工具集成¶
from metagpt.tools import Tool
class WebSearchTool(Tool):
name = "web_search"
description = "Search the web for information"
async def run(self, query: str) -> str:
# 调用搜索 API
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.search.com",
params={"q": query}
) as resp:
return await resp.text()
# 在角色中使用
class Researcher(Role):
tools = [WebSearchTool()]
常见问题¶
Q: 多角色之间如何通信?¶
通过 Message 消息机制。每个角色通过 _watch 定义监听哪些角色/动作的输出,通过 _publish_message 发布结果给其他角色。
Q: Token 消耗很大怎么控制?¶
- 使用
invest()设置预算上限 - 简单角色用便宜模型(GPT-3.5)
- 减少
n_round轮数 - 在 Action 中精简 prompt
Q: 生成的代码质量不高?¶
- 使用 GPT-4 而非 GPT-3.5
- 增加代码审查角色
- 在角色 prompt 中明确编码规范
- 设置测试角色验证输出
Q: 本地模型能用吗?¶
可以,但效果取决于模型能力。推荐 70B+ 模型用于复杂任务,13B+ 用于简单任务。通过 Ollama 或 vLLM 对接。
参考资源¶
- GitHub:https://github.com/geekan/MetaGPT
- 文档:https://docs.deepwisdom.ai/
- 论文:https://arxiv.org/abs/2308.00352
- 教程:https://docs.deepwisdom.ai/main/en/guide/tutorials/
- Discord:https://discord.gg/metagpt