Task Statement 1.1·Domain 1 — 27% of exam
Agentic Loops
Design and implement agentic loops for autonomous task execution
Official Exam Guide Objectives
The objectives below are quoted from Anthropic's Claude Certified Architect – Foundations exam guide, v1.1. Read the exam guide summary for the full blueprint.
Task 1.1: Design and implement agentic loops for autonomous task execution.
Knowledge of
- The agentic loop lifecycle: sending requests to Claude, inspecting stop_reason ("tool_use" vs "end_turn"), executing requested tools, and returning results for the next iteration
- How tool results are appended to conversation history so the model can reason about the next action
- The distinction between model-driven decision-making (Claude reasons about which tool to call next based on context) and pre-configured decision trees or tool sequences
Skills in
- Implementing agentic loop control flow that continues when stop_reason is "tool_use" and terminates when stop_reason is "end_turn"
- Adding tool results to conversation context between iterations so the model can incorporate new information into its reasoning
- Avoiding anti-patterns such as parsing natural language signals to determine loop termination, setting arbitrary iteration caps as the primary stopping mechanism, or checking for assistant text content as a completion indicator
What You Need to Know
An agentic loop is the core execution cycle behind every Claude-based agent. It is deterministic control flow that you write in code — not a prompt trick, not a retry wrapper, not a chatbot turn. Claude never runs the loop; it answers one question per pass and your code decides what happens next. Get this lifecycle right and most of Domain 1 follows from it, because orchestration, hooks and session state all attach to points on this cycle. Get it wrong and the agent stops halfway through a task in production while passing every test you wrote.
The Agentic Loop Lifecycle
Four steps, repeated until the model reports that it is finished:
-
Issue the request. Call the Messages API carrying the entire conversation so far — the system prompt, every previous message, and the tool results produced on the last pass. The API is stateless, so anything absent from this payload does not exist as far as the model is concerned.
-
Branch on
stop_reason. The response carries a field stating why generation stopped. Two values drive a basic loop:"tool_use"— one or more tools have been requested. Another pass is needed."end_turn"— the model considers the work complete. Exit here.
-
When
stop_reasonis"tool_use": run each requested tool, append Claude's response to the conversation unchanged, append the results after it as a new message, and return to step 1 with that extended history. -
When
stop_reasonis"end_turn": stop looping and hand the final response back to the caller. The answer is in its text blocks, so collect them by type rather than by position.
One field decides whether the loop goes round again, step 1: messages[] holds the user's task — your code sends the whole array
The append in step 3 is the step people drop, and dropping it fails quietly. Conversation history is the only route by which a tool result reaches the model — there is no side channel and no server-side memory of the call. Skip the append and pass 2 is byte-identical to pass 1, so the model is asked an unchanged question and has no reason to give a changed answer. It will either reissue the same tool call indefinitely, or decide it cannot proceed and stop with the task half-done. Both look like the model behaving badly and both are your control flow.
What Gets Appended, and in What Shape
Each pass that ends in tool_use adds exactly two messages to the history, in this order: Claude's response, unchanged, as an assistant message; then one user message holding a tool_result for every tool_use block in that response. A turn that narrates and then requests two lookups therefore plays out as two API calls and four messages:
user "I want to return order ORD-4417"
assistant [text "Let me verify your account and pull up that order.",
tool_use get_customer, tool_use lookup_order] stop_reason: tool_use
user [tool_result for get_customer, tool_result for lookup_order]
assistant [text "The return window is still open, so ..."] stop_reason: end_turnSix rules govern that append. The exact wording and field names are in the Deep Dive; what matters here is why each exists and what breaks without it.
| Rule | Why it exists | If you break it |
|---|---|---|
Append the assistant response unchanged, text and tool_use blocks together | The tool_use blocks carry the id each result must cite, and they are the model's own record of what it asked for | Appending only the text, a reconstruction, or just the results "to save tokens" leaves the results with no call to answer |
Answer every tool_use block, not just the first | One response can request several tools | A call left without a result gets the next request rejected |
Put all of that turn's results in one user message | One turn's calls are answered together | A separate message per result is accepted, but it teaches Claude to stop batching calls |
| Results first, any text after them | A formatting requirement of the API | Text ahead of a tool_result is a 400 |
| Nothing between the two messages | Results must immediately follow the calls they answer | A progress note, reminder or log line inserted there is rejected |
A failed or skipped tool still returns a result, flagged is_error: true, saying what went wrong and what to try next | The model can only recover from a failure it can see | Dropping the block breaks the second rule; raising out of the loop ends the run with no chance of recovery |
The last rule is what makes recovery possible. A lookup_order call made with "my last one" instead of an order ID comes back as an error result explaining the expected format; on the next pass the model calls get_customer to find the real ID. Had the executor thrown instead, the customer would have received a stack trace or nothing.
Batching is the model's decision. Two independent lookups can arrive as two tool_use blocks in one response, while a call whose input depends on another call's output has to wait for the next pass. A correct loop handles both without knowing in advance which it will get.
Model-Driven Decision-Making
Inside the loop, tool selection belongs to the model: it reads the task, weighs the tools it has been described, and chooses. That is model-driven decision-making. Its opposite is a pre-configured decision tree or a fixed tool sequence, where the developer settles the order at design time and the model only supplies arguments.
For open-ended work the model-driven option is the stronger design, and the reason is worth carrying rather than memorising. A hard-coded sequence covers exactly the paths its author imagined; the first request that does not fit one falls through it. A model choosing at runtime handles that request, and chains tools in orders nobody wrote down. What you give up is predictability of order — which is precisely why it is the wrong choice whenever the order is itself the requirement.
That exception is standing rather than occasional: where business logic demands deterministic compliance — financial operations, security checks, regulatory requirements — programmatic enforcement overrides model flexibility, because "almost always in the right order" is not a property a regulator accepts. Task Statement 1.4 covers where that enforcement is implemented.
| Model-driven loop | Pre-configured tree or fixed sequence | |
|---|---|---|
| Who picks the next tool | Claude, from the accumulated context | Your code, from a static graph |
| An unexpected tool result | Changes the next call | Falls off the graph: no branch was written for it |
| Order of calls | Not guaranteed; the same input can take different paths | Guaranteed |
| Fits | Ambiguous requests and open-ended investigation, such as the support scenario's returns and billing disputes | Compliance-critical ordering, regulated flows, fixed pipelines |
| Stem wording that points this way | "ambiguous", "the agent should decide", "varies by case" | "must always", "before any", "guaranteed", "deterministic" |
The two columns are rarely an either-or. The architecture that usually answers the question is a model-driven loop with deterministic gates on the few steps that must not vary (Task Statements 1.4 and 1.5). When a stem says one step needs a guarantee, guard that step and leave the rest of the loop model-driven.
Model-driven selection is only as good as what the model is told about its tools. It chooses from each tool's name, description and input schema, so two thinly described tools are hard to tell apart; Task Statement 2.1 covers how to write descriptions that separate them.
The Three Anti-Patterns
Three anti-patterns recur for loop termination. The exam guide names all three, and they are worth recognising on sight, because in a scenario they look like reasonable code rather than obvious errors.
Anti-Pattern 1: Parsing natural language signals. Deciding the loop is over because Claude said "I'm done" or "task complete". The model was never constrained to a vocabulary of completion phrases, so no list of phrases detects completion reliably — and the near misses are the dangerous part. "I've finished analysing the first file" is a completion sentence about an unfinished task, and it will end the run with four files unread. A completion-sounding phrase can even share a response with a tool call — "Let me know if you need anything else after I check", followed by the tool_use block — so a phrase match exits before the tool has run. Expanding the phrase list does not converge on correctness, because the space of things the model might say is not enumerable, and the match is brittle against changes that have nothing to do with the task: a prompt edit, a model update, or a customer writing in another language. stop_reason exists to delete the interpretation step rather than improve it.
Anti-Pattern 2: Arbitrary iteration caps as the primary stopping mechanism. Making "stop after 10 loops" the mechanism that ends the run. This is wrong in both directions simultaneously: a task genuinely needing 12 iterations is truncated, and a task finishing in 3 keeps circling to the ceiling. The truncation is the worse half, because a cut-off run returns a partial answer with no marker distinguishing it from a complete one. The model is already reporting completion on every pass; a cap discards that report in favour of a number chosen before the task began. Caps remain legitimate as a safety net — an upper bound that stops a runaway agent burning tokens — but never as the mechanism that decides the work is done. A cap that fires is also evidence: a loop that never reaches end_turn has a defect, and returning quietly at the ceiling hides it. When the bound is reached, surface it as a failure — raise, alert, or return an explicit "incomplete" status — and never hand back the last response as though it were the answer. A ceiling that raises itself whenever it is hit is no ceiling at all.
Anti-Pattern 3: Checking for assistant text content as a completion indicator. Using response.content[0].type == "text" to conclude the loop has finished. content is an array that can hold several blocks of different types in one response, and Claude routinely returns explanatory text alongside a tool_use block — "I'll now search for the customer's order history", followed immediately by the call itself. What sits at index [0] reflects what the model chose to say first, which carries no information about whether work remains. Moving the check to [1] does not repair it either: block ordering is a presentational detail, not an interface guarantee. Nor does testing whether any block is text; that version exits on the first tool call the model narrates.
Common Exam Distractor
Iteration caps make a plausible-looking fix for premature termination. Reject these answers. A cap is an upper bound, so it can only ever stop a loop sooner — raising or lowering one cannot restart a loop that has already decided to exit. Caps address runaway execution; premature termination is a stop_reason problem.
Two more signals that are not the stop signal
The same mistake appears in two further forms. Neither is in the guide's list of three, but both follow from the same rule.
- A business event. "The model called
escalate_to_human, so we exit" treats a tool call as a control signal. It is not one: that response still ends withstop_reason"tool_use", so the loop owes the model atool_resultand one more pass, on which the model writes its closing message and reachesend_turn. Exiting on the call skips the result and loses the customer-facing message. What a tool call means for the business is your code's concern; whether the loop continues isstop_reason's. - A truncated response (beyond the guide).
max_tokensmeans generation hit the output ceiling mid-thought. A loop that treats every value other thantool_useas success returns that fragment as a finished answer. Raise the ceiling or continue the response; never report it as complete.
Practical Example: The Premature Termination Bug
A developer builds a customer support agent. Simple queries work; complex ones sometimes stop mid-task. Completion is decided by if response.content[0].type == "text".
What happens on a failing request: the customer asks something needing a lookup, and Claude returns a text block explaining its intent ("Let me look up your order") followed by a tool_use block requesting lookup_order. Index [0] holds text, the condition is satisfied, the loop exits, and the customer receives a promise that their order will be looked up — while nothing looks it up. No error is raised anywhere, because from the code's point of view the agent finished normally.
Why it survived testing is the instructive part. Simple queries need no tools, so the model answers them with a single text block and the check happens to be correct. The condition only misfires on responses that contain a tool call — the path that is most awkward to cover in a unit test and most common in production traffic.
The fix is to stop inferring completion from output and read the field that states it: continue while stop_reason == "tool_use", terminate on stop_reason == "end_turn". That condition is indifferent to how many content blocks came back, what types they are, and what order they arrived in.
Text alongside a tool call is not a finish line, step 1: One reply — stop_reason is a field on it, content is an array of blocks
Deep Dive
The complete stop_reason enum
The exam keys on two values. The API reference documents seven, and a production loop has to branch on all of them. Every one of these arrives on a successful HTTP 200 response with valid content — stop reasons are part of the response body, not errors. Errors are 4xx/5xx and carry error details instead.
stop_reason | What it means |
|---|---|
end_turn | The model reached a natural stopping point |
max_tokens | Generation exceeded the requested max_tokens, or the model's own maximum |
stop_sequence | One of your custom stop_sequences was generated (read the response's stop_sequence field to see which) |
tool_use | The model invoked one or more tools |
pause_turn | A long-running turn was paused; you may hand the response back as-is in a subsequent request to let the model continue |
refusal | Streaming classifiers intervened to handle a potential policy violation |
model_context_window_exceeded | The response filled the model's context window |
Anthropic's guidance is blunt: "Make it a habit to check the stop_reason in your response handling logic". The same page separates stop reasons from errors in a pair of lists: stop reasons are "Part of the response body" and "Indicate why generation stopped normally"; errors are "HTTP status codes 4xx or 5xx" and "Indicate request processing failures".
When streaming, the field arrives late. stop_reason is null in the initial message_start event and is provided in the message_delta event, so a streaming loop branches after the delta, not on the first event.
Sourcesplatform.claude.com › createplatform.claude.com › handling-stop-reasonsfetched 2026-11-19
Correct loop control for each value
The documented handling per value maps directly onto branch arms in your loop. Note that only tool_use continues the loop by executing tools; pause_turn continues it by resending unchanged.
| Value | Documented handling |
|---|---|
end_turn | Use the response |
tool_use | Run the tool and return the result |
pause_turn | Send the assistant content back to continue |
max_tokens | Raise max_tokens or continue the response |
stop_sequence | Read stop_sequence to see which one fired |
refusal | Read stop_details and retry on a fallback model |
model_context_window_exceeded | Treat the response as truncated |
pause_turn is the one most loops forget. It is returned "when the server-side sampling loop reaches its iteration limit while running server tools such as web search", and that limit defaults to 10 iterations for each request. To continue, add the response's content unchanged as an assistant message and send the request again with the same tools and no new user message. The docs are explicit: "Your application should handle pause_turn in any agent loop that uses server tools." It never stands in for a client tool call: "When Claude stops to call a tool that you run, the stop reason is tool_use, never pause_turn."
Two of the other arms carry a detail worth knowing. A max_tokens cut can land in the middle of a tool_use block, and the documented fix is to "retry the request with a higher max_tokens value to get the full tool use". On a refusal, the stop_details object "identifies the policy category that triggered it" and is null for every other stop reason.
Sourceplatform.claude.com › handling-stop-reasonsfetched 2026-11-19
The canonical loop, and its exit condition
The documented shape is a while loop keyed on stop_reason:
// 1. Send a request with your tools array and the user message.
// 2. Claude responds with stop_reason "tool_use" and one or more tool_use blocks.
// 3. Run each tool. Format the outputs as tool_result blocks.
// 4. Send a new request containing the original messages, the assistant's
// response, and a user message with the tool_result blocks.
// 5. Repeat from step 2 while stop_reason is "tool_use".
while (response.stop_reason === "tool_use") {
// ...
}The exit condition is stated as the inverse: "The loop exits on any other stop reason ("end_turn", "max_tokens", "stop_sequence", or "refusal"), which means Claude has either produced a final answer or stopped for another reason that your application should handle." That phrasing matters — exiting the loop is not the same as the task being complete.
Two structural facts underpin the whole design. First, "The model never runs anything on its own. It emits a structured request, your code (or Anthropic's servers) runs the operation, and the result flows back into the conversation." Second, "The model can't run your code, so every tool call is a round trip: the model asks, you execute, you report back, the model continues."
Sourceplatform.claude.com › how-tool-use-worksfetched 2026-11-19
A complete loop that keeps every rule
The skeleton above shows the control flow. Filled in, a loop that satisfies every rule in this lesson is still short. Here client is an anthropic.Anthropic() client, and run_tool(block) stands for your executor: it returns the tool_result dictionary for one tool_use block, carrying is_error: true and the error text when the tool fails, and it never raises.
def run_agent(client, messages, tools, run_tool, max_iterations=25):
for _ in range(max_iterations): # runaway guard, not the stop condition
response = client.messages.create(
model="claude-opus-5-5", max_tokens=4096, tools=tools, messages=messages
)
if response.stop_reason == "end_turn": # the only "finished" signal
return "".join(b.text for b in response.content if b.type == "text")
if response.stop_reason != "tool_use": # max_tokens, refusal, pause_turn ...
raise RuntimeError(f"Not finished: stop_reason={response.stop_reason}")
messages.append({"role": "assistant", "content": response.content}) # unchanged
results = [run_tool(b) for b in response.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results}) # one message, results only
raise RuntimeError(f"No end_turn after {max_iterations} iterations")Read it as five invariants. stop_reason is the only thing the control flow consults, and the values that are neither end_turn nor tool_use stop the run for their own handling (table above) instead of falling into the tool branch. The assistant content is appended exactly as received, which is the documented step: "add the response's content unchanged as an assistant message". Every tool_use block gets a result, "even if the tool failed". All results share one user message. And reaching the cap raises, so a runaway run can never be mistaken for a finished one.
Sourcesplatform.claude.com › handling-stop-reasonsplatform.claude.com › handle-tool-callsfetched 2026-11-19
How tool_result blocks are appended — the placement rules
Appending tool results is not "add a message somewhere". There are hard formatting rules, and breaking them gets the request rejected rather than producing degraded behaviour.
- A
tool_useblock carries three fields:id(unique, used to match the result later),name, andinput(conforming to the tool'sinput_schema). - Results go back in a user-role message containing
tool_resultblocks, each withtool_use_idmatching the request'sid, optionalcontent, and optionalis_error. - "Tool result blocks must immediately follow their corresponding tool use blocks in the message history. You cannot include any messages between the assistant's tool use message and the user's tool result message."
- "In the user message containing tool results, the tool_result blocks must come FIRST in the content array. Any text must come AFTER all tool results."
- An empty result is valid: a
tool_resultblock may carry onlytypeandtool_use_id. - Leave a
tool_useblock without a result, or put text ahead of the results, and the request fails with a 400invalid_request_errorwhose message includes "tool_useids were found withouttool_resultblocks immediately after". That message is the signature of a broken pairing, and the docs' advice on seeing it is to "check that your tool results are formatted correctly". - On failure, return the error text as
contentwith"is_error": true: "Claude can then call the tool again or tell the user what happened." Because Claude "might then call the tool again with a newtool_useblock", the same page advises you to "limit how many retries your loop allows". Write the error so the model can act on it: "include what went wrong and what Claude should try next". - A malformed request from Claude itself — a missing required parameter, say — is handled the same way. Return an
is_errorresult naming the problem and "Claude can then call the tool again with the missing information filled in". The docs' preferred fix during development is more detailed tool descriptions, andstrict: trueon the tool definition removes invalid calls altogether.
There is no tool or function role in this API: "user messages include client content and tool_result, whereas assistant messages contain AI-generated content and tool_use."
Sourcesplatform.claude.com › handle-tool-callsplatform.claude.com › handling-stop-reasonsfetched 2026-11-19
Parallel tool calls in one iteration
"By default, Claude may call multiple tools in a single response," and Claude 4 and later models do so by default when the request benefits from it. Your loop must therefore treat tool_use as n calls, not one:
- Return "one
tool_resultfor eachtool_useblock, all together in the next user message", matched bytool_use_id, with everytool_resultbefore any text. - Execution order is yours to choose: "you can run the calls concurrently (
Promise.all,asyncio.gather), sequentially in the order they appear, or in any combination". - Even a call you decline to run needs a result: return it "with
is_error: trueand a brief explanation". - Splitting results across separate user messages "teaches" Claude to avoid parallel calls in future turns — the two rules that keep parallelism alive are one user message for all results, and no text before them.
To restrict this, disable_parallel_tool_use: true goes inside the tool_choice object, not at the top level. With tool_choice auto it means at most one tool per response; with any or tool it means exactly one, on the models that accept those two types (see the last section of this Deep Dive).
Sourceplatform.claude.com › parallel-tool-usefetched 2026-11-19
Iteration caps are a safety bound, not a stop condition
Anthropic's own agent guidance treats caps as control, not completion: it is "common to include stopping conditions (such as a maximum number of iterations) to maintain control". The same article observes that "the autonomous nature of agents means higher costs, and the potential for compounding errors", and the recommendation that goes with it is extensive sandboxed testing plus guardrails — not shorter loops.
The Agent SDK exposes the same idea as a first-class option, maxTurns in TypeScript and max_turns in Python, documented in both SDK references as "Maximum agentic turns" with no limit by default. It bounds the loop; it never tells you the task finished. The next section shows how the SDK reports a cap that was reached.
An iteration cap is a fuse, not a finish line, step 1: Three runs of the same agent — each cap is set before the loop starts
Sourcesanthropic.com › building-effective-agentscode.claude.com › typescriptcode.claude.com › pythoncode.claude.com › agent-loopfetched 2026-11-19
The same loop inside the Agent SDK
The exam's agent scenarios are built on the Claude Agent SDK, where you do not write the loop: the SDK runs it and you observe the messages it yields. The cycle is the one above. Claude evaluates, the SDK executes any requested tools and feeds the results back, and "Claude continues calling tools and processing results until it produces a response with no tool calls." A turn is "one pass through the loop".
What you read at the end is the result message. Its subtype field is "the primary way to check termination state", which makes it the SDK-level counterpart of reading stop_reason:
subtype | What happened | Final text in result? |
|---|---|---|
success | Claude finished the task normally | Yes |
error_max_turns | The turn limit was reached before finishing | No |
error_max_budget_usd | The spend limit (max_budget_usd / maxBudgetUsd) was reached before finishing | No |
error_during_execution | An error interrupted the loop | No |
error_max_structured_output_retries | No valid structured output within the retry limit | No |
In the fragment below, query, ClaudeAgentOptions and ResultMessage are imported from claude_agent_sdk, and the loop sits inside an async function:
async for message in query(
prompt="Find and fix the bug causing test failures in the auth module",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash", "Glob", "Grep"],
max_turns=30, # runaway guard
),
):
if isinstance(message, ResultMessage):
if message.subtype == "success":
print(message.result)
else: # error_max_turns, error_max_budget_usd, ...
print(f"Stopped without finishing: {message.subtype}")Three details matter for judgement questions. A reached cap is reported as an error, never as success: the run ends with error_max_turns "and no final response", and a single-shot query() call then raises, which is the SDK doing what your own loop should do when its guard fires. The turn count includes the last one: "Count each turn with tool calls, plus one for the final text-only response." And the result message also carries the final turn's stop_reason, with end_turn, max_tokens and refusal given as common values, so a refusal is detected by checking that field.
Sourcescode.claude.com › agent-loopcode.claude.com › pythonfetched 2026-11-19
Why text alongside tool_use is normal, and why forcing tools backfires
Under the default tool_choice of {"type": "auto"}, "Claude determines on each turn whether to call a tool or respond directly" (tool-use overview), and "Claude often comments on what it's doing or responds naturally to the user before calling tools". The docs add the warning that kills anti-patterns 1 and 3 outright: "Claude might use various phrasings and approaches when explaining its actions. Your code should treat these responses like any other assistant-generated text, and not rely on specific formatting conventions."
The distractor fix — forcing tool_choice: "any" so the model never returns bare text — has documented side effects. "When tool_choice is any or tool, the API makes Claude's response start with a tool call", so the model emits no natural-language response before the tool_use blocks even if asked to. A forced call also skips thinking: the response "has no thinking block". Manual extended thinking rejects any and tool outright, supporting only auto and none (adaptive thinking does not itself block forced tool use). And changing tool_choice invalidates cached message blocks under prompt caching.
Current state: the newest models reject forced tool use
Exam guide (v1.1, November 2026): tool_choice "any" is an available option that guarantees the model calls a tool rather than returning conversational text (Task 2.3). Current docs: on Claude Fable 5.2, Claude Mythos 5.2, Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1 and Claude Mythos 5.1, "any and tool return a 400 error"; auto and none still work, and the suggested replacement is auto with strict tool use or structured outputs. Answer "any" forces a tool call, and is still the wrong fix for loop termination on the exam.
Sourcesplatform.claude.com › define-toolsplatform.claude.com › overviewfetched 2026-11-19
Quick Reference
| Fact | Value |
|---|---|
| Exam's two loop-control values | tool_use (continue), end_turn (terminate) |
Full stop_reason enum | end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal, model_context_window_exceeded |
| Client tool loop exits on | Any stop reason other than tool_use — which is not the same as the task being finished |
pause_turn handling | Append the assistant response to messages unchanged and re-request with the same tools — do not treat as done. Server-tool loop limit defaults to 10 iterations per request |
refusal handling | Read stop_details, retry on a fallback model |
model_context_window_exceeded handling | Treat the response as truncated |
| Stop reason vs error | Stop reasons are in a 200 response body; errors are HTTP 4xx/5xx |
stop_reason when streaming | null in message_start; provided in message_delta |
What a tool_use pass appends | The assistant response unchanged, then one user message with every tool_result |
tool_use block fields | id, name, input |
tool_result block fields | tool_use_id, optional content, optional is_error |
Role carrying tool_result | user (there is no tool or function role) |
| Placement rule 1 | tool_result message must immediately follow the tool_use message |
| Placement rule 2 | All tool_result blocks come before any text in that message |
| Parallel calls | One tool_result per tool_use, all in one user message; failed and skipped calls get is_error: true |
| Broken pairing error | 400 with "tool_use ids were found without tool_result blocks immediately after" |
| Turning off parallelism | disable_parallel_tool_use: true inside tool_choice, not top-level |
Default tool_choice when tools supplied | auto — Claude may return text, a tool call, or both |
tool_choice: "any"/"tool" side effect | Response starts with a tool call; no natural-language text before tool_use, and no thinking block |
tool_choice: "any"/"tool" availability | 400 on Fable 5.2, Mythos 5.2, Opus 5.5, Sonnet 5.5, Fable 5.1, Mythos 5.1; also unsupported with manual extended thinking |
| Iteration cap role | Safety bound to maintain control; when it fires, raise or alert, never return the last response as the answer |
| SDK cap | max_turns / maxTurns ("Maximum agentic turns", no limit by default); the count includes the final text-only turn |
| SDK termination state | Result message subtype: success, or error_max_turns, error_max_budget_usd, error_during_execution, error_max_structured_output_retries |
| Failed or invalid tool call | Return a tool_result with is_error: true; Claude can call the tool again or tell the user, so limit retries |
Exam Traps
Exam Trap
Using response.content[0].type == 'text' to determine loop completion
content is an array, and a single response can hold an explanatory text block and a tool_use block together. Index [0] records what the model said first, not whether work remains — and checking [1] instead is no safer, because block order is not an interface guarantee. Branch on stop_reason.
Exam Trap
Setting arbitrary iteration caps (e.g., 'stop after 10 loops') as the primary stopping mechanism
A cap truncates a task that needed 12 iterations and keeps circling on one that finished in 3, and the truncated run returns a partial answer indistinguishable from a complete one. Keep caps as a runaway safety net; let stop_reason decide completion.
Exam Trap
Parsing natural language phrases like 'I'm done' or 'task complete' to decide loop termination
Nothing constrains the model to a vocabulary of completion phrases, so the phrase list never converges — and "I've finished analysing the first file" ends the run with four files unread. stop_reason removes the interpretation step rather than improving it.
Exam Trap
Forcing tool_choice to 'any' to prevent the agent from returning text
Requiring a tool call on every response removes the model's ability to end its own turn, so the loop loses the only exit condition it had and runs until something external stops it. Let completion be signalled naturally through stop_reason. (On the newest models the request is simply rejected with a 400, so the proposal fails either way.)
Exam Trap
Replacing the whole loop with a decision tree or state machine because one step must be guaranteed
This over-corrects. The guarantee is needed on one step, and the fixed graph removes the model's ability to adapt on every other step, which is what the ambiguous cases in the scenario depend on. Keep the loop model-driven and put a programmatic gate on the step that must not vary.
More wrong answers, and why each fails
| The tempting answer | Why it fails | Choose instead |
|---|---|---|
| End the loop when the assistant's text "no longer requests further action" | Prose parsing under another name; text and tool_use blocks share a response | Branch on stop_reason |
| Send the tool's output as a system message, or add it to the assistant message | Results return only as tool_result blocks in a user message | Append a user message keyed by tool_use_id |
| Summarise or cut tool results before appending them, to save tokens | The model reasons only on what it is given; a cut that drops what the next decision needs breaks the chain | Trim to the relevant fields, keeping what later steps rely on (Task 5.1) |
How This Is Tested
Three of the exam guide's six scenarios list this domain as a primary one, and all three are built on the Agent SDK: the Customer Support Resolution Agent, the Multi-Agent Research System and Developer Productivity with Claude. Expect a loop question to arrive dressed as one of them. Whatever the setting, a stem on this task probes one of three points: what signals continuation (stop_reason, never text), what gets appended (both messages, in order, with all results in one user message), or what stops the loop (end_turn, not a counter and not a keyword). Identify which point the stem is probing and the answer usually follows.
| Stem signal | Answer | The wrong answer sitting beside it |
|---|---|---|
| The agent says "Let me look that up" and stops; the exit check reads the first block or looks for text | Continue while stop_reason is tool_use, terminate on end_turn | Raise the iteration cap; scan for a completion phrase; force tool_choice any |
| The loop ends early on some requests and never on others | The same single condition on stop_reason fixes both directions | Two separate patches: a phrase list for one, a cap for the other |
| A colleague proposes stopping after N iterations to bound cost, returning the last response | Keep the cap as a guard only; completion stays with stop_reason, and a reached cap is surfaced as a failure | Accepting the cap as the stopping mechanism, or banning caps altogether |
| The agent "forgets" what it just looked up and requests the same tool with the same arguments | The tool result is not being appended to the conversation between iterations | Rewriting the tool description; disabling parallel tool use |
A 400 reading "tool_use ids were found without tool_result blocks immediately after" | Some tool_use block has no result in the very next user message (a failed or skipped call was dropped, or a message was inserted in between), or text precedes the results | Deleting the unanswered tool_use block from history; deferring the result to a later turn |
| Over a session the agent stops batching and makes one call per turn | Results were split across several user messages, or led by text | "Parallel tool use has to be switched on" (it is on by default) |
| A fixed tool sequence fails on a case nobody anticipated; should the agent follow a sequence or decide? | Model-driven selection inside the loop, with deterministic gates only on the steps that must not vary | More hard-coded branches; a single up-front plan; a state machine over all the tools |
An Agent SDK run hits max_turns, and the proposal is to treat that as completion | The cap is a guard; read the result subtype (success versus error_max_turns) | "A generous enough cap is only reached when the work is done" |
Practice Scenario
Your support agent hands a ticket to escalate_to_human whenever a response opens with plain text, on the assumption that Claude only writes prose once it has finished working the case. For a routine refund-status question, Claude's reply opens with a one-line acknowledgement followed by a tool_use block for lookup_order, and the ticket is escalated before that lookup ever runs. What's the most effective first step?
Practice Questions
Exam simulator
Question 1 of 13
Scenario · Customer Support Resolution Agent
Your support agent runs every conversation through a fixed sequence: get_customer, lookup_order, then process_refund or escalate_to_human. Returns resolve on first contact 84% of the time, but billing disputes only 41%. Transcripts show it fetching an order for a customer asking why their card was charged twice, then escalating. What change would most effectively raise first-contact resolution?
Sources
- Agent SDK overview — Anthropic
- Building with Claude API (Skilljar) — Anthropic
- Messages — Anthropic
- Create a Message — Anthropic
- Stop reasons and fallback — Anthropic
- How tool use works — Anthropic
- Handle tool calls — Anthropic
- Parallel tool use — Anthropic
- Define tools — Anthropic
- Tool use with Claude — Anthropic
- Building effective agents — Anthropic
- How the agent loop works — Anthropic
- Agent SDK reference - TypeScript — Anthropic
- Agent SDK reference - Python — Anthropic
Did this lesson help?
This guide is free and stays free: no login, no paywall, no locked lessons. If it saved you an evening of digging through docs, a coffee helps keep it maintained against the exam guide.