Break big tasks down; each subtask gets a clean context
What You’ll Learn
- Why subagents need their own
messages[] - How to spawn a subagent and collect only its summary
- Why context isolation is more important than parallelism
The Problem
As the agent works, its messages array grows. Every file read, every bash output stays in context permanently. “What testing framework does this project use?” might require reading 5 files, but the parent only needs the answer: “pytest.”
The Solution
Subagents run with a fresh messages=[]. They explore, execute, and return only the final summary. The parent never sees the intermediate steps.
Parent agent Subagent
+------------------+ +------------------+
| messages=[...] | | messages=[] | <-- fresh
| | dispatch | |
| tool: task | ----------> | while tool_use: |
| prompt="..." | | call tools |
| | summary | append results |
| result = "..." | <---------- | return last text |
+------------------+ +------------------+
How It Works
-
The parent gets a
tasktool. The child gets all base tools excepttask(no recursive spawning). -
The subagent starts with
messages=[]and runs its own loop. Only the final text returns.
def run_subagent(prompt: str) -> str:
sub_messages = [{"role": "user", "content": prompt}]
for _ in range(30): # safety limit
response = client.messages.create(
model=MODEL, system=SUBAGENT_SYSTEM,
messages=sub_messages,
tools=CHILD_TOOLS, max_tokens=8000,
)
sub_messages.append({"role": "assistant",
"content": response.content})
if response.stop_reason != "tool_use":
break
# ...execute tools, append results...
return "...summary..."
What Changed From s03
| Component | Before (s03) | After (s04) |
|---|---|---|
| Tools | 5 | 5 (base) + task (parent) |
| Context | Single shared | Parent + child isolation |
| Subagent | None | run_subagent() function |
| Return value | N/A | Summary text only |
Try It
cd learn-claude-code
python agents/s04_subagent.py
Use a subtask to find what testing framework this project usesDelegate: read all .py files and summarize what each one doesUse a task to create a new module, then verify it from here
Key Takeaway
A subagent is mainly a context boundary. Give it a clean messages array so the parent stays focused on the main goal.