Skip to content

From single call to agent loop

Phase 2 gave you the single-call building blocks: lessons 1 and 2 nailed the request and response shape; lesson 3 picked a model and the effort dial; lesson 4 added custom client tools; lesson 5 added the Anthropic-provided ones; lesson 6 added MCP. Lesson 7 made a request that mixes all of them affordable to repeat. Everything so far has been one round-trip: one user message, one assistant turn, even if that turn contained server-tool calls or MCP tool calls inline.

This lesson is the transition. Real applications run many round-trips: the model decides, your code (or the connector or a server tool) does work, the model gets the result, decides again, and so on, until some stop condition fires. That loop is what makes a tool-using application agentic rather than reactive. The capability the lesson builds: turn a one-shot single-call pattern into a multi-turn loop with explicit stop conditions, choose deliberately between the workflow path and the agent path, and write the loop in the few lines of direct-API code it actually takes.

Phase 3 opens here. Lesson 9 will catalog the canonical patterns the loop can take. This lesson is the substrate underneath them.

The cleanest framing in the field comes from the Anthropic engineering post Building effective AI agents (Erik S. and Barry Zhang, published in December 2024). The post draws a single distinction worth memorizing verbatim:

  • A workflow is a system where LLMs and tools are orchestrated through predefined code paths.
  • An agent is a system where LLMs dynamically direct their own processes and tool usage, maintaining control over how they accomplish tasks.

The difference is who decides the next step. In a workflow, your code decides: call the model with system prompt A, parse the answer, branch on the answer, call the model again with system prompt B, return. The model is a step in your code's plan. In an agent, the model decides: it sees the tools, it sees the goal, it picks the next tool, it inspects the result, it picks the next one, it answers when it is done. Your code is the plumbing for the loop, not the planner.

The post is direct about the trade-off the choice makes. Workflows give you predictability and consistency for well-defined tasks, whereas agents are the better option when flexibility and model-driven decision-making are needed at scale. The standing advice is to begin by finding the simplest solution possible, and only increasing complexity when needed. Most production applications start as workflows and only graduate to a full agent loop when the task's shape demands it (when the steps are not knowable in advance, when the right path depends on intermediate findings, when "what tool to call next" is itself the hard problem).

Underneath every workflow and every agent in the post sits one building block: an augmented LLM. The model itself, plus three capabilities it can actively use: retrieval (over your data, often via a search tool), tools (custom tools from lesson 4, server and Anthropic-schema tools from lesson 5, and MCP tools from lesson 6), and memory (persistent state across turns or sessions). Track 22 has covered all three lever-by-lever; this lesson is what wires them into a loop.

The post's framing: do not start with a multi-step agent. Start by making the augmented LLM as strong as you can on a single call (tool definitions are good, retrieval is targeted, memory is shaped), then add looping only when a single call cannot do the job.

The agent loop is small. The Anthropic Tool use overview describes the round trip for tools your application runs: Claude stops with the tool-use stop reason and one or more tool-use blocks, your code runs the operation, and you send the result back. Wrap that round-trip in a while loop, add a max-iterations safety, and you have an agent.

The minimal Python:

def run_agent(client, system, tools, user_message, max_iterations=20):
messages = [{"role": "user", "content": user_message}]
for iteration in range(max_iterations):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=4096,
system=system,
tools=tools,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn":
return response # model finished; final text is in response.content
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
})
messages.append({"role": "user", "content": tool_results})
continue
if response.stop_reason == "pause_turn":
# a server-tool loop hit its iteration limit; the assistant turn is
# already appended, so re-call as-is (pass back response.container.id
# if the response has one, or files from earlier in the turn are lost)
continue
# max_tokens, stop_sequence, model_context_window_exceeded, "compaction",
# refusal: handle each explicitly or surface it; do not silently iterate
return response
raise RuntimeError(f"agent exceeded max_iterations={max_iterations}")

Four things this loop does that a single call does not. It appends the assistant turn to messages after each response (the model sees its own prior decisions on the next iteration; without this, you have a one-shot, not a loop). It dispatches tool_use blocks to local handlers and packages the results as tool_result entries on a follow-up user turn. It bounds the iteration count so a misbehaving plan cannot run forever. And it handles non-tool stop reasons rather than treating them all as success.

