Skip to content

Agent loop: how AI agents run, and the guards they need

An agent loop calls a model, runs the tools it asks for, and repeats. How one run works, where ReAct fits, and the budgets and gates a production loop needs.

Published
Reading time
14 min read

In short

  • An agent loop sends the conversation to a model, runs the tool calls it returns, appends the results, and repeats until the model answers in text or a guard stops the run.
  • The loop itself is about twenty lines. The production work is in the guards around it: step and token budgets, an approval gate for writes, compaction, and idempotent tools.
  • Every step resends the whole history, so cost grows faster than the step count. Anthropic reports that agents use about 4 times the tokens of a chat, and multi-agent systems about 15 times.
  • A run that hits a budget should end with a status, not a crash, and a retried or resumed step should never run the same write twice.

An agent loop is the control flow that turns a model into an agent. It sends the conversation and the tool definitions to the model, runs any tool calls the model returns, appends the results, and calls the model again. The loop ends when the model replies with text and no tool calls, or when a guard you wrote stops it. Anthropic's definition is plain: agents are "typically just LLMs using tools based on environmental feedback in a loop."

Tool calling covers a single pass. This article covers the loop as a system: where it came from, what one run looks like, and the guards that make it end on time, stay inside a budget, and never repeat a write.

What an agent loop is

An agent loop repeats one cycle: call the model with the full history, read its reply, run the tools it asked for, append the results, and go again. The model decides the next step each time. Your code decides whether that step is allowed, and when the run is over.

The Claude Agent SDK, which runs the same loop as Claude Code, describes five stages: receive the prompt, evaluate and respond, execute tools, repeat, and return the result. The OpenAI Agents SDK describes its runner the same way. It calls the model, and then one of three things happens. A final output with no tool calls ends the loop. A handoff switches to another agent and loops again. Tool calls are executed, their results appended, and the loop runs again.

Two properties follow from that shape, and most production problems trace back to them:

  • The state is the message history. The model provider keeps nothing between calls, so every step sends everything that came before it.
  • The model controls the number of steps. Nothing in the loop itself guarantees that it ends.

ReAct: where the agent loop came from

The agent loop descends from ReAct, a 2022 paper by Shunyu Yao and colleagues. ReAct prompted a model to alternate between reasoning traces and actions, then fed each action's result back as an observation. A ReAct agent writes a thought, takes an action, reads what came back, and repeats until it can answer.

The ReAct paper gave the model three actions against a Wikipedia API: search[entity], lookup[string], and finish[answer]. A thought, in the paper's words, "does not affect the external environment," so only actions produce observations. On the ALFWorld and WebShop benchmarks, ReAct beat imitation and reinforcement learning methods by an absolute success rate of 34% and 10%.

Today's APIs turned the paper's text conventions into structure. The action is a tool call validated against a JSON Schema. The observation is a tool_result or function_call_output item. finish[answer] became a plain text reply with no tool calls. The reasoning step is either visible text before the call or the model's own internal thinking. The control flow is the same one the paper described.

When to use a loop instead of a workflow

Use an agent loop when the number and order of steps depend on what the tools return. Use a fixed workflow when you can write the steps down in advance. Anthropic draws the same line in Building effective agents and warns that autonomy means "higher costs, and the potential for compounding errors."

WorkflowAgent loop
Who picks the next stepYour code, along a predefined pathThe model, after reading each result
Number of model callsKnown in advanceVaries per run
Cost per taskPredictableA distribution with a long tail
Typical failureA step returns a bad resultThe run wanders, repeats, or stops early
How you test itUnit tests per stepEvaluations over whole runs

Many systems called agents are better as workflows. A support flow that always looks up the order, checks the policy, and drafts a reply needs no loop. A coding agent chasing a failing test does, because nobody knows in advance how many files it will read.

One agent run, step by step

A single run makes the costs concrete. Take a support agent with three tools: get_order and search_policy, which read, and issue_refund, which writes. The task is "Order A-10422 arrived damaged. Refund it if the policy allows." The token counts below are illustrative.

StepWhat the model returnsWhat the loop doesInput tokens sent
1Two tool calls: get_order and search_policyRuns both reads in parallel and appends both results3,100
2One tool call: issue_refund for the order totalPauses at the approval gate, then runs the refund with an idempotency key4,900
3Text: the refund is issued, with its IDEnds the run with status done5,300

