{"slug": "how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget", "title": "How to Stop an AI Agent From Looping Forever (and Burning Your API Budget)", "summary": "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.", "body_md": "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.\n\nThe 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:\n\n| Steps | Input tokens sent in total | \n|---|---|\n| 10 | 74,000 | \n| 30 | 582,000 | \n| 100 | 6,140,000 | \n\nTen 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.\n\n## What your framework already does\n\nFrameworks handle this differently. Here are three, as documented in November 2026.\n\n| Framework | Setting | At the limit | Default | \n|---|---|---|---|\n| OpenAI Agents SDK | `max_turns` | Raises `MaxTurnsExceeded` | A default exists; pass `None` to disable | \n| LangGraph | `recursion_limit` in the run config | Raises `GraphRecursionError` | 25 | \n| Claude Agent SDK | `max_turns` ,`max_budget_usd` | Run ends with an `error_max_turns` or`error_max_budget_usd` result | Both off unless you set them | \n\nIn 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.\n\nLook 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.\n\nEven 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.\n\n## Four limits, four different failures\n\n| Limit | Catches | Misses | \n|---|---|---|\n| Step cap | Any loop that never ends | Cheap steps and expensive steps look the same | \n| Token budget | Runs that get expensive, however many steps it takes | A fast, cheap loop that is still pointless | \n| 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 | \n| Repeat detector | The same call over and over, or two calls trading places | A loop that keeps changing its arguments | \n\nNo single limit covers everything. A guard that uses all four stops a run when any one of them trips.\n\n## The guard\n\nThis class has no dependencies. Create one per run, and call its three methods at the matching points in your loop.\n\n``` python\nimport json\nimport time\nfrom collections import Counter, deque\nfrom dataclasses import dataclass, field\nfrom typing import Callable\n\nclass GuardTripped(Exception):\n    \"\"\"Raised when an agent run crosses one of its limits.\"\"\"\n\n    def __init__(self, reason: str):\n        super().__init__(reason)\n        self.reason = reason\n\n@dataclass\nclass RunGuard:\n    max_steps: int = 20\n    max_total_tokens: int = 200_000\n    max_seconds: float = 120.0\n    repeat_window: int = 10    # how many recent tool calls to remember\n    max_repeats: int = 3       # same call this many times within the window trips the guard\n    clock: Callable[[], float] = time.monotonic\n\n    steps: int = field(default=0, init=False)\n    tokens: int = field(default=0, init=False)\n    _started: float = field(default=0.0, init=False)\n    _recent: deque = field(default_factory=deque, init=False)\n\n    def __post_init__(self) -> None:\n        self._started = self.clock()\n        self._recent = deque(maxlen=self.repeat_window)\n\n    def before_model_call(self) -> None:\n        \"\"\"Call right before every model request.\"\"\"\n        if self.steps >= self.max_steps:\n            raise GuardTripped(f\"step limit reached ({self.max_steps})\")\n        if self.tokens >= self.max_total_tokens:\n            raise GuardTripped(f\"token budget used up ({self.tokens:,} of {self.max_total_tokens:,})\")\n        if self.clock() - self._started >= self.max_seconds:\n            raise GuardTripped(f\"time limit reached ({self.max_seconds:g}s)\")\n        self.steps += 1\n\n    def after_model_call(self, input_tokens: int, output_tokens: int) -> None:\n        \"\"\"Call with the usage numbers the provider returns.\"\"\"\n        self.tokens += input_tokens + output_tokens\n\n    def on_tool_call(self, name: str, args: dict) -> None:\n        \"\"\"Call before running each tool the model asked for.\"\"\"\n        key = f\"{name}:{json.dumps(args, sort_keys=True, default=str)}\"\n        self._recent.append(key)\n        if Counter(self._recent)[key] >= self.max_repeats:\n            raise GuardTripped(f\"{name} called with the same arguments {self.max_repeats} times\")\n```\n\nThe 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.\n\n## Wiring it into a loop\n\nThe 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.\n\n``` python\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass ModelReply:\n    text: str = \"\"\n    tool_calls: list = field(default_factory=list)  # [(name, args), ...]\n    input_tokens: int = 0\n    output_tokens: int = 0\n\ndef run_agent(task, call_model, tools, guard):\n    messages = [{\"role\": \"user\", \"content\": task}]\n    try:\n        while True:\n            guard.before_model_call()\n            reply = call_model(messages)\n            guard.after_model_call(reply.input_tokens, reply.output_tokens)\n\n            if not reply.tool_calls:\n                return {\"status\": \"done\", \"answer\": reply.text, \"steps\": guard.steps}\n\n            messages.append({\"role\": \"assistant\", \"content\": reply.text,\n                             \"tool_calls\": reply.tool_calls})\n            for name, args in reply.tool_calls:\n                guard.on_tool_call(name, args)\n                try:\n                    result = tools[name](**args)\n                except Exception as exc:  # unknown tool, bad arguments, or a failing tool\n                    result = f\"Tool error: {exc!r}\"\n                messages.append({\"role\": \"tool\", \"name\": name, \"content\": str(result)})\n    except GuardTripped as stop:\n        return {\"status\": \"stopped\", \"reason\": stop.reason,\n                \"steps\": guard.steps, \"tokens\": guard.tokens}\n```\n\nWhen 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.\n\n## Test it without spending anything\n\nA 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:\n\n| Scenario | Result | \n|---|---|\n| Same tool call forever | Stopped after 3 steps: `search called with the same arguments 3 times` | \n| Two tools alternating | Stopped after 5 steps, by the repeat detector | \n| New query every step, never finishes | Stopped at 15 steps: `step limit reached (15)` | \n| Same, with a 50,000-token budget | Stopped after 8 steps: `token budget used up (50,080 of 50,000)` | \n| Each clock reading jumps 40 s, 100 s limit | Stopped after 2 steps: `time limit reached (100s)` | \n| Finishes on step 4 | Returned `done` normally | \n\nThe 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.\n\nAdd scenarios like these to your test suite, so that a later change to the guard can't quietly break one of the limits.\n\n## Starting values\n\nTreat these as starting points and tune them against what a normal, successful run looks like for your agent.\n\n| Setting | Starting value | How to adjust | \n|---|---|---|\n| `max_steps` | 20 | Set it to about twice the steps a typical successful run takes | \n| `max_total_tokens` | 200,000 | Work backward from the most you'd pay for one run | \n| `max_seconds` | 120 | Match it to the longest a legitimate run should take | \n| `repeat_window` /`max_repeats` | 10 / 3 | Raise `max_repeats` if the agent polls a status endpoint on purpose | \n\n## What the guard doesn't cover\n\n- Token counts are not dollars. Convert them with your model's current price list, and price input and output separately, since they usually differ.\n- 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.\n- 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.\n- 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.\n- Failing tools need retry rules of their own: a cap per tool, a pause between attempts, and operations that are safe to run twice, so a retry can't repeat a payment or a write.\n\n## References\n\n- OpenAI, [Agents SDK: Running agents](https://openai.github.io/openai-agents-python/running_agents) (`max_turns` ,`MaxTurnsExceeded` )\n- LangChain, [GRAPH_RECURSION_LIMIT](https://docs.langchain.com/oss/python/langgraph/errors/GRAPH_RECURSION_LIMIT) and the`recursion_limit` [reference](https://reference.langchain.com/python/langgraph-sdk/schema/Config/recursion_limit)\n- Anthropic, [Agent SDK configuration: limit turns and spend](https://code.claude.com/docs/en/agent-sdk/configuration)", "url": "https://wpnews.pro/news/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget", "canonical_source": "https://zyvop.com/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget-cth0l", "published_at": "2026-12-01 04:52:04+00:00", "updated_at": "2026-12-01 05:14:10.141978+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools"], "entities": ["OpenAI Agents SDK", "LangGraph", "Claude Agent SDK", "RunGuard", "GuardTripped"], "also_reported_by": [], "takeaway": "Combine a step cap, token budget, wall-clock limit and repeat detector in one guard, since a 10-to-100-step loop grows input tokens about 83x (74,000 to 6,140,000) and no single limit catches every failure mode.", "recommendation": {"advice": "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.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget", "markdown": "https://wpnews.pro/news/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget.md", "text": "https://wpnews.pro/news/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget.txt", "jsonld": "https://wpnews.pro/news/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget.jsonld"}}