What you will be able to do
- Match a task to prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer, or an autonomous agent
- Say who drives the tool-use loop in each setup: your own code, Anthropic's servers, the Agent SDK, or a framework, and decide when calling the API directly is the better choice
- Use subagents to keep exploration out of the main context window
- Resume an earlier subagent across query() calls with its session ID and agent ID
- Choose between memory files that persist across sessions and the context window, which lasts only for one session
Key concept
Workflow versus agent — In a workflow, your code fixes the path that LLM calls take. In an agent, the model decides its next step from what it has seen so far. Pick the simplest structure that solves the task, and use an agent only when the steps can't be known in advance.
1.The five workflow patterns and when an agent fits instead
Start with the simplest design and add structure only when a measured gain pays for it. Agentic systems usually trade latency and cost for better task performance. For many applications, a single well-prompted LLM call with retrieval and a few examples is enough. When it isn't, there are five standard workflow shapes. In each one your code fixes the path, and the model does the work at each step.
| Pattern | Shape | Fits when |
|---|---|---|
| Prompt chaining | A fixed sequence of calls. Each call works on the previous output, and code checks can gate between steps | The task splits cleanly into known steps, such as drafting copy and then translating it |
| Routing | A classifier call sends each input to a specialised prompt or model | Inputs fall into distinct categories that are better handled separately, such as easy questions sent to a smaller model |
| Parallelization | Sectioning (independent subtasks run at once) or voting (the same task run several times) | Subtasks are independent and speed matters, or you need several attempts for higher confidence |
| Orchestrator-workers | A central LLM breaks the task down at runtime, hands parts to workers, and combines their results | You can't predict the subtasks in advance, such as code changes across an unknown number of files |
| Evaluator-optimizer | One call generates, another evaluates and gives feedback, and the loop repeats | There are clear evaluation criteria and refining the output measurably improves it |
| Autonomous agent | The model chooses its own tool calls in a loop, guided by feedback from its environment | The number of steps is open-ended and each step can be checked against reality, such as by re-running tests |
Parallelization and orchestrator-workers both split work, and they are the pair candidates confuse most often. In sectioning, the subtasks are fixed in code before the run starts. In orchestrator-workers, the model decides the subtasks at runtime. Voting is a different case: it runs the same task several times, such as several prompts each reviewing code for vulnerabilities, and combines the verdicts. Running the parts at the same time also cuts wall-clock time, because concurrent subagents finish when the slowest one finishes, not after the sum of all of them.
Checkpoint 1 of 8· Check yourself
A pipeline sends the same pull request to four differently worded review prompts and flags the code if any of them finds a vulnerability. Which pattern is this?
The same task runs several times in parallel and the outputs are combined, which is the voting form of parallelization. No orchestrator decides the subtasks at runtime.
“Voting: Running the same task multiple times to get diverse outputs.”Source: www.anthropic.com
Checkpoint 2 of 8· Exam question
An engineering team is building an agent to refactor a large legacy codebase. The exact files needing changes, and how many edits are required, cannot be known until the model inspects the code and encounters each dependency. Which workflow pattern from Anthropic's agent design guidance best fits this task?
Correct answer: A — Deploy an orchestrator LLM that decomposes the refactor into subtasks at runtime and delegates each one to worker LLMs, then synthesizes their combined edits
- A. Correct — orchestrator-workers fits exactly this unpredictable, dependency-driven decomposition where subtasks emerge as the model inspects the code.
- B. Wrong — prompt chaining requires the subtasks to be known and fixed in advance, which conflicts with the scenario's unpredictable dependencies.
- C. Wrong — routing assumes categories are known upfront and doesn't handle a task where subtasks emerge dynamically during execution.
- D. Wrong — parallel voting works for independent attempts at the same task, not for decomposing an unpredictable set of dependent edits.
2.Who drives the tool-use loop
Every agent runs the same cycle: Claude asks for a tool, the tool runs, and the result goes back to Claude. That cycle is covered in [the tool-use (agentic) loop](lesson:8.1). The design choice is who drives it. The answer decides what your code is responsible for and how much of the cycle you can see.
Whoever drives the loop decides what to do next by reading the stop_reason on each API response, which reports why Claude stopped generating. "tool_use" means Claude wants a client tool run, and "end_turn" means it produced a final answer; "max_tokens", "stop_sequence", and "refusal" are other stops your code has to handle. "pause_turn" belongs to server tools: their internal loop has an iteration limit, and when it is reached before the work is done the response comes back paused. Re-sending the conversation, including the paused response, lets Claude continue where it left off.
| Who drives the loop | What your code does | What you give up or gain |
|---|---|---|
| Your own code on the Messages API | Loops while stop_reason is "tool_use": runs each tool, sends tool_result blocks back, and handles end_turn, max_tokens, and refusal | You see and control every request. You also write every line of the loop |
| Anthropic's servers (web_search, web_fetch, code_execution) | Enables the tool and re-sends the conversation when stop_reason is "pause_turn" | Several iterations happen inside one request, out of your view |
| Claude Agent SDK query() | Iterates over the messages it yields (AssistantMessage, UserMessage, ResultMessage). The SDK runs the tools | Built-in tools, subagents, hooks, and session IDs. The loop itself is handled for you |
| A third-party framework (e.g. Strands, LangGraph, PydanticAI) | Configures the framework's agent object | Easy start. The extra layers hide the actual prompts and responses |
With the Agent SDK, the loop runs inside the library. Claude responds, the SDK runs each requested tool, the results go back to Claude, and the cycle repeats until a response contains no tool calls. Then the SDK yields a ResultMessage with the final text, token usage, cost, and session ID. Your code watches the message stream instead of building requests.
Agent frameworks such as the Claude Agent SDK, Strands Agents SDK by AWS, LangGraph, and PydanticAI take over the low-level wiring: calling the model, defining and parsing tools, and chaining calls together. Taking over that wiring is also what hides things from you. When an agent misbehaves, the cause is usually in a prompt or tool result that the framework assembled and you never saw. That makes calling the API directly the better choice in two cases: when a pattern needs only a few lines of code, and when you must inspect exactly what Claude received. If you do adopt a framework, read the code it runs underneath, and don't add steps just because the framework makes them easy to add.
Checkpoint 3 of 8· Check yourself
A team's framework-built agent sometimes calls the wrong tool. Nobody can tell what tool descriptions Claude actually received. Which move best addresses the root cause?
The problem is that the framework's abstraction hides the prompts. Calling the API directly makes the prompts visible. Adding more layers or more tools makes the setup harder to inspect, not easier.
“they often create extra layers of abstraction that can obscure the underlying prompts and responses, making them harder to debug.”Source: www.anthropic.com
3.Subagents as a context-window strategy
The context window holds everything Claude sees in a request: the system prompt, every message, every tool result, and the tool definitions. Filling it has a cost. As token count grows, accuracy and recall degrade, which is known as context rot. In an agent loop, tool results are what fill the window fastest. Twenty file reads to find one function leave twenty files in the history for every later turn.
Subagents solve this by isolation. Each subagent runs in its own conversation, and its intermediate tool calls stay inside it. Only its final message returns to the parent. A research subagent can read dozens of files while the main conversation receives a short summary. Subagents bring three other benefits. Several can run at once, which is parallelization. Each can carry a specialised system prompt. And each can be limited to specific tools. In the Agent SDK you define them in the agents option of query(), or as markdown files in .claude/agents/. Claude can also call a built-in general-purpose subagent through the Agent tool.
"test-runner": AgentDefinition(
description="Runs and analyzes test suites. Use for test execution and coverage analysis.",
prompt="""You are a test execution specialist. Run tests and provide clear analysis of results.
Focus on:
- Running test commands
- Analyzing test output
- Identifying failing tests
- Suggesting fixes for failures""",
# Bash access lets this subagent run test commands
tools=["Bash", "Read", "Grep"],
),Isolation is not the only tool. When a single conversation has to keep going past its limit, compaction replaces the older turns with a summary that Claude writes on the server. The broader discipline of what to keep in context belongs to [context engineering](lesson:6.1).
Checkpoint 4 of 8· Check yourself
A parent agent delegates a codebase search to a subagent that reads 40 files. What lands in the parent's conversation?
Intermediate tool calls and results stay inside the subagent. Keeping them out of the parent's window is the reason to delegate.
“intermediate tool calls and results stay inside the subagent; only its final message returns to the parent.”Source: code.claude.com
4.Resuming a subagent across queries
A subagent's work is lost to you unless you capture two identifiers. Suppose an endpoint-finder subagent spends a query cataloguing every API route, and you then call query() again with a follow-up. That second call starts a fresh session with no memory of the catalogue, so the search runs again from the beginning. To continue instead, you need the session ID, which arrives on the ResultMessage. You also need the subagent's agent ID, which appears in the text of the Agent tool's result.
def extract_agent_id(block: ToolResultBlock) -> str | None:
"""Extract agentId from an Agent tool result's text content."""
parts = block.content if isinstance(block.content, list) else [{"text": block.content}]
for part in parts:
if match := re.search(r"agentId:\s*([\w-]+)", part.get("text") or ""):
return match.group(1)
return NoneBoth identifiers are needed, and each does a different job. Passing resume with the session ID gives the second query access to the earlier transcript. Putting the agent ID in the prompt tells Claude which subagent in that transcript to continue. Resuming is also how you recover from maxTurns. When a subagent hits its turn limit, its output comes back marked as partial, and resuming lets it finish with the context it already built.
Checkpoint 5 of 8· Put it in order
Put the steps for resuming the endpoint-finder subagent in order
- 1.Capture session_id from the ResultMessage and agentId from the Agent tool result
- 2.Start a second query() with resume set to the captured session ID
- 3.Include the agent ID in the second prompt so Claude continues that subagent
- 4.Run the first query() that asks Claude to use the endpoint-finder subagent
The identifiers only exist after the first run. The second query must resume that session and name the agent, otherwise it starts fresh.
“pass resume: sessionId in the second query’s options, and include the agent ID in your prompt”Source: code.claude.com
Checkpoint 6 of 8· Exam question
A content team wants an agent that first drafts a product announcement in English, then, only once the draft passes a length and tone check, translates it into French, German, and Japanese. Each step should read only the previous step's validated output. Which workflow pattern matches this design?
Correct answer: B — Prompt chaining, where the draft and each translation are separate LLM calls in a fixed sequence with a programmatic gate verifying the draft before translation begins
- A. Wrong — the languages here are fixed in advance, not dynamically decided by an orchestrator based on unpredictable requirements.
- B. Correct — this is prompt chaining: fixed sequential steps with a gate between the draft and translation stages.
- C. Wrong — routing selects one path among alternatives; here all three translations run in the same predetermined sequence.
- D. Wrong — no evaluator LLM iteratively critiques the translations in this design; the gate is a one-time check, not a feedback loop.
5.Memory that outlives the session
The context window is working memory, and it ends with the session. Resuming carries one transcript forward. Compaction keeps one conversation inside the window's limit. Neither one lets an agent start a new task next week already knowing what it learned this week. For that, knowledge has to leave the context window and go into storage.
The memory tool provides that storage as files. Claude can create, read, update, and delete files in a memory directory, under /memories, and those files persist between sessions. When the tool is enabled, Claude checks the directory before it starts a task. As it works, it writes down what it learns. This is just-in-time retrieval: the agent loads a memory file only when the current task needs it, instead of putting everything it has ever learned into context at the start. A research agent running across dozens of sessions keeps a small active context and still builds up a knowledge base.
The memory tool runs client-side. Claude only requests file operations. Your application performs them against storage you control and returns each result in a tool_result block, so you decide where the data lives and who can read it. Because Anthropic publishes the tool's schema, Claude has been trained on it and calls it more reliably than a homemade equivalent.
Checkpoint 7 of 8· Check yourself
A team enables the memory tool and asks where Claude's memory files are stored. What is the accurate answer?
Claude only asks for file operations. The application carries them out against storage it controls, which is why memory persists independently of any session.
“The memory tool operates client-side: Claude requests file operations, and your application executes them.”Source: platform.claude.com
Checkpoint 8 of 8· Exam question
A support platform wants incoming tickets first classified as billing, technical, or account-access, then handled by a prompt written specifically for that category, since the resolution steps differ substantially between them. Which pattern should the team implement?
Correct answer: C — Routing, where a classifier step directs each ticket to one of three specialized downstream prompts built for its category
- A. Wrong — sectioning parallelizes independent subtasks of the same input; it doesn't select a single specialized path based on category.
- B. Wrong — the categories here are fixed and known in advance, not dynamically invented by an orchestrator.
- C. Correct — routing separates concerns by classifying input and sending it to a specialized prompt for that category.
- D. Wrong — chaining reuses sequential steps on the same output; it doesn't select a single specialized prompt based on classification.
Exam traps
Each one states something that sounds right. Open it to see what is actually true.
1.A complex multi-step task always calls for an autonomous agent.Why is that wrong?
Start simple and add complexity only when it is needed. A fixed workflow, or even a single call, often wins on cost and predictability. Agents fit when the steps can't be predicted.
Covered in The five workflow patterns and when an agent fits instead
2.Server tools such as web_search need your code to execute them and return tool_result blocks.Why is that wrong?
Anthropic runs server tools and their loop. Your code enables the tool and handles pause_turn, but never builds their results.
Covered in Who drives the tool-use loop
3.A follow-up query() automatically reaches the subagent that ran in the previous query.Why is that wrong?
Each query() starts a new session. You must resume the earlier session by its ID and name the agent ID to continue that subagent's transcript.
Covered in Resuming a subagent across queries
4.Loading every past finding into the context at the start of each session is the right way to give an agent long-term memory.Why is that wrong?
The memory tool keeps knowledge in files and reads them back only when needed, so the active context stays focused on the current task.
Covered in Memory that outlives the session
Sources
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.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”
↩︎ The five workflow patterns and when an agent fits instead“A research-assistant subagent can explore dozens of files without any of that content accumulating in the main conversation.”
↩︎ Subagents as a context-window strategy“Each query() call starts a new session by default, and you must resume the same session to access the subagent’s transcript.”
↩︎ Resuming a subagent across queries“When the agent reaches the limit, Claude Code returns its output marked as partial, and you can resume the agent to continue.”
↩︎ Resuming a subagent across queries“Each query() call starts a new session by default, and you must resume the same session to access the subagent’s transcript.”
↩︎ Exam trap 3“intermediate tool calls and results stay inside the subagent; only its final message returns to the parent.”
↩︎ Checkpoint“pass resume: sessionId in the second query’s options, and include the agent ID in your prompt”
↩︎ Checkpoint - 2.https://www.anthropic.com/engineering/building-effective-agentsSecondary source
“Parallelization is effective when the divided subtasks can be parallelized for speed, or when multiple perspectives or attempts are needed for higher confidence results.”
↩︎ The five workflow patterns and when an agent fits instead“Agentic systems often trade latency and cost for better task performance”
↩︎ The five workflow patterns and when an agent fits instead“simplifying standard low-level tasks like calling LLMs, defining and parsing tools, and chaining calls together.”
↩︎ Who drives the tool-use loop“workflows offer predictability and consistency for well-defined tasks, whereas agents are the better option when flexibility and model-driven decision-making are needed at scale.”
↩︎ Key concept“we recommend finding the simplest solution possible, and only increasing complexity when needed.”
↩︎ Exam trap 1“Voting: Running the same task multiple times to get diverse outputs.”
↩︎ Checkpoint“they often create extra layers of abstraction that can obscure the underlying prompts and responses, making them harder to debug.”
↩︎ Checkpoint - 3.
“Client-executed tools (both user-defined and Anthropic-schema) require your application to drive a loop.”
↩︎ Who drives the tool-use loop“Server-executed tools run their own loop inside Anthropic's infrastructure.”
↩︎ Who drives the tool-use loop“A paused turn means the work isn't finished; re-send the conversation (including the paused response) to let the model continue where it left off.”
↩︎ Who drives the tool-use loop“so it calls them more reliably and recovers from errors more gracefully than it would with a custom tool that does the same thing.”
↩︎ Memory that outlives the session“You never construct a tool_result block for these tools.”
↩︎ Exam trap 2“You never construct a tool_result block for these tools.”
↩︎ Prediction - 4.https://code.claude.com/docs/en/agent-sdk/agent-loopOfficial docs
“The SDK runs each requested tool and collects the results.”
↩︎ Who drives the tool-use loop“followed by a ResultMessage with the final text, token usage, cost, and session ID.”
↩︎ Resuming a subagent across queries - 5.
“As token count grows, accuracy and recall degrade, a phenomenon known as context rot.”
↩︎ Subagents as a context-window strategy“represents a "working memory" for the model”
↩︎ Memory that outlives the session - 6.
“Compaction replaces the older turns of a conversation with a summary that Claude writes on the server”
↩︎ Subagents as a context-window strategy - 7.
“Claude can create, read, update, and delete files that persist between sessions, building up knowledge over time without keeping everything in the context window.”
↩︎ Memory that outlives the session“When the memory tool is enabled, Claude automatically checks its memory directory before starting a task.”
↩︎ Memory that outlives the session“Rather than loading all relevant information up front, an agent records what it learns in memory files and reads them back on demand.”
↩︎ Exam trap 4“The memory tool operates client-side: Claude requests file operations, and your application executes them.”
↩︎ Checkpoint