The final context holds 5,300 tokens, and the run was billed for 13,300 input tokens, because each step resent the whole history. A twenty-step run has the same shape over a longer distance. Prompt caching cuts the price of the repeated prefix, and it does not reduce the count.

Step 1 also shows the ordering rule that most loops adopt. The Claude Agent SDK runs read-only tools concurrently and runs tools that modify state, such as Edit, Write, and Bash, one at a time. Custom tools run sequentially unless you mark them read-only. Parallel reads save wall-clock time. Parallel writes are how an agent creates two tickets for one problem.

A minimal agent loop with its guards

A working loop fits on one screen. This one uses the Claude Messages API in Python and includes the guards this article argues for: a step cap, a token budget, an approval gate for writes, an idempotency key per tool call, errors returned to the model, and a compaction hook.

agent_loop.py
import json
import anthropic
 
client = anthropic.Anthropic()
 
MAX_STEPS = 12               # model calls per run
MAX_INPUT_TOKENS = 250_000   # summed across every call in the run
COMPACT_AT = 60_000          # compact when one call's context passes this
WRITE_TOOLS = {"issue_refund"}
 
def run_agent(task, run_id, tools, execute, approve, compact):
    messages = [{"role": "user", "content": task}]
    spent = 0
    for step in range(MAX_STEPS):
        response = client.messages.create(
            model="claude-sonnet-5-5", max_tokens=2048, tools=tools, messages=messages,
        )
        u = response.usage
        # input_tokens excludes cached tokens, so add them to see the whole window.
        window = u.input_tokens + (u.cache_read_input_tokens or 0) + (u.cache_creation_input_tokens or 0)
        spent += window
        messages.append({"role": "assistant", "content": response.content})
 
        if response.stop_reason == "end_turn":
            return {"status": "done", "steps": step + 1, "messages": messages}
        if response.stop_reason != "tool_use":   # max_tokens, refusal, and others
            return {"status": response.stop_reason, "steps": step + 1, "messages": messages}
        if spent > MAX_INPUT_TOKENS:
            return {"status": "over_budget", "steps": step + 1, "messages": messages}
 
        results = []
        for block in (b for b in response.content if b.type == "tool_use"):
            if block.name in WRITE_TOOLS and not approve(block.name, block.input):
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": "A reviewer denied this action. Do not retry it.",
                                "is_error": True})
                continue
            try:
                # Same run, same call ID, same key: a retried step cannot run twice.
                output = execute(block.name, block.input, idempotency_key=f"{run_id}:{block.id}")
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": json.dumps(output)})
            except Exception as err:
                results.append({"type": "tool_result", "tool_use_id": block.id,
                                "content": f"{type(err).__name__}: {err}", "is_error": True})
        messages.append({"role": "user", "content": results})
        if window > COMPACT_AT:
            messages = compact(messages)
 
    return {"status": "max_steps", "steps": MAX_STEPS, "messages": messages}

Three details are easy to get wrong. The loop treats only end_turn as success, so a reply cut off at max_tokens is reported instead of mistaken for an answer. The token count adds the cache fields, because Claude's input_tokens covers only the tokens after the last cache breakpoint. And every outcome returns a status, so the caller can tell a finished run from a stopped one.

The tool results follow the Claude API's ordering rules: they arrive in the message immediately after the call, and all of them come before any text. Run the reads in that inner loop concurrently if your tools are safe to parallelize.

TEXT ONLYTOOL CALLSModel callPICKS THE NEXT STEPTaskUSER GOALFinal answerRUN ENDSApproval gateWRITES WAITRun toolsREADS IN PARALLELAppend resultsERRORS INCLUDEDCompactWHEN IT GROWSBudget checkSTEPS · TOKENSREPEATS UNTIL A TEXT ANSWEROR A GUARD STOPS THE RUN
The loop and its guards. A text-only reply ends the run. Every other lap passes an approval gate, appends results and errors, compacts when the history grows, and checks the budget before the next model call.

Stop conditions and budgets

An agent loop needs at least three stop conditions besides the model finishing: a step cap, a token or spend budget, and a wall-clock limit. Anthropic calls stopping conditions "such as a maximum number of iterations" common practice. The SDK defaults differ, so check what yours does before you rely on it.

The SDKs also differ in how a stop surfaces:

