Trail content
9 minEnglish narration, Portuguese subtitlesPodcast (RSS)
Chapters
  1. 0:00Opening
  2. 0:47The idea
  3. 1:03Before and after
  4. 1:42A real case
  5. 2:44Why it works
  6. 3:43A challenge
  7. 4:22Safe mechanics
  8. 5:38Risks
  9. 7:14Practice
  10. 8:11Wrap-up
Transcript

Opening

A fintech's content agent is writing about instant payments. It reads thirty pages, writes the post, reviews its own text against the brand guide, and publishes.

By the end of the task, its context mixes three things.

Excerpts from competitors' blogs.

Then the writer's own reasoning, word for word. I used this argument because legal asked.

And the publish tool.

So the reviewer inherits the writer's argument, and lets through what it should have blocked. And a page with a hidden instruction sits one step away from publishing. You met the mega agent in the last lesson. Today you'll take it apart, one subagent at a time.

The idea

Give a large, well bounded subtask its own agent. With a clean context, its own prompt, and only the tools it needs. The main agent hands over an instruction, and gets back only the result, in an agreed format.

Before and after

Before, one context for everything. The pages it read, the review of its own text, and the publish tool, all in the same place.

After, the brief reaches the main agent. It plans, writes, and decides. It doesn't read web pages.

The research subagent reads everything, in its own context, and returns a short list of facts, each with a source.

The review subagent gets only the draft and the brand guide. Without the writer's reasoning.

And publishing stopped being a model tool. It became a step after approval.

A real case

The brief: eight hundred words about instant payments, for solo micro businesses, in the brand's tone, and never promise returns. The main agent calls research, with the topic and a hint to prefer official sources. The subagent spends twelve steps, reads the thirty pages, and returns this.

Facts, each with its source. Like: a micro business can receive these payments in a linked personal account, with the central bank's page as the source.

And open questions. What's the current monthly cap? Nobody found it for sure, so it says so.

The main agent writes from that, with no web pages in sight. The review subagent receives the draft and the guide, and returns one problem. It says paragraph four promises returns to the reader. Publishing only happens after the marketing person approves. The web content never sat next to the side effect tool.

Why it works

A context is the model's working memory. When it holds thirty pages, the writer's reasoning and the review rules all at once, everything competes for attention. Splitting restores three properties.

Focus. Each subagent has a prompt with one role, and few tools.

Cleanliness. The raw work, pages, logs and files, dies inside the subagent. The main agent gets one page of results, instead of a hundred.

And independence. The reviewer doesn't inherit the writer's reasoning, so it judges the text as it is.

And the return format is the contract between the two. Without it, the main agent gets free text, and has to guess what came back. Facts with sources can be reviewed. A paragraph called research summary can't. And each subagent takes its own budget, charged against the task's total.

A challenge

Here's one for you. The research subagent's contract was a free paragraph. And the main agent started filling in facts with no source. What's the next step?

Change the contract to a schema, with facts, sources and open questions. And reject a return that doesn't fill it. Without fields, the main agent fills the gaps.

A bigger research budget only makes a richer paragraph, which is still free text. And sending the thirty pages to the main agent, so it can check, undoes the whole point. It sits next to raw web pages again.

Safe mechanics

Step zero, measure. Run the current agent's eval, and record quality, cost per task, tokens per turn at the end of the task, and known incidents. A bad publish, a review that missed.

Find the boundary. Look in the trace for a stretch with many turns, lots of reading, and a result that fits in a few lines. That's the candidate.

Define the output contract as a schema. What the subagent returns, in what format, with sources or evidence.

Write the subagent's prompt with a single role, and the minimal list of tools. It never gets the publish tool, and none of its sibling's tools. And give it its own budget.

In the main agent, replace the old tools with one tool that calls the subagent.

Record the subagent as a child span on the trace, so you can see what it read, without bringing it into the main context.

And measure again. Quality equal or better, fewer tokens per turn in the main agent. Total cost may rise a little, with one more orchestration call. Check that the gain in quality and isolation is worth it.

Risks

Now the risks. Missing context. The brief said: don't cite competitor X. The research subagent never got that constraint, and returned a fact from X's blog. The main agent used it. Whose failure is it? The main agent's. There's no shared memory. Everything the subagent needs goes into the instruction.

A result too thin. A three line summary may lose the detail the main agent needed. Adjust the schema, based on the cases that failed.

Agent multiplication. Four subagents for research, writing the title, writing the body, and picking an emoji, is decorative multi-agent. Each extraction needs a reason. Context that mustn't mix, tools that mustn't coexist, or independent judgment. And formatting a date doesn't qualify. That's one line of code.

And recursion. If the research subagent can open another researcher, each with fifteen fresh steps and no depth cap, the tree explodes. Cap the depth, and pass the same budget down.

