Why a Deep Agent Should Hand Big Reading Jobs to Subagents

10 min read

The problem

Give one agent a big job, like "read these five log files and tell me which service is failing". It calls read_file five times. Each result lands in its message list. The answer it finally gives is one paragraph, but the five raw files stay in the context for every call that follows.

Then the user asks a follow-up. "Which one is worst?" The model must resend all five log files to answer a question that needs one sentence of them. Ask three follow-ups and you pay for those files three more times. The context also gets noisy: the paragraph that matters sits next to hundreds of lines that do not.

The fix is the same one a team lead uses. Hand the reading to someone else, and ask for a short report back. In a deep agent that someone is a subagent, and the property that makes it work is context isolation: the subagent gets a fresh context, does the messy work there, and only its final message comes back.

This part measures that effect, then walks through every way deepagents 0.7.42 lets you define a subagent.

How this code was tested

Every block ran on deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24 and Python 3.12.3. The code shows model="anthropic:claude-sonnet-4-6". All outputs in this part came from a scripted fake chat model that emits fixed tool calls. No output in this part came from a real model. The token counts are real counts of the requests the deepagents code built and sent to the model, counted with tiktoken's o200k_base encoding as a stand-in tokenizer. Real models tokenize differently, so treat the numbers as relative sizes.

The task tool

When a deep agent has subagents, it gets one extra tool: task. The model calls it with two arguments, description and subagent_type. The library's description for the tool begins with "Launch an ephemeral subagent to handle a complex, multi-step task."

Here is what happens at runtime, read from middleware/subagents.py:

sequenceDiagram
  participant M as Main agent
  participant L as LLM
  participant T as task tool
  participant S as Subagent
  participant F as Filesystem
  M->>L: messages + tools
  L-->>M: task description, type
  M->>T: run tool
  T->>S: new state, one HumanMessage
  S->>F: read_file x5
  F-->>S: file contents
  S-->>T: final AI message
  T-->>M: ToolMessage with that text
  M->>L: short result added

Three details matter. The subagent's message list starts with only the task description as a human message. Its messages and todos are never copied back: the source lists "messages", "todos" and "structured_response", among a few other keys, in _EXCLUDED_STATE_KEYS. And the reply is the subagent's last non-empty AI message text, or its structured response as JSON when it has one.

Other state keys do flow back. That includes files, so the virtual filesystem from Part 5 is the shared desk where a subagent can leave a full report for the main agent to read later.

Hand-drawn diagram: inside the main agent context, the user ask leads to a task call with description and subagent_type; a new state goes to the subagent context, which holds the description as its only human message, then five read_file calls of about 3.4k tokens each, then a final AI message; only that last text returns to the main agent as one short ToolMessage. Main used 2,668 tokens on its last call while the subagent peaked at 19,207 tokens

Measuring the isolation

We built two agents with the same job. Five synthetic log files of 100 lines each sit in state. The user asks for an error summary, then asks three follow-up questions on the same history.

  • No subagent: the main agent reads all five files itself.
  • With subagent: the main agent calls task once, and a log-analyst subagent does the five reads.

The subagent is a plain dict:

python
from deepagents import create_deep_agent

log_analyst = {
    "name": "log-analyst",
    "description": "Reads log files and returns a short error summary.",
    "system_prompt": "You read logs and return only a short summary.",
}
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    subagents=[log_analyst],
    system_prompt="You are an on-call assistant.",
)

A small wrapper around the fake model recorded every request: the number of messages and the token count of the messages plus the bound tool schemas. Here is the log, trimmed:

text
  (tool schemas bound to main model: 2479 tokens)
=== NO subagent
  main call  1:  2 msgs,   2499 input tokens
  main call  2:  4 msgs,   5924 input tokens
  ...
  main call  6: 12 msgs,  19606 input tokens
  main call  7: 14 msgs,  19648 input tokens
  main call  8: 16 msgs,  19663 input tokens
  main call  9: 18 msgs,  19676 input tokens
  main-agent messages kept in state: 18
  main total input tokens: 125318
  last main call input tokens: 19676
  (tool schemas bound to main model: 2496 tokens)
