Lesson 04

Subagent 子代理

进程隔离天然带来上下文隔离

// Parent-Child Architecture

PARENT AGENT messages = [ {user: "重构项目..."} {assistant: "好的..."} {user: tool_result} ... (full history) ] Parent LLM 主代理 TOOLS (5) bash read write edit task CHILD AGENT (Subagent) messages = [ {user: "子任务描述"} ] // fresh context! discarded after return Child LLM 子代理 TOOLS (4) — NO TASK! bash read write edit task dispatch task tool_use summary compressed result PARENT RECEIVES tool_result: "已完成重构, 修改了 3 个文件, 所有测试通过。" // only summary, not full process ANTI-RECURSION Child has no "task" tool → cannot spawn grandchildren

Key Concepts 核心概念

01

上下文隔离 Context Isolation

子代理启动时 messages = [],是全新的对话。不共享父代理的对话历史,天然避免了上下文污染。

Child agent starts with empty messages. It does not share the parent's conversation history, naturally preventing context pollution.

02

信息压缩 Information Compression

子代理完成任务后,只返回一段总结文字。父代理不需要知道子代理执行了多少步、调用了什么工具——只看结果。

Child returns only a summary. The parent doesn't need to know how many steps or tools were used -- only the result matters.

03

防递归 Anti-Recursion

子代理的工具列表里没有 task 工具,所以它不能再创建子代理。深度固定为 1,不会出现无限嵌套。

The child's tool list excludes the "task" tool, so it cannot spawn grandchildren. Max depth is always 1.

Parent vs Child 对比

Dimension 维度 Parent 父代理 Child 子代理 说明
Messages Full history [] (fresh) 上下文完全隔离
Tools 5 (bash, read, write, edit, task) 4 (bash, read, write, edit) 无 task = 不能生子代理
Return Full response to user Summary string only 信息压缩
Lifecycle Lives for session Created & destroyed per task 用完即弃
System Prompt Full prompt + tools Task description only 精简指令

试一试 Try It Out

1

"使用子任务找出这个项目使用什么测试框架"

"Use a subtask to find what testing framework this project uses"

2

"委托:读取所有 .java 文件并总结每个文件的作用"

"Delegate: read all .java files and summarize what each one does"

3

"使用任务创建一个新模块,然后从这里验证它"

"Use a task to create a new module, then verify it from here"