And one more trap. The publish tool stays on the main agent's list, for urgent cases. The research subagent still doesn't have it, so it feels safer. It is safer than before. But the main agent can still publish a raw draft, with no approval. And a prompt saying don't publish without review is the very thing we're trying to leave behind. An available tool will be used, sooner or later.

Practice

Let's practice. An incident agent reads logs, metrics and the runbook, then decides whether to restart a service. What would you extract, and what should it return?

Extract the investigation. A diagnosis subagent reads the logs and metrics, which are large and untrusted, with read only tools. And it returns a structured report.

The likely cause. The evidence, each with a source and an excerpt. The confidence, low, medium or high. And a suggested action. Restart, roll back, escalate, or nothing.

The main agent decides, based on that report and the runbook. And the restart itself stays outside both agents, behind the on-call engineer's approval, when confidence isn't high. Raw logs never sit next to the restart tool.

Wrap-up

So here's the idea to take with you. Extract a subagent where the work is heavy, untrusted, or needs fresh eyes. Give it one role, few tools, its own budget, and everything it needs in the instruction. And make it return a contract, not a paragraph.

In the next lesson, we'll look at the full pattern behind this refactoring: subagent delegation. See you there.

RefactoringMoving control

Extract Subagent

Extrair Subagente

Extract Subagent is an AI refactoring for LLM systems, in the Moving control group. Give a large task its own agent with a clean context and only the tools it needs.

Element
10/35
Level
Advanced
Read
5 min
Updated
On this page 8
  1. 01Problem
  2. 02Solution
  3. 03Before and after
  4. 04Why it works
  5. 05Safe mechanics
  6. 06Risks
  7. 07Challenge
  8. 08Check your understanding
  9. ··Quick answers

Problem

One agent does different kinds of work in the same context: it reads a lot, produces, reviews, and acts. The context bloats and the roles contaminate each other. These are the Mega Agent, Context Rot, and Shared Scratchpad smells.

The fintech’s content agent researches Pix (Brazil’s instant-payment rail), reads 30 pages, writes the post, reviews its own text against the brand guide, and publishes. At the end of the task the context mixes competitor blog excerpts, the writer’s reasoning (“I used this argument because legal asked”), and the publish_post tool. The reviewer inherits the writer’s argument and lets through what it should have blocked. A page with a hidden instruction sits one step away from publishing.

The destination of this extraction is Subagent Delegation with Context Isolation.

Solution

Give a large, well-bounded subtask its own agent, with a clean context, its own prompt, and only the tools it needs. The main agent hands over an instruction and gets back only the result, in an agreed format.

Before and after

 MAIN_TOOLS = [
-    web_search, fetch_page,               # research in the main context
     read_brand_guide, write_draft, edit_draft,
-    publish_post,
+    research,                             # subagent: returns facts with sources
+    review,                               # subagent: returns problems found
 ]
+
+def research(question: str) -> ResearchNotes:
+    return run_agent(RESEARCH_PROMPT, tools=[web_search, fetch_page],
+                     task=question, budget=Budget(steps=15), output=ResearchNotes)
+
+def review(draft: str) -> ReviewReport:
+    return run_agent(REVIEW_PROMPT, tools=[read_brand_guide, check_plagiarism],
+                     task=draft, budget=Budget(steps=6), output=ReviewReport)
+
+# publish_post left the agent: it became a code step after approval

Before: one context for everything.

flowchart TD
  B(["1. Brief"]):::io --> A(["2. Single agent"]):::llm
  A --> W["3. 30 pages read"]:::untrusted
  W --> A
  A --> R["4. Review of its own text"]:::tool
  R --> A
  A --> P["5. Publish"]:::tool

After: subagents with their own context, and only the result comes back.

flowchart TD
  B(["1. Brief"]):::io --> A(["2. Main agent"]):::llm
  A --> S1(["3. Research subagent"]):::llm
  S1 --> W["Pages read"]:::untrusted
  S1 -->|"facts with sources"| A
  A --> S2(["4. Review subagent"]):::llm
  S2 -->|"list of problems"| A
  A --> H((("5. Approval"))):::human
  H --> P["Publish"]:::tool
  1. The brief reaches the main agent.
  2. The main agent plans, writes, and decides. It does not read web pages.
  3. The research subagent reads everything in its own context and returns a short list of sourced facts.
  4. The review subagent gets only the draft and the brand guide, without the writer’s reasoning.
  5. Publishing stopped being a model tool and became a step after approval.

Worked example

Brief: “800-word post about Pix for solo micro-businesses (MEI in Brazil), brand tone, do not promise yield”.

In the before, the agent searches, reads, notes, writes, and reviews in the same history. Around page 20, the start of the brief competes with blog HTML. “Lost in the Middle” (Liu et al., 2023) describes that attention drop. The publish_post tool stays available while the context is full of untrusted text.

In the after, the main agent calls research("Pix for MEI, official sources, 2026"). The subagent spends 12 steps, reads the 30 pages, and returns, for example:

