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

  1. The parent gets a task tool. The child gets all base tools except task (no recursive spawning).

  2. 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

ComponentBefore (s03)After (s04)
Tools55 (base) + task (parent)
ContextSingle sharedParent + child isolation
SubagentNonerun_subagent() function
Return valueN/ASummary text only

Try It

cd learn-claude-code
python agents/s04_subagent.py
  1. Use a subtask to find what testing framework this project uses
  2. Delegate: read all .py files and summarize what each one does
  3. Use 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.