Skip to content
CCAR-F Prep

Task Statement 1.1·Domain 1 — 27% of exam

Agentic Loops

Design and implement agentic loops for autonomous task execution

Jump to practice →

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:

  1. 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.

  2. 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.
  3. When stop_reason is "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.

  4. When stop_reason is "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 Your code holds the conversation in a messages array and sends the whole array to the model. The reply carries a stop_reason field. While it reads "tool_use" the loop continues, and it continues in a fixed order: append the assistant message that carried the tool_use block to the history, run the requested tool, then append the result as a user message containing a tool_result block whose tool_use_id matches. There is no tool role — results travel in user messages. The array grows by two messages on every pass, which is how the model can reason about what the tool returned. When stop_reason reads "end_turn" the loop exits and the final answer goes to the user. send messages[] LLM Messages API reply stop_reason "tool_use" "end_turn" "tool_use" append the reply Run the tool lookup_order append the result "end_turn" ✓ Done final answer Your code the loop messages[] user the task assistant tool_use user tool_result
1 / 6Swipe diagram ↔

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_turn

Six 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.

RuleWhy it existsIf you break it
Append the assistant response unchanged, text and tool_use blocks togetherThe tool_use blocks carry the id each result must cite, and they are the model's own record of what it asked forAppending 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 firstOne response can request several toolsA call left without a result gets the next request rejected
Put all of that turn's results in one user messageOne turn's calls are answered togetherA separate message per result is accepted, but it teaches Claude to stop batching calls
Results first, any text after themA formatting requirement of the APIText ahead of a tool_result is a 400
Nothing between the two messagesResults must immediately follow the calls they answerA 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 nextThe model can only recover from a failure it can seeDropping 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 loopPre-configured tree or fixed sequence
Who picks the next toolClaude, from the accumulated contextYour code, from a static graph
An unexpected tool resultChanges the next callFalls off the graph: no branch was written for it
Order of callsNot guaranteed; the same input can take different pathsGuaranteed
FitsAmbiguous requests and open-ended investigation, such as the support scenario's returns and billing disputesCompliance-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.

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 with stop_reason "tool_use", so the loop owes the model a tool_result and one more pass, on which the model writes its closing message and reaches end_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 is stop_reason's.
  • A truncated response (beyond the guide). max_tokens means generation hit the output ceiling mid-thought. A loop that treats every value other than tool_use as 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 One assistant reply carries two things: a stop_reason field reading "tool_use", and a content array holding two blocks — a text block at index 0 and a tool_use block at index 1. stop_reason is a field on the reply, not an element of the array. Code that checks whether the first element of content is text finds text, concludes the agent has finished, and exits the loop, so the tool call at index 1 never runs and the customer is left with a half answer. Reading response.stop_reason instead returns "tool_use", the loop continues, the tool runs, and the customer gets a real answer. The model often says what it is about to do before calling a tool, so text in a reply never means the work is finished. the assistant reply stop_reason "tool_use" ! content: [ ] 0 { type: "text" } “Let me look up your order.” 1 { type: "tool_use" } lookup_order · id toolu_01 ✕ ✓ response.content[0] .type == "text" ✕ the loop exits early response.stop_reason == "tool_use" ✓ the loop continues what the customer gets back “Let me look up your order.” …and nothing more. The agent stopped before running the tool. “Order #4471 shipped on Tuesday. Anything else?”
