Skip to content

1.1 Agentic Loops

On its own, Claude answers one request with one response. To act, such as finding an order, it needs tools: functions in your code that you describe to Claude in the request. Claude does not run a tool you define. When Claude needs a tool, its response asks for the call. Your code then runs the function and returns the result to Claude. An agent is Claude, its tools and the code that continues this exchange.

That code is the agentic loop: the core execution cycle of every Claude-based agent. It is deterministic control flow, defined in code. It is not a prompt trick, a retry loop or a chatbot turn. Until Claude has finished, your code sends a request, runs any tools that Claude requests, and sends the results to Claude. The stop_reason field in each response says whether to run the loop again. The other Domain 1 lessons, on orchestration, subagents, hooks and sessions, all depend on this loop.

This lesson uses one made-up example throughout: a glazier who runs an agent that answers customer messages. When a customer asks for their fitting date, the agent must find the order and check the fitting diary before it replies. An agent with a broken loop stops halfway through a task like this in production.

The loop has four steps, repeated until Claude has finished.

  1. Send a request to Claude via the Messages API. It includes the conversation history: system prompt, prior messages, and any tool results from the previous iteration.
  2. Inspect the stop_reason field in the response. It is the authoritative signal for what happens next. Two of its values matter for agentic loops:
    • "tool_use": Claude wants to call one or more tools. The loop continues.
    • "end_turn": Claude has finished its work. The loop terminates.
  3. If stop_reason is "tool_use", execute the requested tool(s) and append the tool results to the conversation history as a new message. Then send the updated conversation to Claude.
  4. If stop_reason is "end_turn", the agent has finished. Present the final response to the user.

The glazier’s agent gets "tool_use" for the order lookup and again for the diary check, then "end_turn" with the reply.

Step 3 is where loops fail. Your code must append the tool results to the conversation history. Otherwise the model never sees what the tool returned, so it has nothing new to reason about on the next iteration. The glazier’s order details would never reach Claude.

In an agentic loop, Claude uses the current context to decide which tool to call. This is model-driven decision-making: the model reads the task, compares the available tools and picks one. In a pre-configured decision tree or fixed tool sequence, the developer hard-codes which tool runs at which point.

Model-driven approaches are flexible. Claude adapts to situations that the developer never planned for. It handles edge cases. It also uses tools one after another in orders that nobody planned. A glazier’s customer might ask about a cracked pane and a late fitting in one message.

The exception is business logic that demands deterministic compliance, such as financial operations, security checks and regulatory requirements. For that logic, programmatic enforcement overrides that flexibility. So the glazier’s refund rules are in code. Task Statement 1.4 covers this.

Three anti-patterns recur when code decides to stop the loop.

Anti-Pattern 1: Parsing natural language signals. The code checks whether Claude said “I’m done” or “task complete”. Natural language is ambiguous. Claude might say “I’ve finished analysing the first file” while intending to continue with more files. stop_reason exists to remove that ambiguity.

Anti-Pattern 2: Arbitrary iteration caps as the primary stopping mechanism. The code stops after a fixed count, such as 10 loops. If a task needs 12 iterations, the cap stops useful work early. If it finishes in 3, the cap runs unnecessary iterations. The model uses stop_reason to signal that it has finished, so use that field. A cap is acceptable as a safeguard against runaway agents (agents that do not stop), never as the primary control.

Anti-Pattern 3: Checking for assistant text content as a completion indicator. The code uses response.content[0].type == "text" to decide that the loop is finished. Claude can return text together with tool_use blocks. For example, it can return “I’ll now search for the customer’s order history” followed by a tool call. Text in the response does not tell you whether the agent is finished.

Practical Example: The Premature Termination Bug

Section titled “Practical Example: The Premature Termination Bug”

The glazier’s agent works for simple queries but sometimes stops mid-task on complex ones. Its code checks if response.content[0].type == "text" to decide whether the agent has finished. Claude returns “Let me look up your order” together with a tool_use block for lookup_order. The code sees text in position [0] and concludes that the agent is finished. Then the code returns the incomplete response.

The fix is to check stop_reason instead of the content type: continue on "tool_use", terminate on "end_turn". This check works whatever content types the response holds.

If you understand this lifecycle correctly, most of Domain 1 becomes clear. The right answer continues on "tool_use", terminates on "end_turn", and rejects all three anti-patterns. The exam favours model-driven tool selection because it is flexible, except where deterministic compliance requires programmatic enforcement.

Five exam-style multiple-choice questions on Agentic Loops. Pick an answer, then open the explanation.

A developer’s agent sometimes terminates prematurely when Claude returns text alongside a tool call. Their loop checks response.content[0].type == "text" to determine if the agent is finished. Users report incomplete responses on complex queries. What should the developer change?

  • A. Add an iteration cap of 15 loops to ensure the agent runs long enough for complex queries
  • B. Parse the assistant’s text for completion phrases like “I have finished” before terminating the loop
  • C. Check the stop_reason field instead of content type — continue when stop_reason is “tool_use”, terminate when “end_turn”
  • D. Set tool_choice to “any” so Claude always calls a tool instead of returning text, and treat a text-only reply as the end of the run
