标签: AGI

  • MetaGPT 中的记忆:让你的 AI 智能体拥有记忆力

    在之前的教程中,我们已经了解了智能体和多智能体系统。但一个真正强大的 AI 智能体,还需要拥有记忆能力。记忆可以帮助智能体积累经验,并根据过去的经验进行决策和行动。

    本教程将带你了解 MetaGPT 中的记忆功能,以及如何使用它来提升你的 AI 智能体的能力。

    MetaGPT 中的记忆

    在 MetaGPT 中,Memory 类是智能体记忆的抽象表示。当一个角色被初始化时,它会获得一个 Memory 对象,用于存储它观察到的所有消息。这些消息会被保存在一个列表中,方便以后检索。

    检索记忆

    当你需要使用记忆时,例如将记忆作为 LLM 的上下文,可以使用 self.get_memories() 方法。该方法的定义如下:

    def get_memories(self, k=0) -> list[Message]:
        """A wrapper to return the most recent k memories of this role, return all when k=0"""
        return self.rc.memory.get(k=k)

    该方法接受一个可选参数 k,用于指定要检索的最近记忆数量。如果 k 为 0,则返回所有记忆。

    例如,在之前的多智能体教程中,我们使用 get_memories() 方法将所有记忆作为上下文提供给测试者。这样,如果审查者提供了反馈,测试者可以参考之前的版本修改测试用例。代码片段如下:

    async def _act(self) -> Message:
        logger.info(f"{self._setting}: ready to {self.rc.todo}")
        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=todo)
    
        return msg

    添加记忆

    要添加记忆,可以使用 self.rc.memory.add(msg) 方法,其中 msg 必须是 Message 类的实例。

    建议在定义 _act 方法时,将动作输出的消息添加到角色的记忆中。角色通常需要记住它之前说过的话或做过的事,才能采取下一步行动。

    下一步

    本教程介绍了 MetaGPT 中的“短期记忆”概念。记忆的检索是基于简单的最近性原则。然而,还有许多其他类型的记忆,以及各种各样的记忆生成和检索技术。你可以参考 Memory 教程,了解如何使用记忆来真正提升你的智能体的性能。

  • 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 团队,并演示了如何定义角色和动作,以及如何运行团队。你可以在此基础上进一步扩展你的团队,使其能够执行更复杂的任务。

    更多学习资源

人生梦想 - 关注前沿的计算机技术 acejoy.com 🐾 步子哥の博客 🐾 背多分论坛 🐾 借一步网
Page Stats: PV: 2304 | UV: 1240
Last updated: 2025-06-25 12:31:50
沪ICP备2024052574号-1