Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns

Build the loop that turns Claude's tool calls into an agent: send the messages, read stop_reason, run tools while it says tool_use, stop on end_turn, and see the naive text check quit early and a turn cap catch a stuck loop.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Write an agent loop that lets stop_reason decide when the work is done
  • Let Claude chain several tools on its own, one lap at a time
  • Explain why stopping on any text quits too early
  • Use a turn cap as a safety net, not as the stop rule

Before you start

  • Claude tool use: tool_use and tool_result
  • The Claude Messages API: your first call

A customer asks the shop: Where is my order 1042? The person at the counter doesn't know. They have to look it up first, and only then answer.

Claude is in the same spot. It can't see your orders, so one call to the model can't answer: the fact is simply missing. A small loop fills the gap. And the whole job of that loop comes down to one field on every reply: stop_reason.

The single tool round trip (one tool_use, one tool_result) is covered in Claude tool use. This article is about the loop around it: how many laps it runs, who decides when it ends, and the two ways a loop goes wrong.

The manager decides, the assistant runs the errand

Picture a manager and an assistant with a phone.

  • The manager says: call the warehouse about order 1042. That's a tool use.
  • The assistant writes the answer on a note and hands it back: shipped, arrives Friday. That's the tool result.
  • The manager now has everything and says: tell the customer it arrives Friday. That's end turn.

Notice who never decides when the job is done: the assistant. Claude is the manager. Your code is the assistant with the phone.

One loop, one decision

Keep turning while stop_reason is tool_use, stop on end_turn 1. send messages + tools the whole list, every lap 2. read stop_reason the only field the loop checks 3. tool_use: run the tools append Claude's turn, then tool_result blocks (same ids) go round end_turn: return the text, and stop Turn cap (MAX_TURNS = 5): a safety net if the loop never reaches end_turn
Claude decides whether the work is done. The loop reads stop_reason and keeps turning.

The rule is short: keep turning while stop_reason is tool_use; stop when it is end_turn. On every lap the messages list grows by two entries, Claude's turn and your results. The API remembers nothing between calls, so each request sends the whole list again.

Every turn is a block in the list

After one lap of the order question, the list holds:

  1. A user message with the question.
  2. An assistant message with Claude's tool_use block: an id, the name lookup_order and the input {"order_id": "1042"}.
  3. A user message with a tool_result block whose tool_use_id is the id Claude gave. That's how Claude matches the answer to the question. Results go back as a user turn, never an assistant one.

Then Claude's second reply is plain text with stop_reason set to end_turn.

agent/loop.py

The project is a support agent with two tools, lookup_order and check_return_policy, reading two small JSON files. It runs against a stand-in model (the Anthropic SDK on an httpx mock transport), so no API key is needed; every reply is scripted and starts with "test model reply". With a real key in a .env file, the same loop calls Claude.

"""The agentic loop: send, read stop_reason, run tools, append results, go round."""
from agent.tools import TOOLS, run_tool

MAX_TURNS = 5


def run_agent(client, task):
    messages = [{"role": "user", "content": task}]
    for turn in range(1, MAX_TURNS + 1):
        response = client.messages.create(
            model="claude-sonnet-5-5", max_tokens=1024,
            tools=TOOLS, messages=messages)
        if response.stop_reason == "end_turn":
            print(f"  turn {turn}: end_turn")
            return "".join(b.text for b in response.content if b.type == "text")
        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type == "tool_use":
                print(f"  turn {turn}: tool_use -> {block.name}")
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": run_tool(block.name, block.input)})
        messages.append({"role": "user", "content": results})
    return f"stopped by the safety cap after {MAX_TURNS} turns"
  • The for line is the turn cap. It's only a safety net.
  • Each lap sends the messages list and the tools.
  • The one check that matters: if stop_reason is end_turn, Claude is done and the loop returns its text.
  • If not, Claude's turn is kept in the list exactly as it was sent.
  • Each tool_use block is run, and its tool_result copies the block's id. All results go back together in one user message.

Claude picks the next tool

python main.py loop asks two questions:

agent loop: one tool
  turn 1: tool_use -> lookup_order
  turn 2: end_turn
  answer: test model reply: your wireless headphones arrive Friday.
agent loop: two tools
  turn 1: tool_use -> lookup_order
  turn 2: tool_use -> check_return_policy
  turn 3: end_turn
  answer: test model reply: arrives Friday, and returns are open for 30 days.

