{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget-cth0l","url":"https://zyvop.com/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget-cth0l","title":"How to Stop an AI Agent From Looping Forever (and Burning Your API Budget)","subtitle":"Four limits that stop a runaway agent, plus a tested Python guard that caps steps, tokens, time, and repeated tool calls before your bill climbs.","tldr":"Every agent step re-sends the whole conversation, so costs grow much faster than the step count. This guide covers four limits that catch different failures, and a tested Python guard you can drop into any agent loop to stop runaway runs.","keywords":["Python","AI agents","guardrails","LLM","cost-control","AI Tools"],"entities":["Alysaa Lissy","Python","AI agents","guardrails","LLM","cost-control","AI Tools","ZyVOP"],"keyTakeaways":["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."],"headings":["What your framework already does","Four limits, four different failures","The guard","Wiring it into a loop","Test it without spending anything","Starting values","What the guard doesn't cover","References"],"outboundLinks":["https://openai.github.io/openai-agents-python/running_agents","https://docs.langchain.com/oss/python/langgraph/errors/GRAPH_RECURSION_LIMIT","https://reference.langchain.com/python/langgraph-sdk/schema/Config/recursion_limit","https://code.claude.com/docs/en/agent-sdk/configuration"],"contentText":"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 or error_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) -&gt; None: self._started = self.clock() self._recent = deque(maxlen=self.repeat_window) def before_model_call(self) -&gt; None: \"\"\"Call right before every model request.\"\"\" if self.steps &gt;= self.max_steps: raise GuardTripped(f\"step limit reached ({self.max_steps})\") if self.tokens &gt;= self.max_total_tokens: raise GuardTripped(f\"token budget used up ({self.tokens:,} of {self.max_total_tokens:,})\") if self.clock() - self._started &gt;= 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) -&gt; None: \"\"\"Call with the usage numbers the provider returns.\"\"\" self.tokens += input_tokens + output_tokens def on_tool_call(self, name: str, args: dict) -&gt; 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] &gt;= 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 pause between attempts, and operations that are safe to run twice, so a retry can't repeat a payment or a write. References OpenAI, Agents SDK: Running agents (max_turns, MaxTurnsExceeded) LangChain, GRAPH_RECURSION_LIMIT and the recursion_limit reference Anthropic, Agent SDK configuration: limit turns and spend","contentHash":"sha256:b336c80f478e2dcbf5ed4ae4e3cbff3f2444376dce643e2ffad9689de10f0212","authorName":"Alysaa Lissy","authorUrl":"https://zyvop.com/author/alysaa","authorSameAs":[],"category":"AI Tools","tags":["Python","AI agents","guardrails","LLM","cost-control"],"audience":"Software engineers and developers building applications with AI Tools","tone":"Instructional, practical, code-first","readingTimeMinutes":6,"wordCount":1507,"faqs":null,"primaryTopic":"AI Tools","publishedAt":"2026-12-01T04:52:04.709Z","updatedAt":"2026-12-01T04:52:04.709Z","canonicalUrl":"https://zyvop.com/how-to-stop-an-ai-agent-from-looping-forever-and-burning-your-api-budget-cth0l"}