How to build a Claude API agent loop with a turn limit

Day 7, 30 minutes · beginner

Goal of this lessonBuild a small customer helper that loops until Claude stops asking for tools, with a turn limit, a system prompt and error handling.

Why it matters

Every script so far stopped after one or two rounds. Real questions need more: check the stock, then the price of what is in stock, then the hours for pickup. You cannot know in advance how many rounds Claude needs. What you can do is keep going until Claude is done, and stop it if it never is.

Today you put the course together in one small helper for Margriet. It answers customer questions in a chat in the terminal, calls as many tools as each question needs, sends failures back as errors, and gives up cleanly after a fixed number of turns. That loop is the core of every agent built on the Claude API. At the end you have a working helper, and you have seen the SDK's tool runner, which writes the same loop for you.

The agent loop

An agent here simply means a program that lets Claude call tools in a loop until a task is done. The docs give the shape: while stop_reason is tool_use, run the tools and continue the conversation. In words:

  1. Send the conversation with your tools.
  2. Add Claude's response to the conversation, unchanged.
  3. If stop_reason is not tool_use, stop: this is the answer, or a reason to look closer.
  4. Otherwise run every tool call, add all results in one user message, and go back to step 1.

Keep one growing messages list for the whole chat. Each request then carries everything said so far, so a follow-up such as "and what does it cost?" still knows which plant the customer meant. The price is that every round sends more input tokens.

Always set a turn limit

A plain while loop runs as long as Claude asks for tools. Usually that is two or three rounds. But a tool that keeps failing, or a confusing question, can keep it going, and every round costs tokens. Today's helper uses MAX_TURNS = 8 and stops with a clear message when it is reached. The docs advise the same for retries after an error, and for continuing a paused server tool turn.

Read the stop reason at the end

When the loop ends, stop_reason tells you why:

stop_reason What it means
end_turn Claude finished. Use the answer.
max_tokens the answer hit your max_tokens and is cut off. Raise it or continue.
refusal Claude declined to answer.
pause_turn a server tool loop paused. Send the response back to continue (lesson 6).
stop_sequence one of your stop sequences was reached.

The helper prints a short note for anything that is not end_turn, so a cut-off answer never looks like a finished one.

A system prompt for the helper

The system prompt sets the rules for the whole chat. Margriet's says what the shop is, that stock, prices and hours must come from the tools and never be guessed, and how long an answer may be. Rules about how to behave go there, not inside tool results: the docs warn that Claude treats instructions inside tool results as possibly untrusted.

The tool runner: the same loop, written for you

The SDKs have a tool runner that runs this loop for you: it calls your tools, formats the results, keeps the conversation and stops when Claude is done. In Python you write each tool as a normal function with the @beta_tool decorator, and the SDK builds the schema from the function's type hints and docstring (the text under the def line). max_iterations sets the turn limit. If a tool raises an exception, the runner sends it to Claude as an error result, as your own loop does. In Node the same helper is client.beta.messages.toolRunner().

Two things to know. The tool runner is a beta feature, so its details can still change. And the docs say to write the loop yourself when you need control over each step, for example when a person has to approve a tool call first. Now that you have written it by hand, you know what the runner does for you.

The steps

  1. Create copperleaf_agent.py in two parts: the settings and the answer loop, then the chat around it.
  2. Chat with the helper as a customer would, with follow-up questions.
  3. Optional for Node: the same agent with two tools in two small files.
  4. Optional: the same job with the tool runner, in a few lines.

Follow the steps below.

