# S15 Agent Teams 代码讲解 这一节只讲相对 S14 新增的内容: **Lead Agent 可以启动队友 Agent,并通过文件邮箱互相发消息。** --- ## 1. 本节新增内容 - `MessageBus`:基于文件的消息总线。 - `.mailboxes/`:每个 Agent 的收件箱目录。 - `active_teammates`:记录正在运行的队友。 - `spawn_teammate_thread()`:在后台线程中启动队友 Agent。 - `run_spawn_teammate()`:Lead 启动队友的工具处理器。 - `run_send_message()`:Lead 给队友发消息。 - `run_check_inbox()`:Lead 检查收件箱。 - 3 个新工具:`spawn_teammate`、`send_message`、`check_inbox`。 --- ## 2. MessageBus 数据结构 消息保存成 JSONL,每行是一条消息。 单条消息结构: ```python { "from": "lead", "to": "worker1", "content": "请检查这个文件", "type": "message", "ts": 1720000000.0 } ``` 文件路径: ```text .mailboxes/ lead.jsonl worker1.jsonl ``` 每个 Agent 有自己的收件箱。 --- ## 3. `MessageBus.send()` 作用:把消息追加到目标 Agent 的邮箱文件。 ```python BUS.send("lead", "worker1", "请检查测试") ``` 会写入: ```text .mailboxes/worker1.jsonl ``` --- ## 4. `MessageBus.read_inbox()` 作用:读取某个 Agent 的收件箱。 教学版采用“读完即删除”: ```python read_text() unlink() ``` 这表示消息被消费了。 --- ## 5. `spawn_teammate_thread(name, role, prompt)` 作用:启动一个队友 Agent。 队友有自己的: ```python messages: list[dict] system: str sub_tools: list[dict] sub_handlers: dict[str, function] ``` 队友的工具包括: ```text bash read_file write_file send_message ``` 重点是:队友可以通过 `send_message` 把结果发回 Lead。 --- ## 6. Lead 工具 Lead 新增三个团队工具: ```python spawn_teammate(name, role, prompt) send_message(to, content) check_inbox() ``` 模型调用示例: ```python { "name": "spawn_teammate", "input": { "name": "reviewer", "role": "代码审查员", "prompt": "请检查当前改动" } } ``` --- ## 7. 本节课堂重点 Agent Team 的本质是: ```python 多个 Agent 各自有独立 messages 通过 MessageBus 交换信息 Lead 负责启动、收消息、继续决策 ``` 这不是简单的子 Agent 摘要返回,而是更接近多 Agent 协作。