# S06 Subagent 代码讲解 这一节只讲相对 S05 新增的内容: **父 Agent 可以通过 `task` 工具启动一个全新上下文的子 Agent。** --- ## 1. 本节新增内容 - `SUB_SYSTEM`:子 Agent 专用系统提示词。 - `SUB_TOOLS`:子 Agent 可用工具列表。 - `SUB_HANDLERS`:子 Agent 工具分发器。 - `extract_text()`:从模型返回的 content blocks 里提取文本。 - `spawn_subagent()`:创建并运行子 Agent。 - `task` 工具:父 Agent 用它把复杂子任务交给子 Agent。 --- ## 2. 父 Agent 和子 Agent 的区别 父 Agent 使用自己的 `messages`: ```python parent_messages = [...] ``` 子 Agent 启动时使用全新的 `messages`: ```python messages = [{"role": "user", "content": description}] ``` 这叫上下文隔离。 子 Agent 不会继承父 Agent 的完整历史,只拿到父 Agent 分配的任务描述。 --- ## 3. `task` 工具的数据结构 父 Agent 调用 `task` 时,模型会生成: ```python { "type": "tool_use", "name": "task", "input": { "description": "请检查这个模块的问题,并给出结论" } } ``` 程序执行: ```python spawn_subagent(description) ``` 子 Agent 完成后,只返回一个摘要字符串。 --- ## 4. `SUB_TOOLS` 子 Agent 有工具,但没有 `task` 工具: ```python SUB_TOOLS = [ bash, read_file, write_file, edit_file, glob ] ``` 为什么不给子 Agent `task`? 为了避免无限递归: ```python 父 Agent -> 子 Agent -> 子子 Agent -> ... ``` 教学版本先把这个边界锁住。 --- ## 5. `spawn_subagent(description)` 核心流程: ```python 创建新的 messages 最多循环 30 轮 调用模型 如果模型要用工具,就执行工具并回填 tool_result 如果模型停止,就提取最终文本 返回摘要给父 Agent ``` 这里的 30 轮是安全上限,防止子 Agent 一直循环。 --- ## 6. 本节课堂重点 Subagent 的本质不是“多了一个模型”,而是: ```python 用新的 messages 开一个隔离任务 给它一组受限工具 最后只把摘要返回父 Agent ``` 这就是复杂任务拆分的基础。