使用MetaGPT 创建智能体(2)多智能体

在这里插入图片描述

先给上个文章使用MetaGPT 创建智能体(1)入门打个补丁:

补丁1: MeteGTP中Role和Action的关联和区别?这是这两天再使用MetaGPT时候心中的疑问,这里做个记录

Role(角色)和 Action(动作)是MetaGPT中的两个重要概念和对象,Role顾名思义也就是角色,这Role子类中表示一个独立的功能模块,一个Role里面调用多个Action;Action(动作)具体任务中的最小操作单元。

举个例子的话就是,一个讲师(Role),如果要讲课的话就需要备课(Action),开始讲课(Action),上课期间还有提问(Action),最后由多个讲师(Role)来完成整个学生上课的这个功能。


补丁2: 安装volcengine-python-sdk[ark]~=1.0.94报错

Could not build wheels for volcengine-python-sdk, which is required to install pyproject.toml-based projects

由于 Windows 系统有最长路径限制,导致安装失败,按照以下方式设置:


  1. 按下 Win+R ,输入 regedit 打开注册表编辑器。

  2. 设置 \HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem 路径下的变量 LongPathsEnabled 为 1



再蹭个热度:

deepseek前段时间爆火,这里写个怎么在MetaGPT中使用deepseek(本地启动版),使用的话也很方便,第一启动ollama里面的deepseek模型,打开控制台,输入

ollama run deepseek-r1

等待模型下载运行就好,修改config2.yaml配置文件

llm:
  api_type: "ollama"  # or azure / ollama / groq etc.
  model: "deepseek-r1"  # or gpt-3.5-turbo
  base_url: "http://localhost:11434/api"  # or forward url / other llm url
  api_key: "ollama"

然后就可以使用了,有一说一确实不错。



正文


多智能体指的就是创建多个智能体去进行执行任务,这也是实际业务中的常用处理。

多个智能体的使用大致3步,

1、定义多个Role,Action

2、Role中定义_watch监听相关Action

3、使用Team对象加入多个Role启动


MetaGPT 多智能体框架中,Team 对象是协调和管理多个智能体(Agent)协作的核心组件。它的作用类似于一个“虚拟团队”,负责组织智能体之间的交互、任务分配、通信协调,以及整体协作流程的控制。

Team 的核心作用

  1. 多智能体协作的容器
    Team 作为多个智能体的容器,集中管理智能体的生命周期(创建、销毁)、状态监控和资源分配。
  2. 任务分配与调度
    将复杂任务拆解为子任务,并根据智能体的角色(Role)和能力(Skill)动态分配任务,确保高效协作。
  3. 通信与协调
    管理智能体之间的通信(如消息传递、事件触发),避免冲突并确保信息同步。例如,在自动化客服系统中,协调“用户意图识别”和“工单生成”两个智能体的协作。
  4. 环境管理
    提供共享的上下文环境(如全局数据、知识库),使智能体可以访问统一的信息源,避免重复计算或数据不一致。
  5. 容错与恢复
    监控智能体运行状态,处理异常(如任务超时、逻辑错误),并触发恢复机制(如重试任务、切换备用智能体)。

代码

创建Role1和对应的Action1,第一个Role需要接收用户传来的指令,所以_watch监听用户UserRequirement消息,因为需要具体操作所以也不用重写_act函数(全部代码在最下面)

def parse_code(rsp):
    # r 定义原始字符串,忽略其中的所有转义字符
    pattern = r"```python(.*)```"
    match = re.search(pattern, rsp, re.DOTALL)
    code_text = match.group(1) if match else rsp
    return code_text

class Action1(Action):
    name:str = "Action1"
    PROMPT_TEMPLATE:str = """ 编写一个python函数,可以 {instruction} """

    async def run(self, instruction: str):
        prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)

        # 令 LLM 赋予这个动作能力
        rsp = await self._aask(prompt)
        # 解析返回内容
        code_text = parse_code(rsp)

        return code_text

# 角色
class Role1(Role):
    name:str = "Role1"
    profile:str = "Role1"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([UserRequirement])  # 监听来自用户或其他智能体的重要上游消息
        self.set_actions([Action1])

编写Role2和Action2,因为需要等待Action的执行内容,所以_watch监听Action1

class Action2(Action):
    name:str = "Action2"
    PROMPT_TEMPLATE:str = """ 
        上下文:{context} 
        假设您已导入给定函数,则使用pytest为其编写{k}个单元测试。 
    """

    async def run(self, context: str, k:int=3):
        prompt = self.PROMPT_TEMPLATE.format(context=context, k=k)

        rsp = await self._aask(prompt)
        code_text = parse_code(rsp)

        return code_text

class Role2(Role):
    name:str = "Role2"
    profile:str = "Role2"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([Action2])
        self._watch([Action1])  # 监听来自用户或其他智能体的重要上游消息

    async def _act(self) -> Message:
        todo = self.rc.todo
        context = self.get_memories() # 查找消息

        code_text = await todo.run(context, k=5) # 这里开始执行Action2的处理
        # role 消息角色
        # cause_by 专门用于追踪消息的触发来源,建立消息与动作(Action)之间的关联
        msg = Message(content=code_text, role=self.profile, cause_by=type(todo))

        return msg

