An agent that has stopped making progress rarely announces it. It reads the same file again, runs the same search with the same words, or alternates between editing a file and running a test that fails the same way every time. Each step looks reasonable on its own. A hard cap on steps or tokens will eventually end the run, but only after you have paid for the whole budget, and a cap tells you nothing about why the run ended. A loop detector is a cheaper, earlier signal: it notices that the last few steps taught the agent nothing new, and it lets you intervene while the run is still recoverable.

This article builds a small detector from three ideas: fingerprint each step, judge repetition by call and result together, and respond in escalating stages rather than killing the run on first suspicion.

Fingerprint the step, not the text

You cannot detect repetition by comparing raw model output. The model rephrases its reasoning every turn even when it is doing the same thing. The stable signal is the tool call: tool name plus arguments. Hash a canonical form of that, and two calls that mean the same thing collide.

Canonicalization is where most of the value is. Sort object keys, collapse whitespace, lowercase free-text arguments, and drop arguments that change on every call without changing meaning (request ids, timestamps, trace ids). Without that, a search for "Refund Policy" and one for "refund policy" hash differently and the detector never fires.

import hashlib, json

VOLATILE_ARGS = {"request_id", "timestamp", "trace_id"}

def fingerprint(obj) -> str:
    def clean(v):
        if isinstance(v, dict):
            return {k: clean(x) for k, x in sorted(v.items())
                    if k not in VOLATILE_ARGS}
        if isinstance(v, list):
            return [clean(x) for x in v]
        if isinstance(v, str):
            return " ".join(v.split()).lower()
        return v
    return hashlib.sha256(
        json.dumps(clean(obj), sort_keys=True).encode()
    ).hexdigest()[:12]

Lowercasing is a trade-off. For a code-search tool, Foo and foo can be different symbols, and normalizing them would merge two genuinely different calls. Decide per tool which arguments are case-sensitive. A per-tool normalizer table is more work than the single function above, but it is the difference between a detector you trust and one you mute after a week of false alarms.

Repetition means call plus result

A repeated call is not automatically a loop. Polling a job status five times is correct behavior, and so is re-reading a file after you edited it. What distinguishes a stuck agent from a patient one is whether the world answered differently.

So fingerprint the result too, and track the pair (call_fp, result_fp):

  • Same call, different result: progress or legitimate polling. Do not flag it.
  • Same call, same result: the agent learned nothing. Count it.
  • Different call, same result: often a near-duplicate query, such as three differently worded searches that all return the same top hits. Worth logging, though not worth acting on by itself.
from collections import deque

class LoopGuard:
    def __init__(self, window=12, max_stale=3, max_cycle_repeats=2):
        self.steps = deque(maxlen=window)   # (call_fp, result_fp)
        self.max_stale = max_stale
        self.max_cycle_repeats = max_cycle_repeats

    def record(self, tool, args, result):
        self.steps.append((fingerprint([tool, args]), fingerprint(result)))
        return self.check()

    def check(self):
        steps = list(self.steps)
        last = steps[-1]
        if sum(1 for s in steps if s == last) >= self.max_stale:
            return "stale_repeat"
        for n in range(2, 5):                     # cycles of length 2-4
            need = n * (self.max_cycle_repeats + 1)
            if len(steps) >= need:
                tail = steps[-need:]
                block = tail[:n]
                if (all(tail[i:i+n] == block for i in range(0, need, n))
                        and len(set(block)) > 1):
                    return f"cycle_{n}"
        return None

The window keeps the check cheap and keeps old, legitimate repetition from counting against a run that has since moved on. max_stale=3 means the third identical call-and-result pair inside the window trips the alarm; the first repeat is often a harmless retry, so you want at least two before acting.

Catch the cycles that exact matching misses

The stale counter catches an agent hammering one call. Real loops are often two or three steps long: edit a file, run the tests, see the same failure, edit the file back, run the tests again. The second half of check looks at the tail of the window for a block of 2 to 4 steps repeated end to end.

Be honest about the limits here. If the results in that cycle are byte-identical, the stale counter will usually fire first, because each pair keeps recurring. The cycle check earns its place when results differ in a way that does not matter, for example a test runner that prints a duration, or a tool that echoes a counter. In that case the pairs never match exactly, and nothing fires. Two fixes help: normalize volatile fields out of results the same way you did for arguments, and for noisy tools fingerprint only a stable slice of the result, such as the exit code plus the first failing test name.

The detector will not catch an agent that varies its calls enough to dodge exact matching, such as a search whose query it rewrites slightly each time. That needs semantic comparison (embedding distance between consecutive queries, or a "has the set of distinct results grown?" check). Both add cost and false positives, so start with exact matching, measure how many real stuck runs it misses in your traces, and add the fuzzy layer only if that number justifies it.

Respond in stages

Detection is cheap. Reacting wrongly is expensive, because the false positive that kills a healthy run is worse than the loop it prevented. Escalate:

  1. Nudge. Append a short, factual message to the context: "You have called read_file with the same arguments 3 times and received the same error. Do something different, or explain what is blocking you." Name the repeated call and the repeated result. A vague "you seem stuck" gives the model nothing to act on.
  2. Constrain. If the pattern recurs after a nudge, remove or disable the offending tool for a few turns, or require the next response to be a plain-text summary of what has been tried. This forces a change of strategy without ending the run.
  3. Stop with a report. If it still recurs, end the run and return a structured failure: the pattern name (stale_repeat, cycle_2), the repeated step, and the last few steps. That report is what lets a human, or a retry with a different prompt, pick up the work.

Trade-offs to know about. A nudge costs tokens and sometimes anchors the model on the very call you flagged. Disabling a tool can strand an agent whose only path forward runs through it. And any threshold is a bet: set it too low and slow, deliberate agents get interrupted; too high and you are back to paying for the full budget.

Test it on recorded traces, not on hope

The detector is deterministic, so test it like ordinary code. Feed it scripted sequences and assert on the verdict:

def test_polling_with_changing_result_is_not_a_loop():
    g = LoopGuard()
    for status in ["queued", "running", "running2", "done"]:
        assert g.record("job_status", {"id": 7}, {"s": status}) is None

def test_same_call_same_result_flags_stale():
    g = LoopGuard()
    out = [g.record("read_file", {"path": "a.py"}, {"err": "not found"})
           for _ in range(3)]
    assert out == [None, None, "stale_repeat"]

def test_fingerprint_ignores_noise():
    a = fingerprint(["search", {"q": "Refund  Policy", "request_id": "1"}])
    b = fingerprint(["search", {"request_id": "2", "q": "refund policy"}])
    assert a == b

The first test is the one that protects you from yourself: it encodes that polling must stay quiet. Then replay your real traces. Collect a few runs you know were stuck and a few you know were healthy but repetitive, run the guard over each, and check that it flags the first group and stays silent on the second. Adjust thresholds against those traces, not against intuition. If you have no labeled traces yet, the stuck ones are easy to find: they are the runs that hit your step cap.

Checklist

  • Fingerprint tool name plus normalized arguments; drop volatile fields and decide per tool what is case-sensitive.
  • Fingerprint results too, and normalize noisy fields (durations, counters) or hash only a stable slice.
  • Treat same call with a different result as progress; flag same call with the same result.
  • Keep a bounded window so old repetition does not count against a run that moved on.
  • Check for short cycles (length 2 to 4) as well as single-call repeats.
  • Escalate: nudge naming the repeated call, then constrain, then stop with a structured report.
  • Log every detection with the pattern name so you can measure false positives.
  • Tune thresholds on labeled traces, and add fuzzy matching only when exact matching demonstrably misses real stuck runs.