
AI Agent Infinite Loop: Step Limits, Time and Budget Caps
How to stop an AI agent infinite loop with step limits, time and budget caps, repeat detection and a human handoff that keeps a clear log.
Want to apply this in your company?
Book a call with Juan →AI Agent Infinite Loop: Step Limits, Time and Budget Caps
An AI agent stuck in an infinite loop is only truly contained when the limit lives outside the model: a step counter, a clock and a spending cap, all enforced by the code that runs the agent, plus a rule that detects repetition. When any limit is hit, the agent stops, records its state and hands the case to a person instead of trying one more time. Asking the agent in the prompt not to repeat itself helps, but it does not replace the brake.
Key takeaways
- The limit must be enforced by the system that runs the agent, not by the model's good behavior.
- Three caps work together: number of steps, total time and a budget of tokens or paid calls. Whichever is reached first ends the run.
- Repetition is detected by comparing recent actions and results, not just by counting steps.
- Stopping well is part of the design: the agent hands over a summary of what it tried, and the case goes to a person who has context.
- Every stop caused by a limit should be logged, because it is the best signal that a workflow needs adjusting.
Why does an AI agent get stuck in an infinite loop?
In its most common form, an agent works in a cycle: the model decides on an action, a tool runs it, the result goes back to the model, and the model decides again. That cycle ends only when the model judges the work done or when something external interrupts it. If nothing external exists, the ending depends entirely on the model's judgment, and that is where the problem starts.
The most frequent causes are predictable:
- A tool returns an error the model does not understand, and it repeats the same call with small variations.
- The completion criterion is vague, so the agent never considers the task finished.
- The information the agent is looking for does not exist, but it keeps searching instead of admitting that.
- The context grows with every turn and the agent forgets what it already tried (see what a context window is in AI), so it repeats paths it had already ruled out.
- Two parts of the system, for example an agent and an automation, react to each other's output without end.
Anthropic's documentation on building agents describes execution as typically including stopping conditions, such as a maximum number of iterations, precisely to keep control. That is official documentation. The rest of this article combines that foundation with deployment good practice and a few working hypotheses, which we flag where they appear.
Which three caps does every agent need?
A single cap leaves gaps. A step limit does not protect against one slow call that hangs for a long time. A time limit does not protect against fast steps that burn through many tokens. That is why the three work as a set.
Step cap
Set a maximum number of turns in the cycle for each type of task. The right value comes from the real workflow: observe how many steps a healthy run uses and set the cap with reasonable headroom above that, not far above. An agent that answers a simple question does not need the same headroom as one that crosses three systems.
Time cap
Set a total run deadline and also a deadline for each tool call. In WhatsApp support, the total deadline should match the patience of the person waiting for the answer. If the customer is waiting, time is part of the experience, not only an engineering detail.
Budget cap
The cost of a language model follows the tokens it processes (see what tokens are in AI). In a loop, every turn resends context that only grows, so spending rises faster than the step count suggests. Set a maximum budget per run, measured in tokens or paid calls, and a second budget per period (day or month) for the agent as a whole. The second one protects against the case where every run respects its limit, but thousands of runs happen without control.
OWASP, in its list of top risks for LLM applications, treats unbounded consumption as its own risk category. Limiting resources per run and per period is one of the basic defenses.
How do you detect repetition before hitting the cap?
The caps are the safety net. Repetition detection is the alarm that goes off earlier and saves steps, time and money. The idea is simple: the code that runs the agent keeps a short history of recent actions and compares them.
Practical signals to monitor:
- The same tool called with the same arguments more than once in a short sequence.
- The same tool with nearly identical arguments, changing only an irrelevant detail.
- The same error returned repeatedly by the tool.
- Alternation between two actions (A, B, A, B), a typical oscillation pattern.
- Model responses that are very similar from turn to turn, with no new information.
- No progress: the task state (fields filled in, items resolved) does not change after a few turns.
The last one is the most valuable. Text repetition is easy to measure, but what matters is whether the task moved forward. If the workflow has an explicit state, for example data collected from the customer, compare that state between turns. If nothing changes, the agent is spinning.
What should you do when repetition shows up? There is a ladder of responses, from lightest to firmest:
- On the first repetition, inject a system message reminding the agent what it already tried and asking for a different approach.
- On the second, remove or disable the failing tool for that run.
- On the third, stop and hand off.
These attempt counts are a working starting point, a hypothesis to calibrate with your pilot logs, not a universal rule.
How do you stop with a handoff instead of trying again?
Stopping is easy. Stopping well takes design. An agent that simply goes silent or returns a generic error creates rework and frustration. A proper shutdown has four parts.
- An honest message to the person waiting: the agent says it could not finish and that a person will take over, without promising timelines the system does not control.
- A context package for the human: the goal of the task, what has been collected, what was tried, which limit was reached and what the last error was.
- A clear destination: a queue, an owner or a channel defined in advance, taking working hours into account (see after-hours customer service with AI).
- Safe handling of pending actions: nothing half-done can be left in an inconsistent state. If the agent started a registration or a send, the shutdown must complete it, undo it or flag it.
That last point deserves attention. Interrupting in the middle of a sequence of actions with external effects, such as creating an order and not yet sending the confirmation, can leave the system incoherent. Actions with effects should be idempotent or require confirmation, so that repeating or aborting does not duplicate anything. For the logic of validating inputs and outputs, the article on guardrails for AI agents covers this kind of control in detail.
If the agent makes decisions that affect people, the handoff also supports the right to review provided by Brazil's LGPD. The article on LGPD automated decision-making and Article 20 covers that topic.
Step-by-step plan to put the limits in place
A lean plan, in the order that usually works:
- List the agent's workflows and, for each one, describe what done means and what failed means.
- Observe healthy runs and note the steps, time and tokens used. That is your baseline.
- Set the three caps per workflow, with moderate headroom above the baseline.
- Implement the caps in the code that runs the agent, never only in the prompt.
- Add repetition detection with the response ladder described above.
- Define the handoff destination and the format of the context package.
- Create a per-period budget for the whole agent, with an alert before the cutoff.
- Test on purpose: simulate a tool that always fails, a search with no results and an ambiguous question, and confirm that the agent stops and hands off.
- Review limit-triggered stops every week at the start, and less often afterward.
Illustrative scenario
Imagine a services company that uses a WhatsApp agent to check the status of an order. The internal system goes down for a few minutes and the lookup tool starts returning errors. Without limits, the agent would retry the lookup nonstop, consuming tokens on every turn while the customer waits. With limits, the second identical failing call triggers the repetition warning. The third failure disables the tool for that conversation. The agent then tells the customer it could not check right now and that a support agent will follow up, and it opens a ticket with the order number, the error received and the time. Cost stayed contained, and the person who took over did not have to ask everything again. This is an illustrative example, not a client result.
What should you log to spot loops before they get expensive?
Without logs, a loop only shows up on the bill or in a complaint. Every run should leave a structured trace: run identifier, workflow, number of steps, total time, tokens consumed, tools called, reason for ending (completed, step limit, time limit, budget limit, repetition, error) and whether a handoff happened.
With that in place, a few questions become answerable:
- Which workflow ends most often because of a limit? Probably the completion criterion or a tool needs review.
- Which tool most often appears before a repetition? Maybe its description or its error message is confusing. Anthropic has a useful guide on writing better tools for agents.
- Is the average cost per run stable or rising?
Logs can also follow observability conventions. OpenTelemetry maintains semantic conventions for generative AI, which helps standardize token usage and model call fields across systems. Be careful with personal data in logs: record what you need to audit, mask the rest and set a retention period, in line with LGPD.
A note on method: stops caused by limits are not failures to hide. They are the most honest data about where the agent is not yet reliable. If the team is pushed to reduce that number, the risk is loosening the caps so the metric looks good. To avoid that distortion, read about how to measure an AI automation pilot.
How does this control fit into the way we work?
In the method we follow, loop limits show up at every stage. In mapping, we describe the current process and measure the baseline of steps, time and human effort, because without it the cap would be a guess. In limiting, we define accessible data, permitted actions and the three caps, along with the handoff criterion. In piloting, we run a real workflow with a decision log and an agreed success metric, and we use limit-triggered stops to calibrate. In handing over, we deliver the operation with the log dashboard and a clear rule for when to expand, adjust or stop.
When the agent serves customers on WhatsApp, the handoff design must respect the rules of the channel and of human support; the guide on how to integrate AI into your company's WhatsApp covers that foundation.
Frequently asked questions
How high should the step limit be? There is no universal number. Measure healthy runs of your workflow and set the cap with moderate headroom above them. Then adjust based on the limit-triggered stops that appear during the pilot.
Can I put the limit only in the prompt? That is not enough. The model can ignore, forget or misread an instruction to stop, and a prompt does not prevent a hung call or growing cost. The reliable limit is the one the execution code enforces, with the prompt only reinforcing the desired behavior.
What should happen when the agent hits the limit in the middle of an action with external effects? Before anything else, the system should leave the state consistent: complete the action, undo it or clearly mark it as pending for the human. Designing actions to be idempotent, or to require confirmation, lowers the risk of duplicated orders, messages or registrations.
How do you keep the handoff from becoming a bottleneck? Hand off only what the agent truly cannot resolve, and send the full context package so the person does not start from zero. Track the volume of handoffs per workflow. If one workflow hands off too much, the fix usually lies in the tools, the completion criterion or the agent's scope, not in the size of the team.