=== WITH subagent
  main call  1:  2 msgs,   2516 input tokens
  main call  2:  4 msgs,   2598 input tokens
  main call  3:  6 msgs,   2640 input tokens
  main call  4:  8 msgs,   2655 input tokens
  main call  5: 10 msgs,   2668 input tokens
  sub  call  1:  2 msgs,   2100 input tokens
  ...
  sub  call  6: 12 msgs,  19207 input tokens
  main-agent messages kept in state: 10
  main total input tokens: 13077
  subagent total input tokens: 63937
  last main call input tokens: 2668

The main agent without a subagent grows by about 3,400 tokens per file read, then stays near 19,600 for every follow-up:

Main agent input tokens per call, no subagent
21393.711087.5781.3249915924293493127674161865196066196487: follow-up196638: follow-up196769: follow-up
Data from the sources listed below.

With the subagent, the main agent's context never passes 2,668 tokens:

Main agent input tokens per call, with subagent
2683.225922500.8251612598226403: follow-up26554: follow-up26685: follow-up
Data from the sources listed below.

And the totals across the whole conversation:

Total input tokens across the conversation
No subagent: main125318With subagent: main13077With subagent: subagent63937With subagent: both77014
Data from the sources listed below.

Read this honestly. The subagent did not make the reading cheaper. It peaked at 19,207 tokens, close to the 19,606 the lone agent hit, because it read the same five files. The saving comes from what happens after. The subagent's context is thrown away when it finishes, so the three follow-ups ran at about 2,600 tokens each instead of about 19,600. Across this conversation the total fell from 125,318 to 77,014 tokens, and the gap grows with every extra turn the main agent takes.

Note also that the first main call is the same size in both runs, about 2,500 tokens. Most of that is tool schemas: 2,479 tokens for the default tools, 2,496 with the task tool's description included. That is the fixed cost of a deep agent before anyone types a word.

Animation: the task tool starts a subagent with a fresh context. Its tool results stay inside it, and only one report comes back. Illustration, not to scale.

The general-purpose subagent

You get one subagent for free. The docstring of create_deep_agent says: "If no subagent named general-purpose is provided, a default general-purpose synchronous subagent is added automatically". It uses the main agent's model and tools, with its own system prompt.

We checked what it actually receives. The main agent's system prompt contained a marker, and the user's message mentioned a name from "earlier chat". The scripted main model delegated a word count:

python
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    system_prompt="You are the main agent. SECRET-MAIN-PROMPT.",
)
out = agent.invoke({
    "messages": [{"role": "user", "content": "Earlier chat: my name is Asha. Now count words in my draft."}],
    "files": {"/draft.md": {"content": "Deep agents keep context small.\n", "encoding": "utf-8"}},
})

The first request the general-purpose subagent got, and what came back:

text
general-purpose subagent, first request:
  system: 'In order to complete the objective that the user asks of you, you have access to a number of standard tools.\n\nThe calling agent only sees your final assistant m' ...
  human: 'Count the words in /draft.md and write the number to /count.txt. Reply with the number only.'
sees main system prompt? False
sees user's earlier chat? False
main agent got back: ['6']
main agent message count: 4 | subagent requests made: 3
/count.txt in shared state: 6

Two messages. Its own system prompt, which warns it that "The calling agent only sees your final assistant message", and the task description. No main prompt, no chat history. Three subagent model calls turned into one tool message, '6', and the file it wrote, /count.txt, was visible to the main agent afterwards.

This is the most common mistake with subagents: writing a task description that assumes the subagent knows what the user said. It does not. Put every fact it needs in description.

Three kinds of subagent

Hand-drawn diagram: the main agent hands off work two ways. Synchronously through the task tool, which waits for the answer and can call a SubAgent dict with prompt, tools and model, or a CompiledSubAgent wrapping any graph with a messages key; general-purpose is a SubAgent added for you. In the background through start_async_task, check, update, cancel and list, which runs an AsyncSubAgent on an Agent Protocol server identified by graph_id and url. The main agent keeps only the final text

The subagents= argument accepts three forms, per the 0.7.42 source.

