项目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)= 发消息 + 分配任务 + 记录日志

  • 它管的是:谁给谁发了什么、任务分给谁、日志存哪里。只管任务的 "交付",不管执行顺序。
  • 只负责 通讯 这块的内容;
相关推荐
kyriewen3 分钟前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
kyriewen34 分钟前
你写的代码没有测试,就像出门不锁门——Jest + Testing Library 从入门到不慌
前端·单元测试·jest
辞旧 lekkk37 分钟前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
yuzhiboyouye1 小时前
web前端英语面试
前端·面试·状态模式
2301_809204702 小时前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277772 小时前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
Aaswk2 小时前
Java Lambda 表达式与流处理
java·开发语言·python
canonical_entropy2 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
万邦科技Lafite3 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
东方小月3 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构