MetaGPT 多智能体 101:打造你的第一个 AI 团队

在上一章中,我们学习了如何创建一个单个智能体。虽然单个智能体在许多情况下已经足够,但对于更复杂的任务,往往需要协作和团队合作。这就是多智能体系统发挥作用的地方。MetaGPT 的核心优势在于它能够轻松灵活地开发多个智能体组成的团队。在 MetaGPT 框架下,只需编写少量代码,就能实现智能体之间的交互。

通过本教程,你将学会:

  • 理解智能体之间的交互方式
  • 开发你的第一个 AI 团队
  • 运行软件创业示例

开发你的第一个 AI 团队

让我们以软件创业为例,想象一下,你需要一个团队来开发一个 CLI 版本的 Flappy Bird 游戏:

metagpt "write a cli flappy bird game"

这个简单的命令就可以启动 MetaGPT,并让它自动组建一个 AI 团队来完成这个任务。

1. 定义角色和动作

与单个智能体类似,我们需要定义每个角色以及它们能够执行的动作。

  • SimpleCoder: 接受用户指令,编写主要代码。
  • SimpleTester: 接受 SimpleCoder 生成的代码,编写测试用例。
  • SimpleReviewer: 接受 SimpleTester 生成的测试用例,审查其覆盖率和质量。

每个角色对应一个动作:

  • SimpleWriteCode: 接受用户指令,生成 Python 代码。
  • SimpleWriteTest: 接受代码,生成测试用例。
  • SimpleWriteReview: 审查测试用例,并提供评论。

2. 定义角色

在 MetaGPT 中,定义一个角色通常只需要几行代码。

SimpleCoder:

class SimpleCoder(Role):
    name: str = "Alice"
    profile: str = "SimpleCoder"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([UserRequirement])  # 监听用户指令
        self.set_actions([SimpleWriteCode])

SimpleTester:

class SimpleTester(Role):
    name: str = "Bob"
    profile: str = "SimpleTester"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([SimpleWriteTest])
        self._watch([SimpleWriteCode])  # 监听 SimpleCoder 生成的代码
        # self._watch([SimpleWriteCode, SimpleWriteReview])  # 可以尝试监听更多信息

    async def _act(self) -> Message:
        logger.info(f"{self._setting}: to do {self.rc.todo}({self.rc.todo.name})")
        todo = self.rc.todo

        # context = self.get_memories(k=1)[0].content  # 使用最近的记忆作为上下文
        context = self.get_memories()  # 使用所有记忆作为上下文

        code_text = await todo.run(context, k=5)  # 指定参数
        msg = Message(content=code_text, role=self.profile, cause_by=type(todo))

        return msg

SimpleReviewer:

class SimpleReviewer(Role):
    name: str = "Charlie"
    profile: str = "SimpleReviewer"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([SimpleWriteReview])
        self._watch([SimpleWriteTest])  # 监听 SimpleTester 生成的测试用例

3. 创建团队

现在,我们已经定义了三个角色,可以将它们组合成一个团队:

import asyncio
import typer
from metagpt.logs import logger
from metagpt.team import Team
app = typer.Typer()

@app.command()
def main(
    idea: str = typer.Argument(..., help="write a function that calculates the product of a list"),
    investment: float = typer.Option(default=3.0, help="Dollar amount to invest in the AI company."),
    n_round: int = typer.Option(default=5, help="Number of rounds for the simulation."),
):
    logger.info(idea)

    team = Team()
    team.hire(
        [
            SimpleCoder(),
            SimpleTester(),
            SimpleReviewer(),
        ]
    )

    team.invest(investment=investment)
    team.run_project(idea)
    asyncio.run(team.run(n_round=n_round))

if __name__ == '__main__':
    app()

这段代码首先定义了一个 main 函数,并创建一个 Team 对象。然后,我们使用 team.hire() 方法雇佣了三个角色。最后,我们使用 team.run() 方法运行团队,并打印输出结果。

运行团队

现在,你可以运行这段代码,并观察团队之间的协作:

python3 examples/build_customized_multi_agents.py --idea "write a function that calculates the product of a list"

总结

本教程展示了如何使用 MetaGPT 创建一个简单的 AI 团队,并演示了如何定义角色和动作,以及如何运行团队。你可以在此基础上进一步扩展你的团队,使其能够执行更复杂的任务。

更多学习资源

发表评论