最后Role3,Action3,监听Action2,监听是可以监听多个Action的

class Action3(Action):
    name:str = "Action3"
    PROMPT_TEMPLATE:str = """ 
        上下文:{context} 
        审查测试用例并提供一条关键意见: 
    """

    async def run(self, context: str):
        prompt = self.PROMPT_TEMPLATE.format(context=context)
        rsp = await self._aask(prompt)
        return rsp

class Role3(Role):
    name:str = "Role3"
    profile:str = "Role3"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([Action3])
        self._watch([Action2])

最后是运行,运行时创建Team对象,添加角色,然后运行

# 运行函数
async def main(idea:str,
               investment:float,
               n_round:int):
    # MetaGPT中的团队
    team = Team()
    # 添加角色
    team.hire([
        Role1(),
        Role2(),
        Role3()
    ])
    # 注入资源 invest 属性用于设定或表示团队对某个任务或目标的资源投入程度
    team.invest(investment=investment)
    team.run_project(idea) # 启动团队协作流程
    await team.run(n_round=n_round)

if __name__ == '__main__':
    asyncio.run(main('计算列表乘积的函数', 3.0, 3))

三个智能体

Role1,执行Action1,监听用户输入;

Role2,监听Action1,执行Action2;

Role3,监听Action2,执行Action3;

这就是多个智能体的合作使用,重点总结的话就是,监听_watch其他人,Team运行。

最后是全部代码

import asyncio
import re

from metagpt.actions import Action, UserRequirement
from metagpt.roles import Role
from metagpt.schema import Message
from metagpt.team import Team


# 多个智能体案例
def parse_code(rsp):
    # r 定义原始字符串,忽略其中的所有转义字符
    pattern = r"```python(.*)```"
    match = re.search(pattern, rsp, re.DOTALL)
    code_text = match.group(1) if match else rsp
    return code_text

class Action1(Action):
    name:str = "Action1"
    PROMPT_TEMPLATE:str = """ 编写一个python函数,可以 {instruction} """

    async def run(self, instruction: str):
        prompt = self.PROMPT_TEMPLATE.format(instruction=instruction)

        # 令 LLM 赋予这个动作能力
        rsp = await self._aask(prompt)
        # 解析返回内容
        code_text = parse_code(rsp)

        return code_text

# 角色
class Role1(Role):
    name:str = "Role1"
    profile:str = "Role1"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._watch([UserRequirement])  # 监听来自用户或其他智能体的重要上游消息
        self.set_actions([Action1])

class Action2(Action):
    name:str = "Action2"
    PROMPT_TEMPLATE:str = """ 
        上下文:{context} 
        假设您已导入给定函数,则使用pytest为其编写{k}个单元测试。 
    """

    async def run(self, context: str, k:int=3):
        prompt = self.PROMPT_TEMPLATE.format(context=context, k=k)

        rsp = await self._aask(prompt)
        code_text = parse_code(rsp)

        return code_text

class Role2(Role):
    name:str = "Role2"
    profile:str = "Role2"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([Action2])
        self._watch([Action1])  # 监听来自用户或其他智能体的重要上游消息

    async def _act(self) -> Message:
        todo = self.rc.todo
        context = self.get_memories() # 查找消息

        code_text = await todo.run(context, k=5) # 这里开始执行Action2的处理
        # role 消息角色
        # cause_by 专门用于追踪消息的触发来源,建立消息与动作(Action)之间的关联
        msg = Message(content=code_text, role=self.profile, cause_by=type(todo))

        return msg

class Action3(Action):
    name:str = "Action3"
    PROMPT_TEMPLATE:str = """ 
        上下文:{context} 
        审查测试用例并提供一条关键意见: 
    """

    async def run(self, context: str):
        prompt = self.PROMPT_TEMPLATE.format(context=context)
        rsp = await self._aask(prompt)
        return rsp

class Role3(Role):
    name:str = "Role3"
    profile:str = "Role3"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_actions([Action3])
        self._watch([Action2])


# 运行函数
async def main(idea:str,
               investment:float,
               n_round:int):
    # MetaGPT中的团队
    team = Team()
    # 添加角色
    team.hire([
        Role1(),
        Role2(),
        Role3()
    ])
    # 注入资源,invest 属性用于设定或表示团队对某个任务或目标的资源投入程度
    team.invest(investment=investment)
    team.run_project(idea) # 启动团队协作流程
    await team.run(n_round=n_round)



if __name__ == '__main__':
    # fire.Fire(main) 快速将 Python 对象(如函数、类、模块)转换为命令行接口(CLI)
    # main('编写一个计算列表乘积的函数', 3.0, 5)
    asyncio.run(main('计算列表乘积的函数', 2.0, 3))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值