flowchart TB
  A[subagents list] --> B{Which form?}
  B -->|name, description, prompt| C[SubAgent dict]
  B -->|name, description, runnable| D[CompiledSubAgent]
  B -->|name, description, graph_id| E[AsyncSubAgent]
  C --> T[task tool]
  D --> T
  E --> X[async task tools]

SubAgent: a dict

name and description are required. The description is what the main model reads when it decides whom to call, so make it specific. Optional fields include system_prompt, tools, model, middleware, interrupt_on, skills, permissions and response_format. The source notes that without system_prompt the subagent "Uses an empty prompt", and without tools it inherits the main agent's tools.

CompiledSubAgent: bring your own graph

If you already have an agent or any LangGraph graph whose state has a messages key, wrap it. It is called through the same task tool.

python
from langchain.agents import create_agent
from langchain_core.tools import tool
from deepagents import create_deep_agent, CompiledSubAgent

@tool
def web_search(query: str) -> str:
    """Search the web."""
    ...

@tool
def fetch_price(ticker: str) -> str:
    """Fetch a price."""
    ...

pricer = create_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[fetch_price],
    system_prompt="Return the price only.",
    name="pricer",
)
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    system_prompt="You coordinate helpers.",
    subagents=[
        {
            "name": "researcher",
            "description": "Searches the web and saves notes to /research/.",
            "system_prompt": "Search, save notes, reply in one line.",
            "tools": [web_search],
        },
        CompiledSubAgent(name="pricer", description="Looks up a stock price.", runnable=pricer),
    ],
)

In our run both tools slept 1.5 seconds to stand in for network calls. The log shows the tools each model was given and the agent list the task tool advertises:

text
main agent tools: ['ls', 'read_file', 'write_file', 'edit_file', 'delete', 'glob', 'grep', 'task']
researcher tools: ['ls', 'read_file', 'write_file', 'edit_file', 'delete', 'glob', 'grep', 'web_search']
--- task tool description (agent list) ---
Available agent types and the tools they have access to:
- general-purpose: General-purpose agent for researching complex questions, ...
- researcher: Searches the web and saves notes to /research/.
- pricer: Looks up a stock price.

The main agent does not get web_search. The researcher does, plus the file tools. General-purpose was added even though we did not ask for it. To remove it, the docstring points to general_purpose_subagent=GeneralPurposeSubagentProfile(enabled=False) in a harness profile.

Parallel task calls

A model can put several task calls in one message. The scripted main model did that, then we ran the same two jobs one per turn:

text
--- main agent message log ---
  human  'Research gVisor users and price ACME.'
  ai     '' ['researcher', 'pricer']
  tool   'Found A, B and C. Notes are in /research/notes.md.'
  tool   'ACME is 101.5.'
  ai     'Done: A, B, C; ACME 101.5.'
files visible to main agent: ['/research/notes.md']
wall time, two task calls in one turn : 2.41 s
wall time, one task call per turn     : 4.10 s

A second run of the same script gave 3.00 s and 4.37 s. The exact times vary, but in both runs the two subagents overlapped when called in one turn. The researcher's notes file is in the main agent's state, as the shared filesystem promises.

Wall time for two 1.5 s subagent jobs (fake model, first run)
Both in one turn2.4 sOne per turn4.1 s
Data from the sources listed below.

AsyncSubAgent: background work on a server

The task tool blocks: the main agent waits until the subagent finishes. Async subagents do not. An AsyncSubAgent spec has name, description and graph_id, plus an optional url and headers. The source describes it as a subagent "running on a remote Agent Protocol server", reached through the LangGraph SDK, and marks it Beta.

Instead of task, the main agent gets five tools: start_async_task, check_async_task, update_async_task, cancel_async_task and list_async_tasks. It can start a long job, keep talking to the user, and check back later. We did not run this one, because it needs a running Agent Protocol server. The details here come from middleware/async_subagents.py and the async subagents docs page.

When not to use a subagent

