Loop Detection and Step Budgets for LLM Agents in October 2026: Stop Runaway Tool Loops Before They Burn Your Budget

Every agent that can call tools can also get stuck. It reads a file, gets an error, reads the same file again, gets the same error, and repeats until it hits a timeout or your spending cap. Nothing crashed, so your usual alerts stay quiet, but the run is useless and the bill is real. This post covers how to detect those loops early, how to cap them with budgets, and what the agent should do when it gets stopped.

BalticServers data center
Image: BalticServers.com via Wikimedia Commons (CC BY-SA 3.0)
Virginia Tech   data center
Image: Christopher Bowns via Wikimedia Commons (CC BY-SA 2.0)

What a runaway loop actually looks like

Loops in production agents are rarely a literal infinite while True. They usually show up in a few recognizable shapes:

  • Exact repeats: the same tool called with identical arguments several times in a row, usually because the result did not change anything the model can use.
  • Oscillation: the agent alternates between two actions, such as editing a file and reverting it, or searching with two phrasings that return the same results.
  • Slow drift: arguments change slightly each time (a page number, a timestamp, a trailing space) so a naive duplicate check never fires, but no progress is made.
  • Error retry spirals: a tool keeps returning the same error and the model keeps "trying again" with the same plan.
  • Plan-only spinning: the model produces long reasoning or plan updates but never calls a tool that changes state.

Each shape needs a slightly different detector, and you want a hard budget behind all of them as a final safety net.

Layer 1: hard budgets that always apply

Budgets are the simplest control and the one you should ship first. They do not try to understand what the agent is doing. They just put a ceiling on it. Track at least these per run:

  1. Max steps: total model turns or tool calls. Pick a number from your own successful runs, for example a bit above the 99th percentile of completed runs, rather than guessing.
  2. Max wall-clock time: a deadline for the whole run, independent of step count, so slow tools cannot stretch a run indefinitely.
  3. Max tokens or cost: sum input and output tokens across turns, and convert to cost if your provider pricing is stable enough to rely on.
  4. Max calls per tool: an expensive or side-effecting tool (sending email, creating tickets) should have a much lower cap than a cheap read-only one.

Keep the budget in a small object that travels with the run, and check it before every model call, not after. Checking afterwards means the last expensive call has already happened.

from dataclasses import dataclass, field
import time

@dataclass
class Budget:
    max_steps: int = 40
    max_seconds: float = 300
    max_tokens: int = 400_000
    per_tool_caps: dict = field(default_factory=lambda: {"send_email": 2})
    steps: int = 0
    tokens: int = 0
    tool_counts: dict = field(default_factory=dict)
    started: float = field(default_factory=time.monotonic)

    def check(self, next_tool: str | None = None) -> str | None:
        if self.steps >= self.max_steps:
            return "max_steps"
        if time.monotonic() - self.started > self.max_seconds:
            return "max_seconds"
        if self.tokens >= self.max_tokens:
            return "max_tokens"
        cap = self.per_tool_caps.get(next_tool)
        if cap is not None and self.tool_counts.get(next_tool, 0) >= cap:
            return f"tool_cap:{next_tool}"
        return None

Return a reason string rather than raising immediately. You will want to log the reason and feed it into the stop behavior described later.

Layer 2: fingerprint repeated tool calls

To catch exact repeats and oscillation, compute a fingerprint for each tool call: the tool name plus a normalized version of its arguments. Normalization matters. Sort JSON keys, trim whitespace, lowercase where case does not matter, and drop fields that change every call but carry no meaning, such as request IDs or timestamps.

import hashlib, json
from collections import deque

