What you will be able to do
- Choose between prompt chaining, routing, parallelization and orchestrator-workers based on whether the subtasks are known in advance
- Assign a model to each decomposed subtask based on how hard and how frequent it is
- Decompose a multi-dimension task into Agent SDK subagents with scoped tools and descriptions
- Recognise when a tight loop of tool calls should move into code through programmatic tool calling
Key concept
Task decomposition — Splitting one hard request into smaller subtasks, each handled by its own focused model call, prompt, tool set or model. The design question is who decides the subtasks: you, while you build the system, or a model, at run time.
1.Why decomposition improves results
One model call that has to do everything gives each part of the job less attention. If a single prompt has to screen a request for unsafe content and also answer it, both jobs get worse. Splitting the work so that each call handles one consideration is the basic move behind every pattern on this page. Decomposition fits best where several well-scoped tasks feed one overall goal.
The patterns differ in who decides the subtasks. In prompt chaining, routing and parallelization, the designer fixes the subtasks when the system is built. In orchestrator-workers, a model works them out at run time for each input. This is the same line drawn in Workflows versus agents, seen here as a decomposition choice: if you can list the subtasks today, write them into code. If they depend on the input, let a model plan them.
Decomposition is not free. Every extra call adds latency and tokens, and every handoff is a place where context can get lost. Each pattern below says what it costs and when that cost is worth paying.
Checkpoint 1 of 10· Check yourself
A support assistant uses one prompt to screen each request for unsafe content and also answer it. Both the screening and the answers are mediocre. The team moves screening into its own call, separate from the call that answers. Why should this improve results?
Decomposition helps because a call that does one job can give that job its full attention. It does not save time or tokens, because every extra call adds both. Here the designer fixed the subtasks while building the system. Run-time planning applies only to orchestrator-workers.
“LLMs generally perform better when each consideration is handled by a separate LLM call, allowing focused attention on each specific aspect.”Source: www.anthropic.com
2.Prompt chaining: fixed steps with gates between them
Prompt chaining splits a task into a fixed sequence of steps. Each model call takes the previous call's output as its input. Between steps you can add programmatic checks, called gates, that confirm the process is still on track before the next call runs. Two standard examples: writing marketing copy and then translating it, or writing an outline, checking it against criteria, and only then writing the document.
Chaining fits when a task splits cleanly into fixed subtasks. A worked case: turning a quarterly performance summary into a table takes four calls. The first extracts each metric with its value. The second converts the values to one format. The third sorts them in descending order. The fourth renders a markdown table. Each step is trivial for the model, and a code check between steps (for example, "did step 1 return every metric?") catches a failure before it spreads to the later steps.
The same shape appears in Claude Code dynamic workflows. The first agent call returns a list of files in a declared schema, and that list drives the next step, which audits each file.
const found = await agent('List every .ts file under src/routes/.', {
schema: { type: 'object', required: ['files'], properties: { files: { type: 'array', items: { type: 'string' } } } },
})
const audits = await pipeline(found.files, file =>
agent(`Audit ${file} for missing authentication checks.`, { label: file }),
)
return audits.filter(Boolean)Checkpoint 2 of 10· Fill the gap
In this two-step chain, the first agent call must return a structured file list for the next step to work through. Which option name makes that first call return output in a declared shape?
const found = await agent('List every .ts file under src/routes/.', {
? : { type: 'object', required: ['files'], properties: { files: { type: 'array', items: { type: 'string' } } } },
})
const audits = await pipeline(found.files, file =>
agent(`Audit ${file} for missing authentication checks.`, { label: file }),
)
return audits.filter(Boolean)In a chain, each call takes the previous call's output as its input. Here, schema makes the first call return a files array in a fixed shape, and pipeline hands that array to the audit step. label only names each audit agent.
3.Routing: split by input type, and match the model to the subtask
Routing classifies an input first, then sends it to a follow-up step built for that category. That step can use its own prompt, its own tools or its own model. The reason to route is interference. If one prompt has to serve every kind of input, tuning it for one kind tends to make it worse for the others. A customer-service system might route general questions, refund requests and technical support into three separate processes, each with its own prompt and tools.
Routing works when the categories really are distinct and classification can be done accurately, whether by an LLM or by a traditional classifier. If inputs are often misclassified, every downstream specialist receives work it was not built for.
Routing is also the place to choose a model for each subtask. Model classes differ mainly in how hard a problem they can reliably handle and what that capability costs in price and speed. Easy, common requests go to a small, cheap model. Hard or unusual ones go to a more capable model. Take a support pipeline with two subtasks: classifying a large stream of tickets, and drafting detailed remediation plans for the few that need engineering. Classification goes to Haiku. Remediation, which is multi-step and often new, goes to a more capable class such as Opus. Running everything on the largest model pays its price for every routine classification. Running everything on Haiku asks it to carry work beyond what it reliably handles. Assigning models at random is not routing, because nothing about the input decides where it goes. The broader trade-offs are covered in model selection trade-offs.
| Model class | Fits subtasks that are |
|---|---|
| Haiku | High-frequency, where latency and cost matter most: classification, simple extraction |
| Sonnet | Everyday general-purpose work, including high-volume sub-agents in multi-agent setups |
| A more capable class (e.g. Opus) | Slow, multi-step or previously unsolved: the hard tail of the workload |
With agents, routing means sending work to a specialist agent rather than a specialist prompt. In the Agent SDK, each subagent definition has an optional model field, so a cheap classifier and an expensive drafter can live in the same system.
Checkpoint 3 of 10· Check yourself
Logs from a routed customer-service system show that many refund requests are being sent to the technical-support process, and answers on those tickets are poor. What should the team fix first?
Routing only pays off when inputs can be classified accurately. A misclassified ticket reaches a specialist that was not built for it, so the router is what needs fixing. Merging back into one prompt brings the interference back, and a bigger model or more categories does nothing about tickets being sent to the wrong place.
“where classification can be handled accurately, either by an LLM or a more traditional classification model/algorithm”Source: www.anthropic.com
Checkpoint 4 of 10· Exam question
A support-automation pipeline is decomposed into two subtasks: classifying a high volume of incoming tickets, and drafting detailed technical remediation plans for the subset that need engineering follow-up. How should model selection be applied across these decomposed subtasks?
Correct answer: A — Assign Claude Haiku 4.5 to the high-volume classification subtask and Claude Opus 4.8 to the remediation subtask, matching model to complexity
- A. Correct. Decomposition allows each subtask to use the model best suited to it: a fast, economical model for high-volume classification, and a more capable model for complex remediation reasoning, per Anthropic's model selection guidance.
- B. Incorrect. Lowering effort on Opus reduces reasoning depth uniformly but still runs the larger, costlier model for simple classification, missing the cost and latency benefit of matching model to subtask.
- C. Incorrect. A smaller model cannot be reliably compensated for on complex reasoning subtasks purely through longer prompts; capability gaps for nuanced remediation work require a more capable model.
- D. Incorrect. Random model assignment ignores the actual complexity differences between subtasks and produces inconsistent quality and unpredictable cost.
4.Parallelization: sectioning and voting
Parallelization runs several model calls at the same time and combines their outputs in code. It comes in two forms that solve different problems.
- Sectioning splits a task into independent subtasks that run side by side. For example, one instance answers the user while another screens the request for inappropriate content. This tends to beat one call doing both. Automated evals can also be sectioned, with each call grading a different aspect of the output.
- Voting runs the same task several times and combines the answers to get more confidence. For example, several prompts review the same code for vulnerabilities and flag it if any of them find a problem. Content moderation can also use different vote thresholds to balance false positives against false negatives.
Speed and cost need to be kept apart. Independent subtasks that run concurrently finish in the time of the slowest one, not the sum of all of them, so a single sectioned step takes less wall-clock time. Across a whole multi-agent system the picture is different. Such systems typically use 3 to 10 times more tokens than one agent, and they often take longer overall because there is so much more computation. Choose parallelization for coverage or confidence, and expect a larger bill.
Checkpoint 5 of 10· Check yourself
Three separate prompts each review the same pull request for security vulnerabilities at the same time. Code then flags the pull request if any one of them reports a problem. Which decomposition pattern is this, and why?
All three prompts do the same job on the same input, and code combines their answers. That is voting, which buys confidence. Sectioning would give each call a different part of the work. Orchestrator-workers has a model choose the subtasks at run time, and a chain runs its steps one after another, not in parallel.
“Voting: Running the same task multiple times to get diverse outputs.”Source: www.anthropic.com
5.Orchestrator-workers: decomposition decided at run time
In orchestrator-workers, a central model reads the task, decides which subtasks it needs, hands each one to a worker model, and combines the results. It can look like sectioning, but the subtasks are not pre-defined. The orchestrator chooses them for each input. A coding change is the standard case: you cannot know in advance how many files need editing or what each edit is.
async def research_topic(query: str) -> dict:
# Lead agent breaks query into research facets
facets = await lead_agent.decompose_query(query)
# Spawn subagents to research each facet in parallel
tasks = [
research_subagent(facet)
for facet in facets
]
results = await asyncio.gather(*tasks)
# Lead agent synthesizes findings
return await lead_agent.synthesize(results)That flexibility has costs. Each run makes N+1 calls: one to the orchestrator and one per worker. The decomposition is only as good as the orchestrator's plan, so the orchestrator prompt is where most of the engineering effort goes. Cost can be managed by splitting models, with a capable model such as Opus planning and Haiku workers executing. Do not use the pattern for simple single-output tasks, for latency-critical paths, or when the subtasks are always the same. In that last case, pre-defined parallelization does the job with less machinery.
Claude Managed Agents provides this as dynamic workflows. The agent writes a program that runs many agents in phases and combines their results, and the server runs it in the background. Audits, migrations, deep research and cross-checking are the typical uses. Every agent in a run uses tokens, so set a session budget.
| Pattern | Subtasks decided by | Reach for it when |
|---|---|---|
| Prompt chaining | Designer, as a fixed sequence | The task splits cleanly into fixed steps, and accuracy matters more than latency |
| Routing | Designer, as a set of categories | Inputs fall into distinct categories that can be classified accurately |
| Parallelization: sectioning | Designer, as independent pieces | Separate considerations each deserve a focused call |
| Parallelization: voting | Designer, as repeated attempts | Higher confidence is needed from several attempts or perspectives |
| Orchestrator-workers | Orchestrator model, per input at run time | The subtasks needed cannot be predicted in advance |
Checkpoint 6 of 10· Fill the gap
Nothing in this orchestrator-workers sample fixes how many subagents run. Which name belongs in the blank so that the number of workers follows the plan the lead agent made for this query?
async def research_topic(query: str) -> dict:
# Lead agent breaks query into research facets
facets = await lead_agent.decompose_query(query)
# Spawn subagents to research each facet in parallel
tasks = [
research_subagent(facet)
for facet in ?
]
results = await asyncio.gather(*tasks)
# Lead agent synthesizes findings
return await lead_agent.synthesize(results)In orchestrator-workers, the designer does not set the subtasks. The orchestrator chooses them for each input at run time. Here decompose_query returns facets, and starting one subagent per facet means the number and content of the workers depend on the input. results only exists after the workers finish, and tasks is the list being built.
6.Decomposing into Agent SDK subagents
In the Claude Agent SDK, decomposition takes the form of subagents. You define them with the agents option in code, or as markdown files in .claude/agents/. The main agent invokes them through the Agent tool. Each subagent runs in its own conversation, and its intermediate tool calls stay inside that conversation; only its final message returns to the parent. That isolation is the reason Coordinator pattern and isolated subagent context applies even when nothing runs in parallel. The main reason to split may be to keep pages of tool output out of the main agent's context.
@dataclass
class AgentDefinition:
description: str
prompt: str
tools: list[str] | None = None
disallowedTools: list[str] | None = None
model: str | None = NoneThree fields carry the decomposition. description is a natural-language statement of when to use the agent, and the orchestrator reads it to decide where each piece of work goes. tools is the allowed list; if you leave it out, the subagent inherits every tool available to subagents, so leaving it blank removes the scoping. prompt is the specialist's system prompt.
Take a codebase audit with three dimensions (security vulnerabilities, code quality and test coverage), each needing different tools and a different focus. The decomposition is an orchestrator plus three subagents, each with a description and a tool set matched to its dimension. A security scanner, a style checker and a coverage checker can then run at the same time instead of one after another. Compare the alternatives:
- One prompt asking the main agent to do all three in sequence. Every dimension's tool output builds up in a single context, and quality drops as the context grows.
- One MCP server exposing all the checks as tools for the main agent. This adds tools without separating anything. An agent loaded with tools across unrelated domains confuses which domain applies, and with roughly 20 or more tools it struggles to pick the right one.
- A larger context window plus extended thinking. More room does not solve the problem. Response quality can degrade as context grows, so more space for clutter makes the clutter worse.
Checkpoint 7 of 10· Check yourself
Your team is building an agent to audit a codebase for security vulnerabilities, code quality and test coverage. Each of the three needs different tools. In early trials the main agent's context fills up with scanner and linter output, and its later findings get worse. Which design fixes this?
Each subagent runs in its own conversation. Its tool calls stay there, and only its final message goes back to the parent, so the main agent's context stays clean. The subagents can also run at the same time. Putting all the checks on one server gives the agent more tools without separating anything. A bigger context window just leaves more room for the clutter. Doing the three in order inside one prompt still piles all the output into the same context.
“intermediate tool calls and results stay inside the subagent; only its final message returns to the parent.”Source: code.claude.com
Checkpoint 8 of 10· Exam question
A team is building an agent that must audit a large codebase across three distinct dimensions: security vulnerabilities, code quality, and test coverage. Each dimension requires a different set of tools and a different area of focus. Which approach best decomposes this problem using the Agent SDK?
Correct answer: A — Define an orchestrator agent that invokes specialized subagents through the Agent tool, each configured with a scoped tool set and description matching its subtask domain
- A. Correct. The Agent SDK's subagent capability lets an orchestrator delegate focused subtasks to specialized agents, each with its own scoped tools and description, then aggregate their results — the intended decomposition pattern for multi-dimensional review work.
- B. Incorrect. A single undifferentiated prompt forces one agent to hold all three review contexts and tool needs at once, losing the isolation and specialization benefits of decomposition.
- C. Incorrect. Exposing checks as tools on one MCP server still leaves a single agent responsible for orchestrating and interpreting all three domains itself, rather than delegating focused reasoning to specialized subagents.
- D. Incorrect. A larger context window and extended thinking add reasoning depth but do not decompose the task into independently scoped, delegatable units of work.
7.Moving a tight tool loop into code
Sometimes the cost is in the tool calls, not in the subtasks. If a step needs dozens of small tool calls in a loop, each standard tool-use turn is a round trip through the model, and each result adds to the context. Programmatic tool calling removes that overhead. Claude writes code that calls your tools inside a code execution container, so the loop runs in the container instead of passing through the model on every call.
The standard approach makes 20 separate round trips through the model and pulls thousands of expense lines into the context. With programmatic tool calling, one script runs all 20 lookups, filters the results, and returns only the employees over their limit. Claude reasons over a few lines instead of hundreds of kilobytes.
The savings come from filtering. Data is processed before it reaches the model's context window, so latency and token use both fall. The feature needs the code execution tool at version code_execution_20260120 or later.
Two other options look similar but do not help. The Message Batches API processes requests asynchronously and independently, and most batches finish within an hour. That suits bulk work that does not need an immediate response, but it cannot feed one tool's result into the next step of a live loop. Wrapping each tool call in its own subagent keeps the orchestrator's context clean, but it adds a whole agent for each call, and multi-agent setups typically use 3 to 10 times more tokens. That makes the overhead problem worse.
Checkpoint 9 of 10· Check yourself
An expense agent has to make 40 small lookup calls in a loop inside one step. Each call is a round trip through the model, and every result adds to the context. Four fixes are proposed. Which one would make the overhead worse instead of better?
A subagent per call keeps the orchestrator's context clean, but it adds a whole agent for each lookup, and multi-agent setups typically use 3 to 10 times more tokens. When the overhead comes from many small tool calls in one step, the fix is programmatic tool calling: the loop runs in code and only filtered results reach the model.
“In our testing, multi-agent implementations typically use 3-10x more tokens than single-agent approaches for equivalent tasks.”Source: claude.com
Checkpoint 10 of 10· Exam question
A decomposed data-processing workflow requires Claude to invoke dozens of small tools in a tight loop, and issuing each call through the standard conversational tool-use turn is adding significant latency and token overhead. Which technique addresses this?
Correct answer: A — Use programmatic tool calling so Claude invokes tools directly from a code execution container, cutting round trips and token overhead per call
- A. Correct. Programmatic tool calling lets Claude call tools directly from code running in a code execution container, avoiding a full conversational round trip per call and reducing latency and token consumption for tight, multi-tool loops.
- B. Incorrect. Wrapping every small tool call in its own subagent adds orchestration and reporting overhead rather than removing the per-call round-trip cost within a tight loop.
- C. Incorrect. Message Batches is for asynchronous, large-volume request processing, not for reducing round trips within a single live, tightly looped tool-calling workflow.
- D. Incorrect. Raising effort increases reasoning depth per turn but does not change how many separate conversational turns are needed to issue a large number of small tool calls.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://www.anthropic.com/engineering/building-effective-agentsSecondary source
“For complex tasks with multiple considerations, LLMs generally perform better when each consideration is handled by a separate LLM call”
↩︎ Why decomposition improves results“on any intermediate steps to ensure that the process is still on track”
↩︎ Prompt chaining: fixed steps with gates between them“where the task can be easily and cleanly decomposed into fixed subtasks”
↩︎ Prompt chaining: fixed steps with gates between them“Without this workflow, optimizing for one kind of input can hurt performance on other inputs.”
↩︎ Routing: split by input type, and match the model to the subtask“Routing easy/common questions to smaller, cost-efficient models like Claude Haiku 4.5 and hard/unusual questions to more capable models like Claude Sonnet 4.5”
↩︎ Routing: split by input type, and match the model to the subtask“This tends to perform better than having the same LLM call handle both guardrails and the core response.”
↩︎ Parallelization: sectioning and voting“Voting: Running the same task multiple times to get diverse outputs.”
↩︎ Parallelization: sectioning and voting“subtasks aren't pre-defined, but determined by the orchestrator based on the specific input”
↩︎ Orchestrator-workers: decomposition decided at run time“For complex tasks with multiple considerations, LLMs generally perform better when each consideration is handled by a separate LLM call”
↩︎ Key concept“The main goal is to trade off latency for higher accuracy, by making each LLM call an easier task.”
↩︎ Exam trap 1“LLMs generally perform better when each consideration is handled by a separate LLM call, allowing focused attention on each specific aspect.”
↩︎ Checkpoint“The main goal is to trade off latency for higher accuracy, by making each LLM call an easier task.”
↩︎ Prediction“where classification can be handled accurately, either by an LLM or a more traditional classification model/algorithm”
↩︎ Checkpoint - 2.
“where multiple well-scoped tasks contribute to an overall goal”
↩︎ Why decomposition improves results“Specialization: Route to agents with domain-focused system prompts and tools”
↩︎ Routing: split by input type, and match the model to the subtask“With dynamic workflows, it writes a workflow: a program that runs many agents in the background and combines their results.”
↩︎ Orchestrator-workers: decomposition decided at run time“Every agent in a run uses tokens, so set a session budget to cap the session's spend, runs included.”
↩︎ Orchestrator-workers: decomposition decided at run time - 3.
“suffered from lost context at each handoff and spent more tokens coordinating than executing”
↩︎ Why decomposition improves results“multi-agent systems often take longer overall than single-agent systems because of the sheer increase in total computation”
↩︎ Parallelization: sectioning and voting“An agent with too many tools (often 20+) struggles to select the appropriate one.”
↩︎ Decomposing into Agent SDK subagents“Large language models have finite context windows, and response quality can degrade as context grows.”
↩︎ Decomposing into Agent SDK subagents“multi-agent implementations typically use 3-10x more tokens than single-agent approaches for equivalent tasks”
↩︎ Moving a tight tool loop into code“multi-agent systems often take longer overall than single-agent systems because of the sheer increase in total computation”
↩︎ Exam trap 2“The primary benefit of parallelization is thoroughness, not speed.”
↩︎ Prediction“In our testing, multi-agent implementations typically use 3-10x more tokens than single-agent approaches for equivalent tasks.”
↩︎ Checkpoint - 4.
“Chain workflow for structured data extraction and formatting”
↩︎ Prompt chaining: fixed steps with gates between them - 5.https://code.claude.com/docs/en/workflowsOfficial docs
“use a workflow to review every file changed in this PR for correctness issues, then merge the per-file findings into one ranked summary”
↩︎ Prompt chaining: fixed steps with gates between them - 6.https://claude.com/blog/claude-models-explained-choosing-the-best-model-for-your-use-caseSecondary source
“Haiku models are designed for high-frequency workloads where latency and cost matter.”
↩︎ Routing: split by input type, and match the model to the subtask“If it typically takes a lot of time, involves multiple steps, or is previously unsolved then a more capable model class is appropriate.”
↩︎ Routing: split by input type, and match the model to the subtask - 7.https://code.claude.com/docs/en/agent-sdk/pythonOfficial docs
“Model override for this agent.”
↩︎ Routing: split by input type, and match the model to the subtask“Natural language description of when to use this agent”
↩︎ Decomposing into Agent SDK subagents“Array of allowed tool names. If omitted, inherits every tool available to subagents”
↩︎ Decomposing into Agent SDK subagents - 8.https://code.claude.com/docs/en/agent-sdk/subagentsOfficial docs
“independent subtasks finish in the time of the slowest one rather than the sum of all of them”
↩︎ Parallelization: sectioning and voting“intermediate tool calls and results stay inside the subagent; only its final message returns to the parent.”
↩︎ Decomposing into Agent SDK subagents“During a code review, you can run style-checker, security-scanner, and test-coverage subagents simultaneously instead of sequentially.”
↩︎ Decomposing into Agent SDK subagents - 9.
“Requires N+1 LLM calls (1 orchestrator + N workers)”
↩︎ Orchestrator-workers: decomposition decided at run time“Orchestrator might not break down tasks optimally (prompt engineering is critical)”
↩︎ Orchestrator-workers: decomposition decided at run time“Consider using Claude Opus for the orchestrator and Claude Haiku for workers to optimize cost vs. quality”
↩︎ Orchestrator-workers: decomposition decided at run time“Subtasks are predictable and can be pre-defined (use simpler parallelization)”
↩︎ Exam trap 3 - 10.https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-callingOfficial docs
“rather than requiring round trips through the model for each tool invocation”
↩︎ Moving a tight tool loop into code“With programmatic tool calling, a single script runs all 20 lookups, filters the results, and returns only the employees who exceeded their limits”
↩︎ Moving a tight tool loop into code“decreases token consumption by allowing Claude to filter or process data before it reaches the model's context window”
↩︎ Moving a tight tool loop into code“rather than requiring round trips through the model for each tool invocation”
↩︎ Exam trap 4 - 11.
“The batch is then processed asynchronously, with each request handled independently.”
↩︎ Moving a tight tool loop into code