GuardClaude Agent SDKOpenAI Agents SDK
Step capmax_turns, no limit by defaultmax_turns, 10 by default; None turns it off
Spend capmax_budget_usd, no limit by defaultNo runner option; enforce it in your code
What a stop looks likeA result with subtype error_max_turns or error_max_budget_usdA MaxTurnsExceeded exception, or a controlled output through error_handlers
Tool approvalPermission modes, canUseTool, and PreToolUse hooksneeds_approval on a tool, which pauses the run

Spend caps overshoot. The Claude Agent SDK checks spend after each model response arrives, so the response that crosses the cap still completes, and spend can pass the cap by up to the cost of one response plus any sub-agents still running. Leave headroom.

Set caps from data. Measure steps and tokens per successful run, put the hard stop well above the 99th percentile, and alert on the share of runs that reach it. A cap at the median kills legitimate long tasks. No cap at all turns one confused run into the largest line on the invoice.

Context growth, compaction, and sub-agents

The context window does not reset between steps. Every tool call and every result is appended, and a single large file read or verbose command can add thousands of tokens. Long runs need a way to shrink the history, either by summarizing it or by moving work into a separate window.

Compaction summarizes older history and keeps the recent exchanges. The Claude Agent SDK does this automatically as the window approaches its limit, and its docs state the cost plainly: "specific instructions from early in the conversation may not be preserved." The fix is to keep standing rules in content that is re-sent on every request, such as the system prompt, rather than in the first user message. Compact at a threshold well below the window, because quality drops long before the limit, as the context rot article explains.

Sub-agents move work out of the main window entirely. A sub-agent gets its own context, does a bounded task such as searching a codebase, and returns only its final answer. Anthropic's multi-agent research system uses this to cover more ground in parallel, and reports the price: agents use about 4 times the tokens of a chat interaction, and multi-agent systems about 15 times.

Use a sub-agent when a task would flood the main context with material it does not need to keep, not for every step. Trimming tool results and loading context just in time, covered in context engineering, are cheaper first moves.

Approval gates for consequential tools

An approval gate pauses the loop before a tool that writes, sends, pays, or deletes, and waits for a person or a policy to allow it. Reads run unattended. The gate is keyed on the tool, not on the model's stated reason, because the reason can come from text an attacker wrote.

That is the risk a loop adds to plain tool calling. Content from a web page, an email, or another tool's output enters the history, and the model may act on instructions hidden in it. Prompt injection describes the attack; the gate stops it from becoming an action.

Both SDKs build the gate into the loop. In the OpenAI Agents SDK, a tool with needs_approval pauses the run and lists the pending call as an interruption. You approve or reject it on a RunState, which can be serialized to a database and resumed later.

In the Claude Agent SDK, permission modes and the canUseTool callback decide each call, and a PreToolUse hook can block one outright. A denied call comes back to the model as a rejection message in the tool result, so the model can try another approach or report that it could not proceed.

The cost is latency and attention. A gate that fires on every step trains reviewers to click approve. Gate the few tools whose effects you cannot undo, and let everything else run.

Retries, idempotency, and resuming a run

Retry model calls freely and tool calls carefully. A failed model call has no side effects, so the loop or a gateway can resend it. A tool call that timed out may have run anyway, so resending it can charge a card twice. Make write tools idempotent, and a retry becomes safe.

An idempotency key is how payment APIs solve this. Stripe's v1 API saves the status code and body of the first request made with a given key, and returns that saved response to any retry with the same key. In an agent loop, build the key from the run ID and the tool call ID, as the code above does. The same call in the same run then maps to the same key, whether it is a network retry or a resumed run replaying its last step.

Resuming matters because long runs fail partway through. Anthropic's research team found that "Agents are stateful and errors compound," and built their system to resume from where the agent was when an error occurred instead of restarting. Persist the message history after every step, along with each tool result keyed by its call ID. A resumed run can then skip calls that already completed instead of running them again.

Loop failure modes and the guard for each

Most loop incidents follow a few patterns, and each has a guard you can write before the incident. The symptoms rarely show on a single request. They show up when you look at the whole run, which is why every guard below counts or limits something per run.

