โ† Back to Blog
AgentsAI EngineeringLLMs

Subagents for Context Management: Keep Your Main Agent's Window Clean

Your agent's context fills up with grep output, file dumps and failed attempts long before the task is done. Subagents let you push noisy work into a throwaway context and return only a short, structured result.

By Joinloopยท21 November 2026ยท8 min read
ShareLinkedInXReddit
๐Ÿงน

A coding agent asked to "find where we validate JWTs and add rate limiting" will typically run a dozen searches, open eight files, and read a few thousand lines of test output. By the time it starts writing code, most of its context window is occupied by material it will never need again. Quality drops, cost rises on every subsequent turn, and the original instructions drift further back in the window.

Thoughtworks' Technology Radar now lists "subagents for context management" as a technique, and it is worth understanding independent of any specific product. The idea is simple: treat context as a scarce resource, and spend it in a disposable worker instead of in your main loop.

The problem: context is a shared, append-only log

In a single-agent loop, every tool call and result is appended to one growing message list. Three things go wrong:

  1. Cost compounds. Every new turn re-sends (or re-reads from cache) everything before it. A 5,000-token grep result you needed once is paid for on every later turn.
  2. Attention dilutes. Long contexts tend to degrade instruction-following and recall of details in the middle. Your system prompt competes with raw tool output.
  3. Dead ends persist. Failed approaches stay visible and can bias the model toward repeating or rationalising them.

Compaction (summarising old turns) helps, but it is lossy and happens after the damage. Subagents prevent the pollution in the first place.

How subagent isolation works

A subagent is just another LLM loop with its own message list, its own (usually narrower) toolset, and a single instruction. The parent hands over a task; the child does all the messy exploration; only the final message crosses back.

Parent context:   [system][user task][tool: delegate(...)] -> [short result] [next step...]
Child context:    [child system][task][grep][read][read][grep][read] ... [final answer]
                   ^ discarded when the child returns

The parent pays for one tool call and one short result, no matter how much work the child did.

A minimal implementation

This example uses the Anthropic Python SDK. Check the official docs for current model IDs and SDK details; the structure is what matters.

import json
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"  # verify against the current model list

SEARCH_TOOLS = [
    {
        "name": "grep_repo",
        "description": "Search the repo for a regex. Returns matching lines with file:line.",
        "input_schema": {
            "type": "object",
            "properties": {"pattern": {"type": "string"}},
            "required": ["pattern"],
        },
    },
    {
        "name": "read_file",
        "description": "Read a file by path (first 400 lines).",
        "input_schema": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"],
        },
    },
]

def run_tool(name: str, args: dict) -> str:
    import subprocess
    if name == "grep_repo":
        out = subprocess.run(["grep", "-rnE", args["pattern"], "."],
                             capture_output=True, text=True).stdout
        return out[:8000]
    if name == "read_file":
        with open(args["path"]) as f:
            return "".join(f.readlines()[:400])
    return "unknown tool"

def run_subagent(task: str, max_turns: int = 10) -> str:
    """Isolated loop. Returns ONLY the final text."""
    system = (
        "You are a research subagent. Investigate the task using the tools. "
        "Finish with a report under 200 words: findings, file:line references, "
        "and anything uncertain. Do not paste large code blocks."
    )
    messages = [{"role": "user", "content": task}]
    for _ in range(max_turns):
        resp = client.messages.create(
            model=MODEL, max_tokens=1500, system=system,
            tools=SEARCH_TOOLS, messages=messages,
        )
        if resp.stop_reason != "tool_use":
            return "".join(b.text for b in resp.content if b.type == "text")
        messages.append({"role": "assistant", "content": resp.content})
        results = []
        for block in resp.content:
            if block.type == "tool_use":
                results.append({
                    "type": "tool_result",
                    "tool_use_id": block.id,
                    "content": run_tool(block.name, block.input),
                })
        messages.append({"role": "user", "content": results})
    return "Subagent hit the turn limit without a final report."

# The parent exposes the subagent as just another tool.
DELEGATE_TOOL = {
    "name": "delegate_research",
    "description": (
        "Delegate a read-only codebase investigation. Use for questions that "
        "need many searches. Returns a short report."
    ),
    "input_schema": {
        "type": "object",
        "properties": {"task": {"type": "string"}},
        "required": ["task"],
    },
}

