项目03-手搓Agent之团队协作(发消息/分配任务)

介绍

(1)包含 Agent 之间的通信,如何通信;(2)邮箱的构建;(3)任务如何构建;

1. 入口:示例演示

python 复制代码
def demo_team_collaboration():
    """演示 4: 团队协作"""
    print("\n=== 演示 4: 团队协作 ===")
    collab = TeamCollaboration()

    # 1 初始化邮箱
    collab.init_agent_mailbox("coder")
    collab.init_agent_mailbox("tester")

    # 2 发送消息
    msg_id = collab.send_message("lead", "coder", "请实现登录功能", priority=10)
    print(f"✅ 消息已发送: {msg_id}")

    # 3 创建协作任务
    task_id = collab.create_collaborative_task(
        "请实现登录功能",
        assigned_to="coder"
    )
    # 4 统计
    print(f"✅ 协作任务已创建: {task_id}")
    print(f"📊 协作统计: {collab.get_collaboration_stats()}")
  • 第一步: 先初始化两个 Agent 的邮箱;
  • 第二步: Lead 向 sub_agent 发任务,并记录日志;
  • 第三步: 构建任务状态(包含被分配的 agent,任务内容);

2. 团队协作类 TeamCollaboration

主要包含三个功能:

  • 初始化邮箱 :本质上基于字典构建而成,邮箱由 MailBox 实现;
  • 发送消息: 发送方向接收方发送任务,并记录在日志中;
  • 创建任务: 根据任务赋予状态,基于 TodoManager 类;
python 复制代码
class TeamCollaboration:
    """👥 团队协作模块 - 消息邮箱 + 待办任务管理
        核心功能:实现智能体之间的消息通信、任务分配、协作日志记录
    """
    def __init__(self):
        self.mailbox_system = {} # 邮箱系统:key=智能体名称,value=邮箱实例
        self.todo_mgr = TodoManager() # 待办管理器:管理协作任务
        self.collaboration_log = [] # 协作日志:记录所有消息和操作
        self.team_dir = ".team"  # 目录配置 
        self.log_file = os.path.join(self.team_dir, "collaboration_log.json") # 团队消息总线,日志
        self._load_logs() # 启动时加载历史日志
        
		def _load_logs(self):
        """启动时加载历史协作日志"""
        if os.path.exists(self.log_file):
            with open(self.log_file, "r", encoding="utf-8") as f:
                try:
                    self.collaboration_log = json.load(f)
                except:
                    self.collaboration_log = []
		
    def init_agent_mailbox(self, agent_name: str):
        """初始化指定智能体的邮箱"""
        self.mailbox_system[agent_name] = Mailbox(agent_name=agent_name)
        
    def _save_logs(self):
        """每次操作后自动保存日志"""
        with open(self.log_file, "w", encoding="utf-8") as f:
            json.dump(self.collaboration_log, f, indent=2, ensure_ascii=False)

    def send_message(self, from_agent: str, to_agent: str, content: str, msg_type: str = "task", priority: int = 5) -> str:
        """智能体之间发送消息
            :param from_agent: 发送方
            :param to_agent: 接收方
            :param content: 消息内容
            :param msg_type: 消息类型(任务/通知/求助)
            :param priority: 优先级1-10
            :return: 消息ID
        """
        # 接收方无邮箱则自动创建
        if to_agent not in self.mailbox_system:
            self.init_agent_mailbox(to_agent)
        # 推送消息到目标邮箱
        msg_id = self.mailbox_system[to_agent].push(to=to_agent, content=content, msg_type=msg_type, from_agent=from_agent, priority=priority)
        # 记录协作日志(时间 + 收发方 + 类型 + 消息ID)
        log = {
            "timestamp": datetime.now().isoformat(),
            "from": from_agent,
            "to": to_agent,
            "type": msg_type,
            "msg_id": msg_id
        }
        self.collaboration_log.append(log)
        self._save_logs()
        
        return msg_id

    def create_collaborative_task(self, title: str, description: str, assigned_to: str = None, dependencies: List[str] = None) -> str:
        """创建团队协作待办任务
            :param title: 任务标题
            :param description: 任务描述
            :param assigned_to: 负责人
            :param dependencies: 依赖任务
            :return: 任务ID
        """
        return self.todo_mgr.create_task(description=description, assigned_to=assigned_to, dependencies=dependencies)

    def get_collaboration_stats(self) -> Dict:
        """获取团队协作统计:总消息数、在线智能体、最近10条日志"""
        return {"total_messages": len(self.collaboration_log), "agents": list(self.mailbox_system.keys()), "recent_activity": self.collaboration_log[-10:]}

3 总结

团队协作(TeamCollaboration)= 发消息 + 分配任务 + 记录日志

  • 它管的是:谁给谁发了什么、任务分给谁、日志存哪里。只管任务的 "交付",不管执行顺序。
  • 只负责 通讯 这块的内容;
相关推荐
m0_4939345341 分钟前
如何监控AWR数据收集Job_DBA_SCHEDULER_JOBS中的BSLN_MAINTAIN_STATS
jvm·数据库·python
xiaotao1311 小时前
01-编程基础与数学基石:概率与统计
人工智能·python·numpy·pandas
bukeyiwanshui1 小时前
20260417 DNS实验
linux
代码中介商1 小时前
Linux 帮助手册与用户管理完全指南
linux·运维·服务器
赵侃侃爱分享1 小时前
学完Python第一次写程序写了这个简单的计算器
开发语言·python
a9511416421 小时前
Go语言如何操作OSS_Go语言阿里云OSS上传教程【完整】
jvm·数据库·python
2401_897190551 小时前
MySQL中如何利用LIMIT配合函数分页_MySQL分页查询优化
jvm·数据库·python
whuhewei1 小时前
为什么客户端不存在跨域问题
前端·安全
断眉的派大星1 小时前
# Python 魔术方法(魔法方法)超详细讲解
开发语言·python
妮妮喔妮2 小时前
supabase的webhook报错
开发语言·前端·javascript