cd /news/ai-agents/how-to-stop-an-ai-agent-from-looping… · home › topics › ai-agents › article
[ARTICLE · art-179129] src=zyvop.com ↗ pub= topic=ai-agents verified=true sentiment=· neutral

How to Stop an AI Agent From Looping Forever (and Burning Your API Budget)

A dependency-free Python RunGuard class that caps agent runs on four axes — 20 steps, 200,000 total tokens, 120 seconds, and 3 repeats of the same tool call within a 10-call window — is presented as a way to stop runaway agent loops, because a loop that grows from 10 to 100 steps costs roughly 83 times the input tokens (74,000 versus 6,140,000 in the illustrative example). The guard is needed because framework defaults differ: LangGraph's recursion_limit defaults to 25 super-steps, the OpenAI Agents SDK raises MaxTurnsExceeded at a default max_turns, and the Claude Agent SDK's max_turns and max_budget_usd are both off unless set. No single limit covers every failure, so the guard trips when any one of the four is crossed.

recommendation

Set max_turns, max_budget_usd and a wall-clock limit explicitly on every agent run — Claude Agent SDK leaves both caps off by default — and add a repeat detector for identical tool calls.

more in playbook: Controlling LLM cost
by read8 min views25 publishedDec 1, 2026
How to Stop an AI Agent From Looping Forever (and Burning Your API Budget)
Image: Zyvop (auto-discovered)

An agent is a loop with a language model inside it: call the model, run the tool it asks for, feed the result back, repeat. The loop is what makes agents useful. It also means that when something goes wrong, nothing in the design says stop.

The cost of that loop grows faster than the number of steps. Every iteration re-sends the whole conversation so far, so each call is bigger than the last. Say the task and instructions take 2,000 tokens and every tool round-trip adds 1,200 more. The input tokens you pay for add up like this:

Steps Input tokens sent in total
10 74,000
30 582,000
100 6,140,000

Ten times the steps costs about 83 times the input tokens. These numbers are illustrative, and provider-side prompt caching can discount the repeated part of the history, but the volume still climbs the same way.

What your framework already does #

Frameworks handle this differently. Here are three, as documented in November 2026.

Framework Setting At the limit Default
OpenAI Agents SDK max_turns Raises MaxTurnsExceeded A default exists; pass None to disable
LangGraph recursion_limit in the run config Raises GraphRecursionError 25
Claude Agent SDK max_turns ,max_budget_usd Run ends with an error_max_turns orerror_max_budget_usd result Both off unless you set them

In the OpenAI SDK, a turn is one model invocation, including any tool calls that come with it. LangGraph counts super-steps rather than model calls. Its own docs example needs four super-steps per lap of a simple loop, so a graph with several nodes uses up the limit faster than you might expect. Nodes can read the current step from config["metadata"]["langgraph_step"] and wind down before the limit hits. In the Claude Agent SDK, a one-shot query() yields the cap result and then raises, so wrap the loop in a try block.

Look at the Claude Agent SDK row: both caps are off unless you set them. Depending on the framework, doing nothing can mean a default limit or no limit at all, so look up yours.

Even where a cap exists, a step count is a blunt tool. It doesn't know what a step costs, and it won't notice an agent that is making different calls that all go nowhere.

Four limits, four different failures #

Limit Catches Misses
Step cap Any loop that never ends Cheap steps and expensive steps look the same
Token budget Runs that get expensive, however many steps it takes A fast, cheap loop that is still pointless
Time limit A run that drags on, such as many slow calls A single call that never returns, because the clock is only checked between calls; put a timeout on the request or tool itself
Repeat detector The same call over and over, or two calls trading places A loop that keeps changing its arguments

No single limit covers everything. A guard that uses all four stops a run when any one of them trips.

The guard #

This class has no dependencies. Create one per run, and call its three methods at the matching points in your loop.

import json
import time
from collections import Counter, deque
from dataclasses import dataclass, field
from typing import Callable

class GuardTripped(Exception):
    """Raised when an agent run crosses one of its limits."""

    def __init__(self, reason: str):
        super().__init__(reason)
        self.reason = reason

@dataclass
class RunGuard:
    max_steps: int = 20
    max_total_tokens: int = 200_000
    max_seconds: float = 120.0
    repeat_window: int = 10    # how many recent tool calls to remember
    max_repeats: int = 3       # same call this many times within the window trips the guard
    clock: Callable[[], float] = time.monotonic

    steps: int = field(default=0, init=False)
    tokens: int = field(default=0, init=False)
    _started: float = field(default=0.0, init=False)
    _recent: deque = field(default_factory=deque, init=False)

    def __post_init__(self) -> None:
        self._started = self.clock()
        self._recent = deque(maxlen=self.repeat_window)

    def before_model_call(self) -> None:
        """Call right before every model request."""
        if self.steps >= self.max_steps:
            raise GuardTripped(f"step limit reached ({self.max_steps})")
        if self.tokens >= self.max_total_tokens:
            raise GuardTripped(f"token budget used up ({self.tokens:,} of {self.max_total_tokens:,})")
        if self.clock() - self._started >= self.max_seconds:
            raise GuardTripped(f"time limit reached ({self.max_seconds:g}s)")
        self.steps += 1

    def after_model_call(self, input_tokens: int, output_tokens: int) -> None:
        """Call with the usage numbers the provider returns."""
        self.tokens += input_tokens + output_tokens

    def on_tool_call(self, name: str, args: dict) -> None:
        """Call before running each tool the model asked for."""
        key = f"{name}:{json.dumps(args, sort_keys=True, default=str)}"
        self._recent.append(key)
        if Counter(self._recent)[key] >= self.max_repeats:
            raise GuardTripped(f"{name} called with the same arguments {self.max_repeats} times")