Answer & explanation

Correct: C

  • C is correct because stop_reason is the deterministic, authoritative signal for loop control. It correctly distinguishes between responses where Claude wants to call more tools (tool_use) and responses where Claude has finished (end_turn), regardless of whether text content appears alongside tool calls.
  • A is wrong because arbitrary caps do not address the root cause. The agent exits because it misidentifies the response type, not because it loops insufficient times. A cap of 15 would still terminate prematurely if the text-check bug triggers on iteration 2.
  • B is wrong because natural language parsing is ambiguous and unreliable. Claude might say it has finished one step while intending to continue with the next. The stop_reason field already provides an unambiguous signal.
  • D is wrong because this forces tool use even when the agent is genuinely finished, creating an infinite loop. The issue is not that Claude returns text — the issue is that the code misinterprets text presence as a completion signal.

Which of the following correctly describes the agentic loop lifecycle?

  • A. Send request, inspect stop_reason, if “tool_use” execute tools and append results to history, if “end_turn” finish
  • B. Send request, check if response contains text, parse text for instructions, execute any tools mentioned in text
  • C. Send request, execute all available tools in sequence, check if any returned errors, retry failed tools
  • D. Send request, count tokens in response, if tokens exceed threshold then tools are needed, otherwise finish
Answer & explanation

Correct: A

  • A is correct because the agentic loop lifecycle follows four deterministic steps: send request via Messages API, inspect stop_reason, execute tools and append results if tool_use, terminate if end_turn.
  • B is wrong because it relies on parsing natural language text for instructions, which is ambiguous. The stop_reason field, not text content, determines what happens next.
  • C is wrong because an agentic loop does not execute all tools in sequence. Claude selects which tool to call based on context (model-driven decision-making). Tools are not retried automatically.
  • D is wrong because token count has no bearing on loop control. The stop_reason field is the sole authoritative signal for whether to continue or terminate.

An agent completes simple tasks correctly but enters an infinite loop on complex queries. The developer’s fix is to add an iteration cap of 10. What is wrong with this approach?

  • A. The iteration cap is too low — it should be at least 50 for complex queries
  • B. Iteration caps only work with synchronous APIs, not with streaming responses
  • C. The agent needs more tools to handle complex queries, not an iteration cap
  • D. Caps are a safety net, but the real bug is an unchecked stop_reason
Answer & explanation

Correct: D

  • D is correct because the infinite loop indicates stop_reason is not being used correctly as the primary control mechanism. An iteration cap masks the underlying bug rather than fixing it. Caps are acceptable only as a safety net (maximum bound) to prevent runaway agents, not as primary loop control.
  • A is wrong because increasing the cap does not fix the root cause. If the loop is infinite because stop_reason is not being checked, no cap value solves the underlying problem — it just delays termination.
  • B is wrong because iteration caps can apply to any execution mode. The issue is using them as primary control rather than checking stop_reason.
  • C is wrong because the number of tools is unrelated to infinite loop behaviour. The loop continues or terminates based on stop_reason, not on whether the right tools are available.

Why must tool results be appended to the conversation history before sending the next request to Claude?

  • A. To reduce API costs by caching previous responses
  • B. So Claude can reason about what the tool returned before deciding what to do next
  • C. To enable streaming of partial results to the user interface
  • D. Because the Messages API rejects requests that do not include complete conversation history
Answer & explanation

Correct: B

  • B is correct because the model needs to see what the tool returned in order to decide its next action. Without tool results in the conversation history, Claude cannot incorporate tool output into its reasoning chain and cannot make informed decisions about whether to call another tool or finish.
  • A is wrong because appending tool results is about enabling reasoning continuity, not cost reduction. The model needs the data to think, not to save money.
  • C is wrong because tool result appending is about the model’s reasoning chain, not about streaming partial results to users. These are separate concerns.
  • D is wrong because the API does not reject incomplete histories as a technical constraint. The issue is that without tool results, the model lacks information needed for correct reasoning.

A customer support agent uses model-driven decision-making to select tools. Under what circumstance should this approach be overridden with programmatic enforcement?

  • A. When the task requires deterministic compliance for financial, security, or regulatory operations
  • B. When the agent is handling more than 3 concurrent conversations, because parallel sessions make model-driven tool selection unreliable
  • C. When the user requests a specific tool by name in their message
  • D. When the agent has access to more than 5 tools, since a wider tool surface makes the model’s selection harder to predict
Answer & explanation

Correct: A

  • A is correct because model-driven decision-making is probabilistic. For operations where a single failure causes financial loss, security breach, or compliance violation, programmatic enforcement provides deterministic guarantees that override model flexibility.
  • B is wrong because the number of concurrent conversations does not determine whether to use model-driven or programmatic approaches. Enforcement type is determined by the stakes of the operation.
  • C is wrong because user requests do not override the architectural decision between model-driven and programmatic enforcement. The stakes of the operation determine the approach.
  • D is wrong because the number of available tools is irrelevant to the enforcement decision. Whether the agent has 2 tools or 20, high-stakes operations require programmatic enforcement.