Lessons 1, 2, 5, and 7 each added a stop_reason the loop now has to dispatch on. The complete set:

  • end_turn. The model is done. Return the response to the caller.
  • tool_use. The assistant content includes one or more tool_use blocks. Execute them, append tool_result entries on a user turn, iterate.
  • pause_turn (from lesson 5 server tools). The server-tool plumbing yielded mid-multi-iteration. Append the assistant turn unchanged and re-call to continue. No new tool dispatch on your side.
  • max_tokens. The model hit the output cap mid-generation. Decide per use case: raise max_tokens, summarize, or surface the partial output.
  • stop_sequence. A configured stop sequence triggered. The agent often treats this as end_turn with a known reason.
  • model_context_window_exceeded (from lesson 7). The response filled the context window, so treat it as cut short. Either compact (if you opted in to compact) or fail with a clear error so the caller can shorten.
  • "compaction" (from lesson 7, with pause_after_compaction: true). Compaction wrote a summary; do the manual preservation pattern (keep the most recent N turns), then re-call.
  • refusal. The model's safety checks declined the request. It arrives as a normal response, not an error, and its stop details name the policy area and give a short explanation. Sending the same request to the same model usually earns another refusal, so do not loop until it gives in. The docs recommend retrying on a fallback model instead: the API, the SDK, or your own code can resend it to another Claude model (the table below lists the options). Where no fallback answers, surface the refusal to the caller. The dispatch is the same shape as the others (an explicit branch), and the discipline is the same: name it, handle it, do not let it fall through to the catch-all.
As of November 2026: refusal handlingDetail
What arrivesHTTP 200 with stop_reason: "refusal" and a stop_details object: category (policy area), explanation (display it, do not parse it; text is not stable), recommended_model (only when fallbacks is set). category and explanation can be null.
Server-side fallback (beta, Claude API and Claude Models on Google Cloud, Anthropic managed)Set fallbacks to "default" (or name up to three models); the API retries in the same call. Not on Message Batches. Haiku 5.5 has no server-side fallback.
Client-side fallbackThe Anthropic SDK refusal-fallback middleware, on any platform.
Manual retryResend with model set to a fallback model; see Fallback credit to avoid paying the prompt-cache write twice.
SourcesHandling stop reasons, Refusals and fallback

A production agent loop dispatches on every one of these explicitly. Silent fall-through is the failure mode that produces "the agent stopped and I do not know why" debugging.

The loop above lets the model decide on every iteration whether to call a tool or finish. That is tool_choice set to auto, the default whenever you send tools: on each turn, Claude itself works out whether to call a tool or answer directly. Three other modes exist:

  • any. The model must call a tool this turn, but picks which.
  • tool (with the tool name in the request). The model must call the named tool.
  • none. The model must not call any tool (useful for a final-answer turn at the end of a workflow).

The first two are the forcing modes, and not every model accepts them. On a model that does not, a request that forces a tool fails with an error. The docs point you elsewhere: keep auto with strict tool definitions, so every call matches its schema, or use structured outputs when you need the reply in a fixed shape. The table below lists which models accept them.

For an agent, auto is usually right anyway (the whole point of the agent is the model deciding). For a workflow, none lets your code end the tool phase deterministically, and on models that accept forcing, tool lets your code choose the next step. Where forcing is not accepted, keep auto and steer with the prompt and with which tools you offer on that step; the docs note that prompting still influences which tool auto picks. The system-prompt nudge is the soft lever: the docs report that "Use the tools to investigate before responding." increases tool use, and "Always call a tool first before responding." pushes further.

One cost fact from the Tool use overview: whenever a request carries tools, the API adds a tool-use system prompt of its own. That is a fixed number of input tokens on every request, on top of your tool definitions. The count depends on the model and on the mode; where the forcing modes are accepted, they cost a little more. In a loop, that fixed overhead is paid again on every iteration, which is one more reason to cache the prefix.

As of November 2026: modelTool-use system prompt tokens, auto or noneTool-use system prompt tokens, any or toolForcing modes (any, tool) accepted?
Claude Fable 5.2Not listed in the Tool use overview tableNot listedNo; returns a 400 error
Claude Opus 5.5286None listedNo; returns a 400 error
Claude Sonnet 5.5286None listedNo; returns a 400 error
Claude Mythos 5.2Not listedNot listedNo; returns a 400 error
Claude Fable 5.1Not listedNot listedNo; returns a 400 error
Claude Mythos 5.1Not listedNot listedNo; returns a 400 error
Claude Haiku 5.5286406Yes (a forced call skips thinking)
Claude Opus 5286406Yes
Claude Sonnet 5354474Yes
Claude Opus 4.8 (legacy)290410Yes
Claude Opus 4.7 (legacy)675804Yes
Claude Opus 4.6 (legacy)497589Yes
Claude Sonnet 4.6 (legacy)497589Yes
Claude Haiku 4.5 (legacy)496588Yes
NotesCounts assume at least one tool; with no tools, none adds 0 tokens. Your tool definitions, tool_use blocks and tool_result blocks are billed as normal input on top.Manual extended thinking (thinking: {type: "enabled"}) rejects any and tool on every model.Where forcing fails, use auto with strict: true tools, or structured outputs.
SourcesTool use overview, PricingDefine tools, Forcing tool useStrict tool use, Structured outputs