The repeat detector keeps a sliding window of recent calls instead of only comparing each call with the previous one, which is how it catches two tools trading places. The clock is injectable so that a test can fast-forward time instead of sleeping.

Wiring it into a loop #

The loop below is provider-agnostic. call_model is whatever function talks to your model, and it needs to return the text, any requested tool calls, and the token counts. The major hosted APIs report token usage with each response, though the field names differ.

from dataclasses import dataclass, field

@dataclass
class ModelReply:
    text: str = ""
    tool_calls: list = field(default_factory=list)  # [(name, args), ...]
    input_tokens: int = 0
    output_tokens: int = 0

def run_agent(task, call_model, tools, guard):
    messages = [{"role": "user", "content": task}]
    try:
        while True:
            guard.before_model_call()
            reply = call_model(messages)
            guard.after_model_call(reply.input_tokens, reply.output_tokens)

            if not reply.tool_calls:
                return {"status": "done", "answer": reply.text, "steps": guard.steps}

            messages.append({"role": "assistant", "content": reply.text,
                             "tool_calls": reply.tool_calls})
            for name, args in reply.tool_calls:
                guard.on_tool_call(name, args)
                try:
                    result = tools[name](**args)
                except Exception as exc:  # unknown tool, bad arguments, or a failing tool
                    result = f"Tool error: {exc!r}"
                messages.append({"role": "tool", "name": name, "content": str(result)})
    except GuardTripped as stop:
        return {"status": "stopped", "reason": stop.reason,
                "steps": guard.steps, "tokens": guard.tokens}

When the guard trips, the function returns a result instead of crashing, so the caller gets the reason and the totals and can decide whether to save partial work or alert someone. Tool errors go back to the model as text rather than ending the run. That is also how a failing tool turns into a retry loop, which is one reason the repeat detector earns its place.

Test it without spending anything #

A fake model is enough to exercise every limit. This one reports a growing prompt, like a real agent, and a script decides what it asks for at each step. Here is what each scenario produced when run:

Scenario Result
Same tool call forever Stopped after 3 steps: search called with the same arguments 3 times
Two tools alternating Stopped after 5 steps, by the repeat detector
New query every step, never finishes Stopped at 15 steps: step limit reached (15)
Same, with a 50,000-token budget Stopped after 8 steps: token budget used up (50,080 of 50,000)
Each clock reading jumps 40 s, 100 s limit Stopped after 2 steps: time limit reached (100s)
Finishes on step 4 Returned done normally

The token row shows a property of this design. The budget is checked between calls, so one large call can push the total past the limit, here by 80 tokens. With a long history a single call can carry far more than that, so set the budget a call or two below what you can afford, and cap the output size on each request.

Add scenarios like these to your test suite, so that a later change to the guard can't quietly break one of the limits.

Starting values #

Treat these as starting points and tune them against what a normal, successful run looks like for your agent.

Setting Starting value How to adjust
max_steps 20 Set it to about twice the steps a typical successful run takes
max_total_tokens 200,000 Work backward from the most you'd pay for one run
max_seconds 120 Match it to the longest a legitimate run should take
repeat_window /max_repeats 10 / 3 Raise max_repeats if the agent polls a status endpoint on purpose

What the guard doesn't cover #

  • Token counts are not dollars. Convert them with your model's current price list, and price input and output separately, since they usually differ.
  • Multi-agent setups need one shared guard. If agent A can ask agent B for help and B can ask A, a separate budget per agent never fills up while the pair keeps going. Create the guard once per run and pass the same object to every agent in it.
  • Legitimate repetition looks like a loop. An agent that polls a job until it finishes will trip the repeat detector. Exempt those tools, or add a changing argument such as an attempt number.
  • When a guard trips, log the reason, the last few tool calls, and the totals. Alerting at a fraction of the budget, such as half, helps you notice a run that is climbing toward its limit before it gets there.
  • Failing tools need retry rules of their own: a cap per tool, a between attempts, and operations that are safe to run twice, so a retry can't repeat a payment or a write.

References #

── more in #ai-agents 4 stories · sorted by recency
── more on @openai agents sdk 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-stop-an-ai-ag…] indexed:0 read:8min 2026-12-01 · —