Isolation has a price. The subagent pays its own fixed cost on every call: about 2,100 tokens in our run before it read anything. A one-line job, like reading a single small file, is cheaper to do in the main agent. Delegation also hides detail. If the main agent will need the raw text later, have the subagent write it to a file and return the path.

There is also an experimental mode="fork" on a SubAgent. A fork gets the parent's conversation instead of a clean slate, which trades isolation for continuity. The source marks it experimental and says it may change.

A rule of thumb from these runs: delegate when the work produces much more text than the answer, and when the main agent will keep talking after it.

The next part gives subagents better tools: your own functions and MCP servers.

Nuances from running it live

We put the Part 13 research team on a public demo: a Vercel function and Groq's free plan, with openai/gpt-oss-20b as the researcher subagent. The isolation worked. What broke was the subagent's exit: a small model does not reliably stop and hand back.

The researcher that would not stop

In live run 6 the researcher used its 3 searches, then kept going. Every refused tool call told it to "call write_file now". It ignored that and asked to read the same blog page 5 times: 1 real read, 4 refused repeats. It never wrote its notes, so the lead never got control back before the run ended at 243.5 s.

sequenceDiagram
  participant L as Lead
  participant R as Researcher (20b)
  participant T as Tools
  L->>R: task: research, save /notes/research.md
  R->>T: web_search x3
  T-->>R: results
  R->>T: web_search (4th)
  T-->>R: No search calls left. Call write_file now
  R->>T: fetch_page v0.7 blog (again)
  T-->>R: You already read this page
  Note over R,T: repeated about 10 more times, about 25 s per call
  R--xL: time runs out, no notes, lead never drafts
Run 6: seconds between researcher calls (approx.)
30.521.512.523817914102511251229132814271526162517
Data from the sources listed below.

The gaps come from the stream's 5-second keep-alive pings, so they are approximate. Calls slowed to about 25 to 29 s each with no 429 in the stream. That looks like free-tier throttling, but we could not confirm it.

The fix: code writes the notes, not the model

Telling the model louder did not work. So the subagent's middleware takes over: once the budget is spent, or the model re-reads a page, it writes the notes file itself from what was already found and jumps the subagent to its end.

python
# demo/real_agent.py, AutoNotes.after_model (commit efb7f9b)
if b.exhausted() or refused:
    return self._finish(state, "search and read budget used up", last.id)

# _finish() returns a state update that ends the subagent:
return {"messages": [msg], "files": {path: create_file_data(body)}, "jump_to": "end"}
sequenceDiagram
  participant L as Lead
  participant R as Researcher (20b)
  participant M as AutoNotes middleware
  L->>R: task
  R->>M: 4th web_search requested
  M->>M: budget spent: build notes from results
  M-->>L: Notes saved to /notes/research.md
  L->>L: read notes, write /draft.md, call critic
Researcher model calls, run 6 vs run 7
Run 6: model told to stop15Run 7: code stops it4
Data from the sources listed below.
Whole run, seconds
Run 6243.5 sRun 733.9 s
Data from the sources listed below.

Run 7 handed back after 4 researcher calls and the whole run took 33.9 s. The cost: it read 0 pages, because the rule fired on the first over-budget search while page reads were still in budget. Commit 089eef9 lets one refused call through first and stops the researcher on the second. In run 8 that fired after researcher call 7, at about 16 s. It still read 0 pages: the model spent its turn on a 4th search instead of opening a result. The notes were snippets only, and that hurt the final report (see Part 12).

Lesson: the parent's context stayed clean, as this part promises. But a subagent's exit condition belongs in code, not in a prompt.

Try this

bash
python -m venv .venv && . .venv/bin/activate
pip install deepagents==0.7.42 tiktoken
python -c "import deepagents, pathlib; p = pathlib.Path(deepagents.__file__).parent / 'middleware' / 'subagents.py'; s = p.read_text(); print(s[s.index('_EXCLUDED_STATE_KEYS = {'):][:120])"
python -c "import deepagents, pathlib; p = pathlib.Path(deepagents.__file__).parent / 'middleware' / 'async_subagents.py'; import re; print(re.findall(r'name=\"(\w+_async_tasks?)\"', p.read_text()))"

Sources