介绍
(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)= 发消息 + 分配任务 + 记录日志
- 它管的是:谁给谁发了什么、任务分给谁、日志存哪里。只管任务的 "交付",不管执行顺序。
- 只负责 通讯 这块的内容;