Sub topic 12
Splitting Work Across Subagents with Separate Contexts
This chapter assumes you have read the earlier chapters on the parts of a context, token budgets, tool results, and compaction. You should be comfortable with the idea that every model call sees only what you put in its window.
Why one large context stops working
A single agent that does everything accumulates context. It reads files, runs searches, calls tools, and tries dead ends. Each step adds tokens, and most of those tokens only matter for a short time.
Suppose an agent must answer "Which of our services still call the deprecated billing endpoint?" It may open 40 files to find the answer. The answer is three lines long. The other 40 files are noise for every later step, yet they stay in the window. They cost tokens, they invite distraction (see the chapter on context failures), and they push useful content toward the middle of the window.
A subagent is a separate model call, or a loop of calls, that runs with its own fresh context. A parent agent gives it a task. The subagent does the messy work in its own window. It then returns a short result. The parent never sees the 40 files. It sees only the three-line answer.
This is context isolation. You are not making the window bigger. You are deciding that some work happens in a different window, and that only a small, chosen piece of its output crosses back.
What crosses the boundary
The boundary between parent and subagent has two directions. Both need design.
Parent to subagent: the task brief
The subagent starts with nothing. It does not see the parent's history, the user's earlier messages, or the parent's reasoning. Whatever it needs must be in the brief. A weak brief is the most common cause of poor subagent results.
A useful brief contains:
- The goal, stated as the question to answer or the artifact to produce.
- Constraints that matter, such as which directory to search or which sources to trust.
- Facts the parent already knows, so the subagent does not rediscover them.
- The output format and a length limit.
- A stopping condition, so the subagent knows when it is done.
Compare two briefs for the same task.
| Brief | Text | Likely outcome |
|---|---|---|
| Weak | "Look into the billing thing." | The subagent guesses what "billing thing" means and may return an unrelated finding. |
| Strong | "List every service under `services/` that imports `billing_v1`. Return one line per service: name, file path, line number. Maximum 30 lines. Ignore tests." | The subagent returns a checkable list the parent can use directly. |
Subagent to parent: the result
The returned text becomes part of the parent's context, so it counts against the parent's budget. Ask for a structured, bounded result. Free-form narration from the subagent ("First I looked at... then I noticed...") brings back exactly the clutter you wanted to avoid.
Good results share these properties:
- They are short relative to the work done.
- They include pointers (file paths, IDs, URLs) so the parent can load details just in time if needed.
- They separate facts from guesses. The subagent should mark what it verified and what it inferred.
A minimal implementation
The following code shows the pattern with a stand-in model function. Replace call_model with a real API call. The structure matters more than the model.
def call_model(system, messages, max_output_tokens=500):
# Stand-in for a real model call. Replace with your provider's client.
# It returns a string. Here it just reports what it was given.
return f"[model reply to {len(messages)} message(s), system={system[:30]!r}]"
def run_subagent(brief, max_result_chars=1200):
# A fresh context: only the system prompt and the brief.
system = (
"You are a research subagent. Complete the task in the brief. "
"Reply with a short result only: findings, then a list of sources. "
"Mark anything you did not verify as UNVERIFIED."
)
messages = [{"role": "user", "content": brief}]
result = call_model(system, messages)
# Enforce the size limit at the boundary, not by trusting the subagent.
if len(result) > max_result_chars:
result = result[:max_result_chars] + " [truncated]"
return result
def parent_step(parent_history, question):
brief = (
f"Question: {question}\n"
"Search only the services/ directory. Ignore tests.\n"
"Return one line per finding: name, path, line number. Max 30 lines."
)
result = run_subagent(brief)
# Only the short result enters the parent's history.
parent_history.append({"role": "user", "content": f"Subagent result:\n{result}"})
return parent_history
history = parent_step([], "Which services call billing_v1?")
print(history[0]["content"])Note two design choices. The subagent's messages list is a new list, so nothing leaks in from the parent. The truncation happens in code at the boundary, so a verbose subagent cannot flood the parent.
When subagents help
Subagents fit work with these traits:
- The task is read-heavy and the answer is small. Searching a codebase, scanning logs, and summarizing long documents all fit.
- Subtasks are independent. Several subagents can run in parallel, each with its own window, and the parent combines their short results.
- Different subtasks need different tools or instructions. A subagent can carry a narrow system prompt and a small tool set. This keeps tool definitions out of the parent (see the chapter on tool context).
- The parent's session is long. Isolation delays the need for compaction.
When subagents hurt
Isolation has costs. Weigh them before splitting.
Lost information
The subagent sees only the brief. If the parent forgets to include a constraint, the subagent will not know it. The parent then receives a result that looks complete but ignores the constraint. This is a context clash risk in a new form: the parent and subagent hold different assumptions, and nothing reconciles them.
Tightly coupled work
If subtask B depends on the exact decisions made in subtask A, separate contexts make them drift apart. Two subagents that each write part of the same module may choose incompatible names or interfaces. Writing code in parallel is riskier than reading in parallel. For coupled work, keep one agent in one context, or give a single subagent the whole coupled task.
Token cost
Subagents do not reduce total tokens. Each one pays for its own system prompt, tools, and reading. Total spend often rises. What falls is the size of the parent's window. You trade cost and latency overhead for a cleaner, smaller parent context. For a small task, a direct call is cheaper and simpler.
Compounding errors
A subagent may summarize wrongly, and the parent cannot easily see that, because it never saw the sources. If a poisoned or mistaken fact enters the parent through a result, the parent treats it as trusted. Pointers help here. When the result includes file paths and line numbers, the parent can spot-check the claims that matter.
Choosing between subagents and other techniques
Subagents are one of several ways to keep a window small. Pick based on what the content is and whether you will need it again.
| Situation | Better tool |
|---|---|
| Old conversation turns are crowding the window | Trimming or compaction |
| Facts must survive across sessions | External memory or notes |
| One lookup against an index | Retrieval, loaded just in time |
| A large exploration with a small answer | Subagent |
| Independent explorations that can run at once | Parallel subagents |
| Tightly coupled edits to one artifact | A single agent |
Practical rules
- State the output format and size limit in every brief.
- Enforce the limit in code, not only in the prompt.
- Ask for pointers alongside findings.
- Give each subagent only the tools it needs.
- Do not pass the full parent history by default. Pass the facts the subagent needs, selected for relevance.
- Log each brief and result. When the final answer is wrong, you need to see which boundary lost or distorted the information.
- Test the split with a fixed set of tasks, as described in the chapter on evaluation. Compare answer quality and total token cost with and without subagents.
Exercises
Exercise
A parent agent asks a subagent to "summarize the repository." The subagent returns 6,000 tokens of narrative, and the parent's window fills up. Name two changes that fix this, one in the brief and one in the code.
Show answer
In the brief, specify the output format and a length limit (for example, "at most 20 lines: path and one-sentence purpose"). In the code, enforce a maximum result size at the boundary by truncating or rejecting oversized results before they enter the parent's history. Asking for file paths as pointers also helps, because the parent can load details later.
Exercise
You need to rename a function and update all 12 call sites across a codebase, keeping names consistent. Would you split the call sites across 12 parallel subagents? Explain.
Show answer
Probably not. The edits are tightly coupled: every site must use the exact new name and signature, and separate contexts can drift apart. A better design is one agent (or one subagent) that owns the whole change, optionally using a read-only subagent first to find the call sites and return their paths and line numbers.
Exercise
Total token usage went up after you added subagents, but answer quality also improved. Is the change worth keeping? What would you measure?
Show answer
It can be. Subagents shift tokens into separate windows and keep the parent's window small, so higher total cost is expected. Run a fixed test set with and without subagents, and compare answer accuracy, total tokens, latency, and the parent's peak window size. Keep the change only if the quality gain justifies the added cost and latency.