Sub topic 3
What a subagent is
A subagent is a separate agent instance that a parent agent starts to handle one scoped piece of work. The subagent runs in its own context window. It does the work, then returns a result to the parent. This chapter defines the term, shows how a subagent differs from the parent, and lists the errors people make most often.
Assumed prerequisites
This chapter assumes you have used an AI coding assistant in a terminal or editor and know what a tool call is. It also assumes you know that a model has a context window, which is the limited amount of text it can consider at once. You should be able to read short Python programs.
The single-agent loop, briefly
A single coding agent repeats one cycle. It reads the conversation so far, decides on an action, calls a tool (read a file, run a test, edit code), and receives an observation. The observation is added to the conversation, and the cycle starts again.
Every step adds text to one shared context window. On a long task this is a problem. Test logs, file dumps, and dead ends pile up. The model has less room for the instructions that matter, and it can lose track of earlier decisions.
A subagent addresses this by moving part of the work into a second loop with its own, separate window.
The definition
A subagent has four properties:
- It is started by another agent. The parent (often called the orchestrator) decides when to create it and what to ask of it.
- It has its own context. It does not see the parent's conversation. It sees only its system prompt and the brief the parent gives it.
- It runs its own loop. It makes its own tool calls and reads its own observations until it finishes or fails.
- It returns a result. Usually this is a short summary. The parent receives that summary, not the subagent's full transcript.
The second and fourth properties together are called context isolation. The parent's window grows by one summary instead of by every step the subagent took.
What the subagent does and does not inherit
The most common misunderstanding is about inheritance. A subagent is not a copy of the parent. Compare the two:
| Item | Parent agent | Subagent |
|---|---|---|
| Conversation history | Full history with the user | None. Only the brief. |
| Context window | Shared by the whole session | Fresh and separate |
| Tools | Whatever the session allows | Whatever the parent grants, often fewer |
| Files on disk | The working directory | The same files unless you isolate the workspace |
| Output to the user | Talks to the user directly | Returns a result to the parent |
The last row of the file row matters. Context is isolated, but the file system is usually not. Two subagents pointed at the same directory can overwrite each other's edits. A later chapter covers branches and git worktrees for that problem.
A minimal orchestrator
The following program starts two subagents at the same time. Each one is represented by a placeholder function. Replace the body of run_subagent with a call to your own agent runtime.
import asyncio
from dataclasses import dataclass
@dataclass
class Task:
name: str
brief: str
async def run_subagent(task: Task) -> dict:
# Placeholder: replace with a call to your agent runtime.
# The subagent receives only the brief, not the parent's history.
await asyncio.sleep(0.1)
return {"name": task.name, "status": "ok", "summary": f"finished {task.name}"}
async def orchestrate(tasks: list[Task]) -> list[dict]:
outcomes = await asyncio.gather(
*(run_subagent(t) for t in tasks), return_exceptions=True
)
results = []
for task, outcome in zip(tasks, outcomes):
if isinstance(outcome, Exception):
results.append({"name": task.name, "status": "failed", "summary": str(outcome)})
else:
results.append(outcome)
return results
if __name__ == "__main__":
tasks = [
Task("update-docs", "Update README usage section for the new --verbose flag."),
Task("add-tests", "Add unit tests for parse_args in tests/test_cli.py."),
]
for result in asyncio.run(orchestrate(tasks)):
print(result)Three details are worth noting:
run_subagenttakes aTask, and the task holds only a name and a brief. That mirrors the real boundary: the brief is the only channel from parent to subagent.return_exceptions=Truemakesasyncio.gatherreturn a failure as a value instead of raising it. One crashed subagent then does not discard the other results.- The orchestrator records a
failedstatus for any task that raised. It does not hide the failure or abort the run.
What the parent gets back
The parent receives a result object, not a shared memory. In the program above, each result is a dictionary with name, status, and summary. Real runtimes vary, but the shape is similar: a status and some text.
This has a consequence. The summary is a lossy compression of what the subagent did. If the subagent found a subtle problem and left it out of the summary, the parent never learns about it. A good brief asks the subagent to report what the parent needs to make its next decision. The brief below does this in its final line.
Goal: Add unit tests for the parse_args function in src/cli.py.
Context: parse_args builds an argparse parser with --verbose and --output options. Tests live in tests/ and use pytest.
Scope: Create or edit only tests/test_cli.py. Do not change files under src/.
Constraints: Do not add new dependencies. Tests must run offline.
Done when: pytest tests/test_cli.py passes.
Return: A short summary of the tests added, the command you ran to check them, and its result. Do not paste full file contents.Later chapters treat briefs in detail. For now, notice that the brief repeats facts the parent already knows, such as the test framework and the file location. That repetition is deliberate. The subagent cannot look them up in a conversation it never saw.
A subagent is not a thread, a function, or a person
Three comparisons help fix the idea.
- Not a function call. A function is deterministic and returns the same output for the same input. A subagent is a model running a loop, so the same brief can produce different results and different failures.
- Not a thread. Threads share memory. Subagents share nothing except the file system and whatever the brief and tools provide.
- Not an autonomous colleague. A subagent has no memory of earlier delegations unless you pass it in. Each start is a cold start.
Common errors
- Assuming the subagent knows the conversation. A brief such as "fix the bug we discussed" fails, because the subagent never saw the discussion. State the bug.
- Treating the summary as proof. A subagent can report success when its work is wrong. A summary is a claim. Check it by running the tests yourself or by reading the diff.
- Sharing one directory between parallel writers. Context isolation does not protect files. Use separate branches or worktrees.
- Delegating tiny tasks. Starting a subagent has a cost in time and tokens. If the work is a single file read, do it in the parent.
- Leaving the return format open. Without a format, a subagent may paste thousands of lines back and undo the benefit of isolation.
- Ignoring failures. If you drop exceptions or treat a missing result as success, the orchestrator reports a finished run that did not finish.
When this model is worth using
A subagent pays off when a piece of work is self-contained, produces noisy intermediate output, or can run beside other work. Searching a large codebase for every caller of a function is a good example: the search reads many files, but the parent needs only a list of locations. Work that depends tightly on the parent's evolving understanding is a poor fit. Later chapters cover how to decide.
Exercise
A parent agent tells a subagent, "Now apply the same fix to the other module." The subagent produces unrelated changes. Give two reasons the brief failed, and rewrite it so it would work.
Show answer
The subagent has no access to the parent's conversation, so "the same fix" and "the other module" refer to nothing it can see. The brief also names no scope or finish condition, so the subagent had no way to know where to stop. A working brief states the goal ("Replace the deprecated call loadconfig(path) with loadconfig(path=path) in src/billing.py"), the scope ("edit only src/billing.py"), a check ("pytest tests/test_billing.py passes"), and the return format ("summarize the lines changed and the test result").
Exercise
In the Python orchestrator, what changes if you remove return_exceptions=True, and why does it matter when one of several subagents crashes?
Show answer
Without it, asyncio.gather raises the first exception to the caller of orchestrate. The function exits before building the results list, so the orchestrator loses the outcomes of the tasks that succeeded and records no failed status. With return_exceptions=True, each failure comes back as a value, so the orchestrator can report which task failed and keep the other results.