def fingerprint(tool: str, args: dict, ignore=("request_id", "timestamp")) -> str:
    clean = {k: v for k, v in args.items() if k not in ignore}
    blob = json.dumps(clean, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(f"{tool}:{blob}".encode()).hexdigest()[:16]

class LoopDetector:
    def __init__(self, window=12, repeat_limit=3):
        self.recent = deque(maxlen=window)
        self.repeat_limit = repeat_limit

    def observe(self, fp: str) -> str | None:
        self.recent.append(fp)
        # same call N times within the window
        if self.recent.count(fp) >= self.repeat_limit:
            return "repeat"
        # A,B,A,B oscillation at the tail
        r = list(self.recent)
        if len(r) >= 4 and r[-1] == r[-3] and r[-2] == r[-4] and r[-1] != r[-2]:
            return "oscillation"
        return None

A repeat limit of 3 inside a window of about a dozen calls is a reasonable starting point. Some legitimate workflows do repeat a call, such as polling a job status. For those tools, either exempt them from fingerprint checks or give them their own backoff and cap instead.

Layer 3: measure progress, not just repetition

Slow drift and plan-only spinning slip past fingerprints. For these, ask a different question: did the last few steps change anything? Practical progress signals include:

  • New information: did a tool result contain content the agent has not seen before? You can hash the result body and check whether it matches an earlier result for the same tool.
  • State change: did a write tool succeed, a file diff grow, a test go from failing to passing, or a checklist item get marked done?
  • Error novelty: is the agent hitting a new error, or the same error message for the third time?

A simple version keeps a "no-progress counter". Reset it to zero whenever you see a new result hash, a successful write, or a new error class. Increment it otherwise. When it reaches a threshold (say 5 steps), treat the run as stalled even if no two calls were identical.

class ProgressTracker:
    def __init__(self, stall_limit=5):
        self.seen_results = set()
        self.seen_errors = set()
        self.stalled = 0
        self.stall_limit = stall_limit

    def update(self, tool, result_text, is_error, wrote_state):
        h = hashlib.sha256(f"{tool}:{result_text}".encode()).hexdigest()
        made_progress = False
        if is_error:
            key = f"{tool}:{result_text[:200]}"
            if key not in self.seen_errors:
                self.seen_errors.add(key)
                made_progress = True
        elif h not in self.seen_results:
            self.seen_results.add(h)
            made_progress = True
        if wrote_state:
            made_progress = True
        self.stalled = 0 if made_progress else self.stalled + 1
        return self.stalled >= self.stall_limit

Be careful with the "new result means progress" rule. A search tool can return different results on every call without the agent getting any closer to an answer. Pairing it with the per-tool call cap from layer 1 covers that gap.

What to do when a loop is detected

Stopping hard is the safe default, but it is not always the most useful behavior. A staged response works better:

  1. Nudge first. On the first detection, inject a short system or tool-result message that names what happened: "You have called read_file with the same arguments 3 times and received the same result. Try a different approach or explain what is blocking you." Models often recover from a clear, specific nudge.
  2. Restrict next. If the loop continues, remove the offending tool from the available tool list for a few turns, or force a different tool choice. This breaks the habit without ending the run.
  3. Stop with a useful result. If detection fires again after the nudge and restriction, end the run. Return a structured outcome: the reason (loop_detected, max_steps), the last few actions, and any partial work completed so far.
  4. Escalate when it matters. For high-value tasks, hand the stopped run to a human queue with the trace attached instead of silently failing.

Count nudges per run. One nudge is cheap and often works. Unlimited nudges just recreate the loop with extra steps.

Be careful with side effects

Loops become dangerous when the repeated tool has side effects. An agent stuck calling "create ticket" is much worse than one stuck calling "read file". Two defenses help here:

  • Give side-effecting tools low per-run caps, as in the budget example, and require idempotency keys so a repeated call does not create a duplicate.
  • Make the loop detector stricter for these tools. A repeat limit of 2 is usually fine for anything that sends, charges, or deletes.

Log enough to tune the thresholds

Thresholds picked on day one will be wrong. Record these fields for every stopped or nudged run so you can adjust them from real data:

  • The reason code and which layer triggered it (budget, fingerprint, progress).
  • The step index at which it fired and the total steps the run would typically take for that task type.
  • The last 5 to 10 tool names and fingerprints, with arguments redacted if they may contain sensitive data.
  • Whether a nudge was sent and whether the agent changed behavior afterward.

Review the false positives first. If a detector is stopping runs that would have finished correctly, raise its limit or exempt that tool. Then review the false negatives, which are the expensive runs that hit only the final hard budget. Those tell you which detector is missing.

A rollout order that works

  1. Ship hard budgets (steps, time, tokens) with a clean "stopped" result. This alone removes the worst surprises.
  2. Add fingerprint-based repeat and oscillation detection in log-only mode for a week. Compare what it would have stopped against what actually completed.
  3. Turn on the nudge, then the tool restriction, once the false-positive rate looks acceptable.
  4. Add the progress tracker for task types where drift shows up in your logs.
  5. Add per-tool caps and stricter limits for side-effecting tools.

Takeaways

You do not need a clever model-based monitor to stop most runaway agents. Hard budgets give you a guaranteed ceiling, fingerprints catch exact and alternating repeats, and a simple progress counter catches the quieter stalls. Respond in stages, protect side-effecting tools more tightly, and log every intervention so your thresholds improve over time. The goal is not to stop agents often. It is to make sure a stuck run costs you a few steps instead of a full budget.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)

Tencent Hy4 Preview: Open 770B MoE Built for Real Work