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. 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. python 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. python 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 https://openai.github.io/openai-agents-python/running agents max turns , MaxTurnsExceeded - 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 - Anthropic, Agent SDK configuration: limit turns and spend https://code.claude.com/docs/en/agent-sdk/configuration