The replies are scripted by the stand-in. The first question takes two laps. The second, Where is my order 1042, and can I return it?, takes three: Claude asks for lookup_order, then, by itself, for check_return_policy, then ends the turn. Nobody told the loop to call the second tool. The loop didn't change; only the list got longer.

The tempting way to stop, and why it breaks

Here is a loop that looks reasonable. It stops as soon as the reply contains any text:

"""The tempting loop that stops when the reply contains any text. Do not copy it."""
from agent.tools import TOOLS, run_tool


def run_naive(client, task):
    messages = [{"role": "user", "content": task}]
    turn = 0
    while True:
        turn += 1
        response = client.messages.create(
            model="claude-sonnet-5-5", max_tokens=1024,
            tools=TOOLS, messages=messages)
        text = "".join(b.text for b in response.content if b.type == "text")
        if text:
            print(f"  turn {turn}: text found, loop stops")
            return text
        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type == "tool_use":
                print(f"  turn {turn}: tool_use -> {block.name}")
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": run_tool(block.name, block.input)})
        messages.append({"role": "user", "content": results})

The bug is if text:. Claude often writes a sentence and asks for a tool in the same reply. This loop sees the sentence and leaves before the tool runs. It also has no cap at all.

python main.py traps runs both traps:

naive loop: one tool
  turn 1: tool_use -> lookup_order
  turn 2: text found, loop stops
  answer: test model reply: your wireless headphones arrive Friday.
naive loop: two tools
  turn 1: text found, loop stops
  answer: test model reply: let me check that order.
agent loop: order 9999
  turn 1: tool_use -> lookup_order
  turn 2: tool_use -> lookup_order
  turn 3: tool_use -> lookup_order
  turn 4: tool_use -> lookup_order
  turn 5: tool_use -> lookup_order
  answer: stopped by the safety cap after 5 turns
  • Quit early. With one tool the naive loop happens to work, only because the text came last. With two tools, the first reply has text and a tool_use. The loop quits, the customer gets "let me check that order", and the tool never ran.
  • Never quit. A stuck task (keep checking order 9999 until it shows up) asks for the same lookup again and again. The real loop stops after five turns because of the cap.

The cap is a safety net. The stop rule is stop_reason.

Text and tool_use in the same reply One reply, turn 1 text: "let me check that order." tool_use: lookup_order stop_reason: tool_use naive: "text found", stop the tool never runs stop_reason loop: run the tool and go round
Text in a reply doesn't mean the work is done. stop_reason does.

Common mistakes

  • Stopping when the text "sounds done". Text and tool_use can arrive together. Read stop_reason.
  • Stopping after a fixed number of turns. That's the cap's job as a safety net, not the stop rule. A fixed count either cuts off real work or wastes calls.
  • Always running the same tools in the same order. That takes the choice away from Claude; at that point you've built a workflow (see workflow or agent).
  • Dropping Claude's turn. Append the assistant content unchanged before the results, or the tool_result has no tool_use to answer.
  • Forgetting the id. Every tool_result carries the tool_use_id from Claude's block.
  • Treating every other stop reason as "continue". This loop returns only on end_turn, so any other value (for example max_tokens) would go round again with no tool to run. Many loops write the test the other way, if response.stop_reason != "tool_use": return, which leaves on anything that isn't a tool request. Pick one and handle the other values on purpose.

Quick recap

stop_reason / situationWhat the loop does
tool_useAppend Claude's turn, run each tool, append the tool_result blocks (same ids) as one user message, go round
end_turnReturn the text and stop
Text plus tool_use in one replyStill a tool turn: run the tool
Never reaches end_turnThe turn cap stops it (here, 5 turns)

When your loop also needs approval rules, unknown-tool handling and error results, see custom agent loops and harnesses.

Try it yourself

Add a third tool, track_parcel, and a question that needs all three: Where is order 1042, has the courier picked it up, and can I return it? Predict the number of laps and the tool_use lines the loop will print. The stand-in only knows the scripted questions, so run this one with a real key in .env, or add a script for it to the stand-in. Then lower MAX_TURNS to 2 and check what the customer gets back.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 27 of 66

Previous
Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
Next post
The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • The manager decides, the assistant runs the errand
  • One loop, one decision
  • Every turn is a block in the list
  • agent/loop.py
  • Claude picks the next tool
  • The tempting way to stop, and why it breaks
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.