1 / 6Swipe diagram ↔

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_reasonWhat it means
end_turnThe model reached a natural stopping point
max_tokensGeneration exceeded the requested max_tokens, or the model's own maximum
stop_sequenceOne of your custom stop_sequences was generated (read the response's stop_sequence field to see which)
tool_useThe model invoked one or more tools
pause_turnA long-running turn was paused; you may hand the response back as-is in a subsequent request to let the model continue
refusalStreaming classifiers intervened to handle a potential policy violation
model_context_window_exceededThe 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.

ValueDocumented handling
end_turnUse the response
tool_useRun the tool and return the result
pause_turnSend the assistant content back to continue
max_tokensRaise max_tokens or continue the response
stop_sequenceRead stop_sequence to see which one fired
refusalRead stop_details and retry on a fallback model
model_context_window_exceededTreat 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_use block carries three fields: id (unique, used to match the result later), name, and input (conforming to the tool's input_schema).
  • Results go back in a user-role message containing tool_result blocks, each with tool_use_id matching the request's id, optional content, and optional is_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_result block may carry only type and tool_use_id.
  • Leave a tool_use block without a result, or put text ahead of the results, and the request fails with a 400 invalid_request_error whose message includes "tool_use ids were found without tool_result blocks 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 content with "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 new tool_use block", 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_error result 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, and strict: true on 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_result for each tool_use block, all together in the next user message", matched by tool_use_id, with every tool_result before 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: true and 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 Three runs of the same agent, each drawn as a row of iteration slots with its cap marked before the run begins. Run A finishes in three passes because stop_reason returns end_turn, and its cap of twenty is never reached — a cap you never hit is a safety net doing its job. Run B needs twelve passes but its cap is ten, so the cap is what stops the loop: two passes of real work never happen and the agent is cut off rather than finished, which is the anti-pattern. Run C never checks the stop signal and has no cap at all, so nothing ends it and it runs away — the situation a cap exists to bound. A cap limits cost and prevents runaway loops; it never tells you the task is complete. Only stop_reason does that. Finishes on its own needed 3 passes cap 20 ✓ end_turn 17 passes unused ✓ correct Cap does the stopping needed 12 passes cap 10 cap 10 2 passes of real work, never done ✕ anti-pattern Nothing says stop stop_reason never checked no cap ! why caps exist stop_reason is the finish line — the cap is only the fuse
1 / 6Swipe diagram ↔

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:

subtypeWhat happenedFinal text in result?
successClaude finished the task normallyYes
error_max_turnsThe turn limit was reached before finishingNo
error_max_budget_usdThe spend limit (max_budget_usd / maxBudgetUsd) was reached before finishingNo
error_during_executionAn error interrupted the loopNo
error_max_structured_output_retriesNo valid structured output within the retry limitNo

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.

Sourcesplatform.claude.com › define-toolsplatform.claude.com › overviewfetched 2026-11-19

Quick Reference

FactValue
Exam's two loop-control valuestool_use (continue), end_turn (terminate)
Full stop_reason enumend_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal, model_context_window_exceeded
Client tool loop exits onAny stop reason other than tool_use — which is not the same as the task being finished
pause_turn handlingAppend 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 handlingRead stop_details, retry on a fallback model
model_context_window_exceeded handlingTreat the response as truncated
Stop reason vs errorStop reasons are in a 200 response body; errors are HTTP 4xx/5xx
stop_reason when streamingnull in message_start; provided in message_delta
What a tool_use pass appendsThe assistant response unchanged, then one user message with every tool_result
tool_use block fieldsid, name, input
tool_result block fieldstool_use_id, optional content, optional is_error
Role carrying tool_resultuser (there is no tool or function role)
Placement rule 1tool_result message must immediately follow the tool_use message
Placement rule 2All tool_result blocks come before any text in that message
Parallel callsOne tool_result per tool_use, all in one user message; failed and skipped calls get is_error: true
Broken pairing error400 with "tool_use ids were found without tool_result blocks immediately after"
Turning off parallelismdisable_parallel_tool_use: true inside tool_choice, not top-level
Default tool_choice when tools suppliedauto — Claude may return text, a tool call, or both
tool_choice: "any"/"tool" side effectResponse starts with a tool call; no natural-language text before tool_use, and no thinking block
tool_choice: "any"/"tool" availability400 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 roleSafety bound to maintain control; when it fires, raise or alert, never return the last response as the answer
SDK capmax_turns / maxTurns ("Maximum agentic turns", no limit by default); the count includes the final text-only turn
SDK termination stateResult message subtype: success, or error_max_turns, error_max_budget_usd, error_during_execution, error_max_structured_output_retries
Failed or invalid tool callReturn a tool_result with is_error: true; Claude can call the tool again or tell the user, so limit retries

Exam Traps

More wrong answers, and why each fails

The tempting answerWhy it failsChoose 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 responseBranch on stop_reason
Send the tool's output as a system message, or add it to the assistant messageResults return only as tool_result blocks in a user messageAppend a user message keyed by tool_use_id
Summarise or cut tool results before appending them, to save tokensThe model reasons only on what it is given; a cut that drops what the next decision needs breaks the chainTrim 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 signalAnswerThe 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 textContinue while stop_reason is tool_use, terminate on end_turnRaise the iteration cap; scan for a completion phrase; force tool_choice any
The loop ends early on some requests and never on othersThe same single condition on stop_reason fixes both directionsTwo 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 responseKeep the cap as a guard only; completion stays with stop_reason, and a reached cap is surfaced as a failureAccepting 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 argumentsThe tool result is not being appended to the conversation between iterationsRewriting 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 resultsDeleting 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 turnResults 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 varyMore 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 completionThe 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