The same post that names workflows and agents is direct about what an agent demands: agents suit open-ended problems where the number of steps is hard or impossible to predict, but they require extensive testing in sandboxed environments because higher costs and compounding errors are real. Four disciplines load-bearing for any agent loop you ship:

  • Hard max-iterations. The example above caps at 20. The number matters less than the cap existing; without one, a runaway plan is a runaway bill.
  • Tool inventory is the surface area. Every tool the loop has access to is a thing the model can decide to call. Computer-use tools (lesson 5) deserve sandboxed environments by default; MCP tools (lesson 6) deserve denylist-by-default for destructive operations; custom client tools (lesson 4) get auth and rate limits at the execute_tool boundary, not inside the loop.
  • The lesson 7 levers stay engaged. Cache the system plus tool stack so each iteration does not re-pay the prefix. If the loop runs long, opt in to compaction and cache the system end so it survives. For tool-heavy loops, tool result clearing trims old retrieval payloads. The loop is exactly where the cost-and-staleness frame from lesson 7 stops being theoretical.
  • Stop conditions are first-class. A loop without explicit dispatch on every stop_reason will silently terminate at the wrong moments. The full vocabulary above is what you handle.

The post's call on framework adoption is worth quoting against the urge to reach for an agent SDK on day one: start by using LLM APIs directly: many patterns can be implemented in a few lines of code. The 30-line loop above is the proof; everything in this track has been one HTTP request and one response shape. Frameworks add value when patterns repeat (parallel workers, evaluator-optimizer harnesses), but the same patterns are implementable on the loop above without giving up visibility into what the model is doing. Lesson 9 walks five workflow patterns plus the agent pattern, all of which can be written on this loop.

The mental shift from "I make a request and get an answer" to "the model plans its own path through a tool set" is the single biggest one in this track. The augmented-LLM building block plus the loop above is enough to ship most useful agentic applications. The loop is small (the 30 lines above), the stop-reason vocabulary is finite (the list above), and the discipline carries over from the rest of Track 22 (cache the prefix, sandbox dangerous tools, denylist destructive operations, cap iterations).

The next four lessons specialize this substrate. Lesson 9 catalogs the canonical patterns the loop takes (prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer, and the open-ended agent). Lesson 10 covers Agent Skills and Claude Code (durable instructions and a worked agent harness reading them). Lesson 11 covers Subagents and Claude Managed Agents (spawning a focused loop from inside another). Lesson 12 closes the track with what changes when you take an agent loop from notebook to production.

  • Workflow vs agent (verbatim). A workflow is a system where LLMs and tools are orchestrated through predefined code paths; an agent is a system where LLMs dynamically direct their own processes and tool usage. The standing advice: begin by finding the simplest solution possible, and only increasing complexity when needed. Workflows for predictability; agents for flexibility at scale.
  • The augmented LLM is the building block underneath both: an LLM plus retrieval, tools, and memory. Maximize what a single call can do before adding looping.
  • The canonical loop in 30 lines. Append the assistant turn after each response. On tool_use, dispatch tool blocks and append tool_result entries on a follow-up user turn. On pause_turn, re-call with the assistant turn unchanged. On other stop reasons, surface to the caller. Cap at a max-iterations bound.
  • The full stop_reason vocabulary the loop dispatches on: end_turn, tool_use, pause_turn (lesson 5), max_tokens, stop_sequence, model_context_window_exceeded (lesson 7), the "compaction" value when pause_after_compaction: true, and refusal (a normal response whose stop details name the policy area; retry on a fallback model, because the same model usually refuses again; surface it if no fallback answers).
  • tool_choice for steering. auto (default; model decides per turn), any (must call a tool), tool with a specific name (must call this tool), none (must not call). Not every model accepts the two forcing modes; where they fail, keep auto with strict tools, or use structured outputs. Every request that carries tools pays a fixed tool-use system-prompt overhead, set per model (see the table).
  • Four disciplines around any agent loop. Hard max-iterations cap; tool inventory is the surface area (sandbox dangerous tools, denylist destructive ones, auth at the execute boundary); cache the prefix and consider compaction plus tool result clearing (the lesson 7 levers stay engaged in the loop); explicit dispatch on every stop_reason.
  • Direct API first. Per the source post: start by using LLM APIs directly: many patterns can be implemented in a few lines of code. The 30-line loop above is the proof; reach for a framework only when patterns repeat and you understand the underlying code.
  • Where this fits. Phase 3 opener. Lesson 9 catalogs the canonical patterns this loop takes; lesson 10 covers Agent Skills and Claude Code on top of the loop; lesson 11 covers Subagents and Managed Agents; lesson 12 covers shipping the result.

A single call is the building block. A loop with stop-condition dispatch and max-iterations is the substrate every agentic Claude application sits on. The next lesson is what shape that loop takes for each common job.