Sub topic 10
Subagents as a Way to Isolate Context
This chapter assumes you have read the earlier chapters on context growth and prompt caching. You should know that an agent loop resends its whole context on every turn, and that tool output is the main thing that makes that context grow. It also assumes you can read short Python programs.
The problem subagents solve
In a single-agent loop, every file read, search result and test log stays in the context until the session ends. Each later turn pays for all of it again as input tokens. Much of that material is only useful for a few turns. An agent that greps a large repository to find one function keeps thousands of lines of search output in its context long after it has found the answer.
A subagent is a separate agent loop that the main agent starts to do one task. The subagent has its own context window. It does its work there, and it returns a short result to the main agent. The main agent never sees the subagent's intermediate steps. This is called context isolation.
The saving comes from what the parent does not carry. The subagent may read 30,000 tokens of files, but the parent receives a 500-token summary. Every later parent turn resends the 500 tokens, not the 30,000.
What the subagent costs
Isolation does not make the work free. The subagent's tokens are still billed. The subagent pays for its own loop, including the repeated resending of its own growing context. The gain is that this cost is bounded and then discarded, instead of being added to every remaining parent turn.
You can model the trade with the loop-cost function from the earlier chapter on agent loop cost. The function below compares two ways to run a 20-turn session. In the first, the parent does an exploration step itself. In the second, a subagent does it and returns a summary.
def loop_input_tokens(system_tokens, step_tokens, turns):
"""Total input tokens billed across an agent loop with no caching."""
total = 0
context = system_tokens
for _ in range(turns):
total += context
context += step_tokens
return total
def parent_only(system_tokens, explore_tokens, step_tokens, later_turns):
"""The parent reads explore_tokens of material, then keeps working."""
context = system_tokens + explore_tokens
return loop_input_tokens(context, step_tokens, later_turns)
def with_subagent(system_tokens, explore_tokens, summary_tokens,
sub_step_tokens, sub_turns, step_tokens, later_turns):
"""A subagent explores in its own loop; the parent receives a summary."""
sub_cost = loop_input_tokens(system_tokens, sub_step_tokens, sub_turns)
parent_cost = loop_input_tokens(system_tokens + summary_tokens,
step_tokens, later_turns)
return sub_cost + parent_cost
a = parent_only(5_000, 30_000, 2_000, 15)
b = with_subagent(5_000, 30_000, 500, 6_000, 5, 2_000, 15)
print(a) # 975000
print(b) # 502500The parent-only run carries 30,000 tokens of exploration through 15 turns. The subagent run pays for five small turns in a separate context and then keeps the parent small. Here the subagent version bills about half the input tokens. This model has no caching, so treat the numbers as a comparison of shapes, not a forecast.
When isolation pays off and when it does not
The saving depends on how much noise the parent avoids and how many turns remain after the noisy step.
| Situation | Subagent helps? | Reason |
|---|---|---|
| Searching a large codebase for one answer | Yes | Large intermediate output, small final answer |
| Running a long test suite and reporting failures | Yes | Logs are big, the useful part is a few lines |
| Reading one small file you need to edit | No | The parent needs the exact text, not a summary |
| Task near the end of the session | Rarely | Few remaining turns to save on |
| A step whose full output the parent must reason over | No | A summary loses detail the parent needs |
A good candidate has three traits. Its input is large, its useful output is small, and it can be described in a self-contained instruction.
Failure modes
Lossy summaries
The parent only knows what the subagent writes back. If the summary omits a file path, a line number or a caveat, the parent either works with a wrong picture or has to repeat the exploration. Ask for structured output with the facts you will need, such as file paths, function names and line numbers, rather than free-form prose.
Thin task descriptions
A subagent starts with none of the parent's history. If the instruction says "fix the failing test" and the subagent does not know which test, it spends tokens rediscovering it. The instruction must carry the goal, the relevant paths, and the format of the answer.
Fixed overhead per subagent
Each subagent starts with its own system prompt and tool definitions. Those tokens are billed on every turn of the subagent loop. For a task that takes two turns, the setup can cost more than the saving. If the prefix is identical across subagent runs, prompt caching can reduce this overhead, as covered in the caching chapter.
Parallel subagents multiply spend
Running five subagents at once finishes sooner, but it bills five loops. Parallelism improves latency, not cost. Use it when time matters and the budget allows.
Delegating work that should stay local
Edits are a poor fit for isolation when the parent needs to see exactly what changed. If a subagent edits files and returns "done", the parent must re-read the files to verify, which brings back the tokens you tried to avoid. Prefer having the subagent return a diff summary, or keep edits in the parent.
Combining subagents with model routing
A subagent is a natural place to use a cheaper model. Exploration and log-reading tasks usually need less reasoning than planning or editing. You can assign the subagent a smaller tier while the parent keeps a stronger one. The routing table from the routing chapter can carry the subagent's task type:
ROUTES = {
"plan": "large-model",
"edit": "mid-model",
"explore": "small-model",
"summarize_tool_output": "small-model",
"run_tests": "small-model",
}
def pick_model(step_kind, default="mid-model"):
return ROUTES.get(step_kind, default)
def spawn_subagent(task, step_kind="explore"):
"""Describe a subagent run: which model, and what it must return."""
return {
"model": pick_model(step_kind),
"instruction": task,
"return_format": "bullet list of file paths with line numbers, max 200 words",
}
print(spawn_subagent("Find where HTTP retries are configured in src/"))Two cautions apply. A weaker model may miss the relevant file, so the parent can pay for a second search. Check cost per resolved task, as described in the evaluation chapter, instead of assuming the cheaper tier saves money.
Measuring whether it worked
Compare sessions on the same task with and without subagents using usage data from the API. Look at three numbers:
- Total input tokens across the parent and all subagents. This must include subagent usage, or the comparison will look better than it is.
- Peak parent context size. This shows whether isolation kept the parent small.
- Whether the task was resolved. A cheaper run that fails costs more per resolved task.
Practical guidelines
- Delegate steps with large output and small results, such as search, log triage and reading many files.
- Write self-contained instructions that name the paths, the goal and the exact return format.
- Ask for facts the parent will act on, with locations, not narrative.
- Keep edits and exact-text work in the parent.
- Limit the subagent's turns so a stuck exploration cannot run up cost, using the step limits from the guardrails chapter.
- Count subagent tokens in every cost report.
Exercise
A parent agent has 5,000 tokens of system prompt and will run 10 more turns, each adding 2,000 tokens. It first needs to explore 20,000 tokens of files. Using loop_input_tokens and no caching, compute the parent's input tokens if it explores itself, and if instead a subagent returns a 400-token summary. Ignore the subagent's own cost. What does the answer leave out?
Show answer
Parent exploring itself: starting context is 25,000, so total = 10 x 25,000 + 2,000 x (0+1+...+9) = 250,000 + 90,000 = 340,000. With the subagent: starting context is 5,400, so total = 10 x 5,400 + 90,000 = 144,000. The parent saves 196,000 input tokens. The answer leaves out the subagent's own billed loop (its system prompt resent each turn plus the files it reads), which must be added before judging the saving. The subagent only wins if its cost is less than 196,000 tokens equivalent, in dollars after pricing and any cheaper model tier are applied.
Exercise
Name two situations where you should not use a subagent, and give the reason for each.
Show answer
Reading a small file the parent will edit, because the parent needs the exact text and a summary loses it. Also a step near the end of a session, because few turns remain to benefit from a smaller context, so the subagent's fixed setup cost outweighs the saving. Other valid answers include tasks where the parent must reason over the full output.