Failure modeSymptomGuard that stops it
Endless loopThe same tool, with the same arguments, called again and againStep cap, plus a repeat counter on tool name and argument hash
Runaway costInput tokens rise at every stepToken or spend budget per run, checked before each model call
Lost instructionsLate steps ignore rules given at the startStanding rules in the system prompt; compaction below the window limit
Duplicate writeA retried or resumed step creates a second refund or ticketIdempotency key from run ID plus tool call ID
Injected actionA write runs because fetched content asked for itApproval gate keyed on the tool, not the model's reason
Silent tool failureA tool fails, returns normal-looking text, and the model carries onErrors returned with is_error, written to say what went wrong and what to try next
Truncated stepThe reply stops at max_tokens and is read as an answerTreat any stop reason other than tool_use or end_turn as a stop with a status
Hung toolA tool never returns and the run stallsA timeout per tool call that returns an error result to the loop

Each guard lives in code the model cannot change, and each turns a silent failure into a recorded status. Agent observability covers how to count them per run.

Where the agent loop runs

The loop can run in your own code, inside an agent SDK, or in a gateway between your application and the model. The choice decides who holds the run's state, where the approval gate sits, and how much of the loop you can change.

Where the loop runsWho holds the stateApprovalFits
Your own codeYou: the message list, persisted where you chooseYour gate, your rulesProducts that need custom guards and storage
An agent SDKThe SDK's session or run stateBuilt-in permission modes or approval flagsCoding agents and general agents that want budgets and compaction included
A gatewayThe gateway, within one requestAn auto-execute list; other calls go back to the applicationChains of read-only tools that sit next to the model

Bifrost, an open-source AI gateway by Maxim AI, shows the gateway version. By default it returns tool calls to your application instead of running them. Its Agent Mode runs only the tools on an auto-execute list, up to a configurable depth of 10 iterations by default, and hands any other tool call back to the application.

That split is the right one wherever the loop lives: let infrastructure loop over reads, and keep writes where a person or your own code decides. The MCP gateway article covers the tool side of that setup.

Frequently asked questions

What is an agent loop?

An agent loop is the cycle that lets a model complete multi-step tasks. Your code sends the conversation and tool definitions to the model, runs any tool calls it returns, appends the results to the history, and calls the model again. The loop ends when the model replies with text and no tool calls, or when a guard such as a step cap or budget stops the run.

What is a ReAct agent?

A ReAct agent alternates reasoning and acting. It writes a thought about what to do, takes an action such as a search, reads the observation that comes back, and repeats until it can answer. The pattern comes from the 2022 ReAct paper by Yao and colleagues. Modern tool-calling APIs implement the same cycle with structured tool calls instead of text conventions.

How do you stop an AI agent from looping forever?

Give every run a step cap, a token or spend budget, and a wall-clock limit, all enforced in code outside the model. Add a counter that flags the same tool called with the same arguments several times. When a guard fires, end the run with a clear status such as max_steps or over_budget, and alert when the share of stopped runs rises.

What is the difference between an AI agent and a workflow?

In a workflow, your code fixes the steps and their order in advance, and the model fills in each step. In an agent, the model chooses the next step after reading each tool result, so the number of steps varies per run. Workflows are cheaper and easier to test. Agents handle tasks whose path you cannot predict, at higher and less predictable cost.

How many steps should an agent loop allow?

There is no universal number. Measure how many steps successful runs take for each agent, then set the hard cap well above the 99th percentile so legitimate long tasks finish. A cap at the median stops real work. SDK defaults are not a substitute: the Claude Agent SDK sets no turn limit, and the OpenAI Agents SDK stops at 10 turns.

How does a coding agent's loop work?

A coding agent runs the same loop with tools for reading files, searching, editing, and running commands. Anthropic describes Claude Code's cycle as gather context, take action, verify work, and repeat. A typical run calls the test suite, reads the failing files, edits one, and runs the tests again, then answers in text once they pass. The tests are what tell the loop it is done.

Sources

  1. 01ReAct: Synergizing Reasoning and Acting in Language ModelsarXiv:2210.03629
  2. 02Building effective agentsAnthropic
  3. 03How the agent loop worksClaude Agent SDK docs
  4. 04Building agents with the Claude Agent SDKClaude blog
  5. 05How we built our multi-agent research systemAnthropic
  6. 06Running agentsOpenAI Agents SDK docs
  7. 07Human-in-the-loopOpenAI Agents SDK docs
  8. 08Handle tool callsClaude API docs
  9. 09Prompt cachingClaude API docs
  10. 10Idempotent requestsStripe API docs
  11. 11Agent ModeBifrost docs
  12. 12BifrostGitHub