Deeper dive

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. In your copperleaf-tools folder, create copperleaf_agent.py with this first part: the settings, the system prompt and the answer function with the agent loop and its turn limit.
    from dotenv import load_dotenv
    import anthropic
    from shop import make_tool_results
    from tools import TOOLS
    
    load_dotenv()
    client = anthropic.Anthropic()
    MODEL = "claude-opus-5-5"
    MAX_TURNS = 8
    SYSTEM = (
        "You answer customer questions for Copperleaf Plants, a small plant shop run by Margriet. "
        "Use the tools for stock, prices and opening hours and never guess them. "
        "Answer in at most four friendly sentences."
    )
    
    
    def answer(messages):
        """Run the agent loop until Claude stops asking for tools, or the limit is hit."""
        for turn in range(1, MAX_TURNS + 1):
            response = client.messages.create(
                model=MODEL, max_tokens=2048, system=SYSTEM, tools=TOOLS, messages=messages
            )
            messages.append({"role": "assistant", "content": response.content})
            if response.stop_reason != "tool_use":
                if response.stop_reason != "end_turn":
                    print(f"(stopped early: {response.stop_reason})")
                return "".join(b.text for b in response.content if b.type == "text")
            print(f"turn {turn}:")
            messages.append({"role": "user", "content": make_tool_results(response.content)})
        raise RuntimeError(f"No final answer after {MAX_TURNS} turns.")
  2. Add this second part to the end of the file: the chat. It keeps one conversation for all questions and stops cleanly on an API error or at the turn limit.
    messages = []
    while True:
        question = input("\nCustomer (empty line to stop): ").strip()
        if not question:
            break
        messages.append({"role": "user", "content": question})
        try:
            print("Copperleaf:", answer(messages))
        except anthropic.APIStatusError as e:
            raise SystemExit(f"API error {e.status_code}: {e}")
        except anthropic.APIConnectionError:
            raise SystemExit("No connection to the API.")
        except RuntimeError as e:
            raise SystemExit(str(e))
  3. With the virtual environment on, run python copperleaf_agent.py. Ask: I want two pothos and a peace lily. Are they in stock, what do they cost together, and can I pick them up on Saturday? Watch the turns and tool calls.
  4. Ask a follow-up such as And on Monday?, then one about a plant Margriet does not sell. Press Enter on an empty line to stop. Copy the chat into agent-chat.txt.
  5. For Node instead of Python: in your Node folder, save this as shop.mjs. It holds two of Margriet's tools and the code that runs them.
    const STOCK = { monstera: 4, pothos: 12, "snake plant": 0, "peace lily": 7 };
    const PRICES = { monstera: 24.5, pothos: 9.95, "snake plant": 18, "peace lily": 14.75 };
    
    function knownPlant(input) {
      const name = String(input.plant ?? "").trim().toLowerCase();
      if (!(name in STOCK)) {
        throw new Error(`Unknown plant '${input.plant}'. Copperleaf sells: ${Object.keys(STOCK).join(", ")}.`);
      }
      return name;
    }
    
    const FUNCTIONS = {
      check_stock: (input) => `${STOCK[knownPlant(input)]} x ${knownPlant(input)} in stock today`,
      get_price: (input) => `${knownPlant(input)}: EUR ${PRICES[knownPlant(input)].toFixed(2)} each`
    };
    
    const plantSchema = {
      type: "object",
      properties: { plant: { type: "string", description: "One plant name in lower case, for example monstera." } },
      required: ["plant"]
    };
    
    export const tools = [
      {
        name: "check_stock",
        description: "Check how many plants of one kind Copperleaf Plants has in stock today. Use it when a customer asks if a plant is available. It returns a count, not a price.",
        input_schema: plantSchema
      },
      {
        name: "get_price",
        description: "Look up the price in euros of one plant at Copperleaf Plants. Use it when a customer asks what a plant costs. It returns a price, not the stock.",
        input_schema: plantSchema
      }
    ];
    
    export function runTool(name, input) {
      if (!FUNCTIONS[name]) throw new Error(`Unknown tool '${name}'.`);
      return FUNCTIONS[name](input);
    }
  6. Then save this as copperleaf_agent.mjs and run node --env-file=.env copperleaf_agent.mjs. It answers one question with the same loop and turn limit.
    import Anthropic from "@anthropic-ai/sdk";
    import { tools, runTool } from "./shop.mjs";
    
    const client = new Anthropic();
    const MAX_TURNS = 8;
    const question = process.argv.slice(2).join(" ") || "Are monstera and pothos in stock, and what do they cost?";
    const messages = [{ role: "user", content: question }];
    
    for (let turn = 1; turn <= MAX_TURNS; turn++) {
      const response = await client.messages.create({
        model: "claude-opus-5-5",
        max_tokens: 2048,
        tools,
        messages
      });
      messages.push({ role: "assistant", content: response.content });
      if (response.stop_reason !== "tool_use") {
        console.log("stop_reason:", response.stop_reason);
        console.log(response.content.filter((b) => b.type === "text").map((b) => b.text).join(""));
        process.exit(0);
      }
      const results = [];
      for (const block of response.content) {
        if (block.type !== "tool_use") continue;
        const result = { type: "tool_result", tool_use_id: block.id };
        try {
          result.content = runTool(block.name, block.input);
        } catch (err) {
          result.content = `Error: ${err.message}`;
          result.is_error = true;
        }
        console.log(`  ${block.name}(${JSON.stringify(block.input)}) -> ${result.content}`);
        results.push(result);
      }
      messages.push({ role: "user", content: results });
    }
    console.log(`No final answer after ${MAX_TURNS} turns.`);
  7. Optional, the tool runner (a beta feature of the SDK): create copperleaf_runner.py with this code and run it. The SDK builds the schemas from the functions and runs the loop for you.
    from dotenv import load_dotenv
    import anthropic
    from anthropic import beta_tool
    import shop
    
    load_dotenv()
    client = anthropic.Anthropic()
    
    
    @beta_tool
    def check_stock(plant: str) -> str:
        """Check how many plants of one kind Copperleaf Plants has in stock today.
    
        Args:
            plant: The common name of one plant in lower case, for example monstera.
        """
        return shop.check_stock(plant)
    
    
    @beta_tool
    def get_price(plant: str) -> str:
        """Look up the shop price in euros of one plant at Copperleaf Plants.
    
        Args:
            plant: The common name of one plant in lower case, for example pothos.
        """
        return shop.get_price(plant)
    
    
    runner = client.beta.messages.tool_runner(
        model="claude-opus-5-5",
        max_tokens=2048,
        max_iterations=8,
        tools=[check_stock, get_price],
        messages=[{"role": "user", "content": "Are monstera and pothos in stock, and what do they cost?"}],
    )
    final_message = runner.until_done()
    for block in final_message.content:
        if block.type == "text":
            print(block.text)

Note: Every question sends the whole chat again, so later questions cost more input tokens. Set a monthly spend limit in the Console if you have not done so in the beginners course.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Build a tool-using agent (opens in a new tab)

Create a free account to save your progress. Sign in or sign up