The parent loop treats delegate_research like any other tool: when it is called, run run_subagent(args["task"]) and return the string. The parent never sees the intermediate greps.

What to delegate and what not to

Task type Delegate? Why
Codebase search / "where is X defined" Yes High-volume, low-value intermediate output
Reading long docs or logs for one answer Yes You need the conclusion, not the text
Running a test suite and summarising failures Yes Output is huge; the summary is small
Parallel independent investigations Yes Each gets a clean window; run concurrently
Editing code the parent must reason about Usually no Parent needs the full diff context to stay coherent
Tight back-and-forth with the user No Subagents cannot ask clarifying questions cheaply
Tiny lookups (one file read) No Delegation overhead exceeds the savings

A useful rule of thumb: delegate when the ratio of exploration to conclusion is high. If the answer is roughly as big as the work, do it inline.

Designing the contract between parent and child

Most subagent failures are interface failures, not model failures.

  • Write a self-contained brief. The child has none of the parent's history. Include the goal, constraints, and what "done" looks like. "Look into the auth thing" fails; "Find every place a JWT is verified in services/api, and list file:line and the library call used" works.
  • Constrain the output format. Ask for a word limit and a structure (findings, references, uncertainties). Otherwise children return essays, which defeats the purpose.
  • Return evidence, not just claims. File paths and line numbers let the parent verify cheaply. A summary the parent cannot check is a hallucination vector.
  • Scope the tools. A research child should be read-only. Give write tools only to children whose whole job is to write.
  • Set budgets. Cap turns and tokens per child, and have the parent handle "I ran out of budget" as a first-class result.

Parallelism

Because children are independent, you can fan out. With the async client, run several in asyncio.gather and merge the reports. This is where the pattern also helps latency, not just context: three 40-second investigations take about 40 seconds, not two minutes.

Be careful with fan-out on write tasks. Parallel writers on the same files need isolation (separate worktrees or branches); see our post on multi-agent coding orchestration for that side of the problem.

Tradeoffs

Benefit Cost
Parent context stays small and focused Extra LLM calls; total tokens spent often goes up, even though parent tokens go down
Dead ends are discarded Information loss: a detail the child dropped is gone
Parallel speedups More moving parts to trace and debug
Cheaper model can run the child Quality of the child's summary caps quality of the parent's decision

The honest framing: subagents trade total compute for parent-context quality. Measure it; do not assume it.

Common pitfalls

  1. Leaky summaries. The child omits the one detail that mattered (a feature flag, a second code path). Mitigate by asking for "things I did not check" explicitly.
  2. Recursive delegation. Children spawning children quickly explodes cost. Give children no delegate tool, or enforce a depth limit of one.
  3. Using subagents as a crutch for a bad prompt. If the parent is flooded because a tool returns 50k tokens of unfiltered output, truncate or paginate that tool first.
  4. No observability. Log each child's task, turns, tokens and final report as its own span, linked to the parent trace. Otherwise you cannot tell why the parent made a decision.
  5. Trusting child output blindly. Treat reports as untrusted input, especially if the child read web pages or user files, since prompt injection can ride along in a summary.

A checklist before you add subagents

  • Is the parent context actually bloated by exploration? (Check token counts per turn.)
  • Have you truncated or paginated noisy tools first?
  • Does each delegation have a self-contained brief and an output size limit?
  • Are child tools scoped to the minimum (read-only where possible)?
  • Are budgets (turns, tokens, wall-clock) enforced and surfaced to the parent?
  • Do you trace children linked to the parent run?
  • Do you have an eval comparing single-agent vs subagent on the same tasks, on accuracy, cost and latency?

Next steps

Start with one delegation tool for the noisiest task in your agent, usually repo search or log analysis. Compare parent token usage and task success rate on 20 representative runs before and after. If the numbers do not move, you do not need more architecture. If they do, extend to parallel fan-out for independent investigations.

Building production agents is a mix of patterns like this, evals to prove they work, and cost controls to keep them affordable. We cover all of that hands-on in the Joinloop AI Engineering cohort.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.