{
  "facts": [
    { "claim": "A MEI can receive Pix in a linked personal account", "source": "bcb.gov.br/..." }
  ],
  "open_questions": ["current monthly cap"]
}

The main agent writes the draft from that, with no HTML. The review subagent receives the draft and the guide, and returns { "problems": ["promises yield in paragraph 4"] }. Publishing only runs after the marketing person approves. Web content never sat next to the side-effect tool.

Check +20 XP on first tryThe post reviewer runs in the same context as the writer and sees the note ‘legal asked to soften paragraph 4’. The reviewer lets the paragraph through. Which property does the extraction restore?

Why it works

A context is the model’s working memory. When it holds 30 pages read, the writer’s reasoning, and the review rules all at once, everything competes for attention, and untrusted content sits close to side-effect tools.

Splitting restores three properties. Focus: each subagent has a one-role prompt and few tools. Cleanliness: the raw work (pages, logs, files) dies inside the subagent, and the main agent receives one page of results instead of a hundred. Independence: the reviewer does not inherit the writer’s reasoning, so it judges the text as it is.

The return format is the contract between the two. Without it, the main agent gets free text and has to guess what came back. ResearchNotes with facts and sources is reviewable; a paragraph of “research summary” is not.

Each subagent takes its own budget, charged against the task total. Without that, the extraction becomes Subagent Recursion. See Add Loop Budget.

Safe mechanics

  1. Measure. Run the current agent’s eval and record quality, cost per task, tokens per turn at the end of the task, and known incidents (bad publish, review that misses).
  2. Find the boundary. Look in the trace for a stretch with many turns, lots of reading, and a result that fits in a few lines. That is the candidate. Extracting a one-line step (format a date) does not pay for a subagent.
  3. Define the output contract as a schema: what the subagent returns and in what format. Include sources or evidence.
  4. Write the subagent prompt with a single role and the minimal tool list. No publish_post. None of the sibling’s tools.
  5. Give it its own budget, charged against the task’s total budget.
  6. In the main agent, replace the old tools with one tool that calls the subagent.
  7. Record the subagent as a child span on the trace, so you can see what it read without bringing it into the main context.
  8. Measure again. Equal or better quality, fewer tokens per turn in the main agent. Total cost may rise a little (one extra orchestration call); check that the quality and isolation gain is worth it.

Common mistake: extracting too much

An agent with four subagents for “research”, “write title”, “write body”, and “pick an emoji” is Decorative Multi-Agent. Each extraction needs a reason: context that must not mix, tools that must not coexist, or independence of judgment. Title and body in the same writer are usually the same job.

Check +20 XP on first tryThe research subagent’s contract was a free paragraph. The main agent started ‘filling in’ facts with no source. What is the next step?

Risks

  • Missing context. The subagent does not know something only the main agent knew (a user constraint: “do not cite competitor X”). Put everything it needs in the instruction; do not count on shared memory.
  • Result too thin. A three-line summary may lose the detail the main agent needed. Adjust the schema based on the cases that failed.
  • Agent multiplication. Extracting too much leads to Decorative Multi-Agent. Each subagent needs a reason: context, tools, or independence.
  • Recursion. If the subagent can also spawn subagents, cap the depth and share the budget.

Challenge

An incident agent reads logs, metrics, and the runbook, then decides whether to restart a service. Which part would you extract, and what should it return?

Show solution

Extract the investigation. A diagnosis subagent reads logs and metrics (large, untrusted content) with read-only tools and returns a structured report:

schema Diagnosis {
  likely_cause: string
  evidence: list[{ source: string, excerpt: string }]
  confidence: "low" | "medium" | "high"
  suggested_action: "restart" | "rollback" | "escalate" | "none"
}

The main agent decides based on the Diagnosis and the runbook. The restart action stays outside both agents, behind on-call approval when confidence is not high. Raw logs do not sit next to restart_service.

Check your understanding

Check +20 XP on first tryOne step of the agent formats the post date from 2026-10-02 to ‘2 October’. Is it worth extracting a subagent?

Check +20 XP on first tryThe brief says ‘do not cite competitor X’. The research subagent did not get that constraint and returned a fact sourced from X’s blog. The main agent used the fact. Whose failure is it?

Check +20 XP on first trypublish_post is still on the main agent’s tool list, ‘for urgent cases’. The research subagent still does not have it. Is the design safe?

Check +20 XP on first tryThe research subagent can call delegate and open another researcher, each with 15 fresh steps. There is no depth cap. Which smell comes back?

Quick answers

What is Extract Subagent?

Extract Subagent is an AI refactoring for LLM systems, in the Moving control group. Give a large task its own agent with a clean context and only the tools it needs.

What problem does Extract Subagent solve?

It treats Context Rot, Mega Agent, and Shared Scratchpad.

Which pattern does Extract Subagent lead to?

The Subagent Delegation and Context Isolation design pattern.

Go further

Relations

Part of the tracks 1
Search