Skip to content

Loop Detection

Loop detection is an optional middleware layer that monitors tool-call patterns during an agentic run and intervenes before the agent exhausts its token budget making no progress. Detector counts are derived from state["messages"] on each model call — there are no persisted counters between calls. Handler modes that need a two-phase flow (synthesize, reflect) also keep small per-run instance flags — see How it works internally.

When to enable it

Enable loop detection if your agents:

  • Call the same search/grep command repeatedly with identical parameters.
  • Repeatedly poll an external API (status check, health check) that is not making progress.
  • Bounce between two tools without converging on an answer.

Configuration

Loop detection is a middleware. Add a loop_detection entry to config.middleware: in abt.yaml (project-wide) or to an agent's middleware: frontmatter list:

config:
  middleware:
    - loop_detection:
        warn_threshold: 5       # advisory warning at this many repetitions
        critical_threshold: 10  # forced graceful wrap-up at this many repetitions
        detectors:
          generic_repeat: true       # same (tool, args_hash) N times
          poll_no_progress: true     # polling tool returns same result N times
          ping_pong: true            # A↔B alternation between two tools
          tool_error_repeat: true    # same tool errors N times (e.g. task retry storms)
          empty_tool_output: true    # same tool returns empty results N times (e.g. git grep sweeps)
          same_tool_repeat: true     # same tool name N times in a row, not all with distinct args

Optional thread_chars_threshold (project or agent) enables thread-size detection when cumulative message chars exceed the limit (warn at threshold, critical at 2×). Default: off. Binary content is not counted: image, file, document, audio and video blocks, and any block carrying a base64 payload. Their context cost is managed by compaction, which estimates them in tokens.

Detectors count only the current turn — the newest HumanMessage when the run starts, and everything after it. On a checkpointed thread, earlier turns are neither counted nor rolled back.

Failure mode Detector
Identical tool + args repeated generic_repeat
Same tool spamming, some repeated args same_tool_repeat
Polling tool stuck poll_no_progress
A↔B tool alternation ping_pong
Tool errors in a row tool_error_repeat
Empty grep / rg sweeps empty_tool_output
Thread bloat from large tool output thread_chars (opt-in)

Per-detector entries can override global thresholds and on_warning / on_critical (see below).

Per-agent frontmatter override

Individual agents can tighten or loosen thresholds. In the agent's frontmatter, add:

middleware:
  - loop_detection:
      critical_threshold: 6   # stricter limit for this agent

Per-detector overrides (thresholds and warn/critical handlers), also in the agent's frontmatter:

middleware:
  - loop_detection:
      on_warning: advise          # global default for warn threshold
      on_critical: terminate      # global default for critical threshold
      detectors:
        empty_tool_output:
          warn_threshold: 4
          critical_threshold: 7
          on_warning: synthesize   # only this detector gets warn synthesis
          on_critical: synthesize  # only this detector gets one synthesis turn at critical
        tool_error_repeat:
          on_critical: reflect     # one reflection-model call at critical

To disable loop detection for a specific agent, add this to its frontmatter:

middleware:
  - loop_detection:
      enabled: false

Inheritance

A project-level loop_detection middleware entry in abt.yaml applies to delegating agents and subagents unless an agent opts out with loop_detection: { enabled: false } or overrides individual fields in frontmatter. Global warn_threshold / critical_threshold apply to every enabled detector; override per detector when one pattern needs tighter limits. In abt.yaml:

config:
  middleware:
    - loop_detection:
        warn_threshold: 4      # default for generic_repeat, poll_no_progress, …
        critical_threshold: 7
        detectors:
          empty_tool_output:
            warn_threshold: 3
            critical_threshold: 5

Boolean toggles still work (generic_repeat: false). A mapping without thresholds enables the detector and inherits globals (tool_error_repeat: {} is equivalent to tool_error_repeat: true; per-detector mappings accept only enabled, warn_threshold, critical_threshold, on_warning, on_critical).

Detectors

generic_repeat

Detects the same tool called with identical arguments N times in a row.

Threshold Behaviour
warn_threshold Appends a HumanMessage advisory: "you've called X N times with identical arguments — try a different approach". The model decides whether to change.
critical_threshold Injects a loop-detected wrap-up AIMessage (run_warning="loop_detected") and jumps to graph end (jump_to="end").

Example: an agent that runs grep -rn "Foo" five times in a row with the exact same pattern and path hits warn_threshold=5 and gets nudged to try something else.

poll_no_progress

Detects a polling tool returning the same result N times consecutively. A tool is classified as a polling tool if its name matches the pattern /(status|poll|check|wait|ping|health)/i.

Threshold Behaviour
warn_threshold Injects an advisory HumanMessage about the stalled resource.
critical_threshold Forces a graceful wrap-up.

ping_pong

Detects an A→B→A→B alternation pattern between exactly two tools with no resolution. Minimum qualifying window: 4 consecutive calls.

Threshold Behaviour
warn_threshold Advisory HumanMessage: "tools A and B have alternated N times — try a different approach or gather what you have".
critical_threshold Forces a graceful wrap-up.

tool_error_repeat

Detects the same tool returning errors N times consecutively, regardless of argument changes. Catches task retry storms where the LLM rewrites the prompt each time but every subagent invocation still fails (e.g. GraphRecursionError).

empty_tool_output

Detects the same tool returning empty or whitespace-only results N times consecutively. Arguments may differ each call (so generic_repeat misses), but every result is still empty — typical of repeated repo_search sweeps that find nothing. Legitimate messages like Error: no results found are not treated as empty.

same_tool_repeat

Same tool called N times in a row, with at least one repeated arg set. Exempts an all-distinct-args tail (fan-out, e.g. varied search queries) — not a loop.

same_tool_repeat_any_args

Same as same_tool_repeat, minus the distinct-args exemption. Off by default; enable when a tool cycles unproductively even with varied args (e.g. troubleshooting the same issue via different IDs). Tune thresholds higher — it also counts legitimate fan-out. In abt.yaml:

config:
  middleware:
    - loop_detection:
        detectors:
          same_tool_repeat_any_args:
            warn_threshold: 6
            critical_threshold: 10

Threshold handlers (on_warning / on_critical)

When a detector hits warn_threshold, the handler mode controls what happens next. Default is advise (current behaviour: inject advisory HumanMessage, agent continues).

Mode At warn At critical
advise (default) Advisory HumanMessage —
terminate Immediate exit (loop_detected) Same
synthesize One executor synthesis turn, then continue One turn, then exit
reflect Reflection model call, inject answer, continue Reflection, then exit
rollback Truncate to last productive checkpoint, inject recovery prompt, continue Same (ends the run if the same detector re-triggers at critical)

Set globally under loop_detection.on_warning / on_critical or per detector under loop_detection.detectors.<name>.on_warning / on_critical (detector wins).

One handler code path serves both the warn and critical levels. The detectors are pure message-scanning logic, and the LangChain middleware is a thin wrapper around them.

Example: early synthesize nudge at warn

In abt.yaml:

config:
  middleware:
    - loop_detection:
        warn_threshold: 2
        critical_threshold: 5
        on_warning: synthesize
        on_critical: terminate
        detectors:
          empty_tool_output:
            warn_threshold: 2
            critical_threshold: 4

At 2 empty results the executor gets a synthesis nudge but may continue; at 4 it hard-stops.

Critical handler modes (reference)

When a detector hits critical_threshold:

Mode LLM calls Behaviour at critical
terminate (default) 0 Ends the run now with an empty answer (see Stopped runs). Use synthesize for an answer
synthesize 1 (executor) Inject synthesis prompt; executor gets one final turn, then exit
reflect 1 (reflection model) One-shot reflection call with curated context; answer injected, then exit
rollback 0 Remove messages after last productive checkpoint, inject strategy-switch prompt; ends the run when the same detector re-triggers at critical

At warn, the same modes apply via on_warning (default advise). See Threshold handlers above.

In the frontmatter of agents/permission-specialist.md, add:

middleware:
  - loop_detection:
      warn_threshold: 4
      critical_threshold: 7
      on_critical: synthesize
      detectors:
        empty_tool_output:
          warn_threshold: 4
          critical_threshold: 7
          on_critical: synthesize

When a search tool returns empty 7 times, the executor gets one turn to produce its output_schema JSON from evidence already in the thread — instead of a generic hard stop.

Example: reflection model at critical (global + per-detector)

config:
  middleware:
    - loop_detection:
        on_critical: terminate
        reflection:
          model: eu.anthropic.claude-opus-4-7-20251101-v1:0
          max_context_messages: 15
          include_tool_results: true
        detectors:
          tool_error_repeat:
            on_critical: reflect

Reflection model resolution: the entry's reflection.model → executor model_id.

Example: rollback on warning, terminate on critical

config:
  middleware:
    - loop_detection:
        on_warning: rollback
        on_critical: terminate

At warn_threshold the handler scans messages backward for the last substantive ToolMessage (non-error, non-empty, non-duplicate) and removes all messages after it via RemoveMessage. A recovery HumanMessage is injected summarizing progress and asking the model to try a different strategy. Each detector gets one rollback per run. If the same detector reaches critical_threshold again, the handler falls through to terminate; a repeated warning only advises, and another detector's rollback never counts against this one. This gives the model a clean slate without losing verified progress. The checkpoint is searched within the current turn, so the turn's own input is never removed.

thread_chars measures size, not repetition, so it never uses rollback: a global on_warning: rollback becomes advise for it, and a global on_critical: rollback becomes terminate.

How it works internally

abt builds the loop-detection middleware whenever a - loop_detection: entry is declared. Its before_model hook scans state["messages"] on every model call. Detector counts are message-derived (no persisted counters). For on_critical: terminate and warn advisories the middleware is stateless across calls. For synthesize and reflect, small per-run instance flags coordinate the two-phase critical flow, so abt creates a fresh instance per agent.

When the critical threshold is reached, behaviour depends on on_critical:

  • terminate: returns jump_to="end" immediately (see below).
  • synthesize: injects a synthesis HumanMessage, allows one executor turn, then exits in after_model.
  • reflect: invokes the reflection model once via abefore_model (async), injects the answer, then exits.

Default (terminate) critical exit:

{"jump_to": "end", "messages": [AIMessage(
    content="Loop detected …",
    additional_kwargs={"abt_run_warning": "loop_detected"},
)]}

The abt_run_warning key is picked up while the run streams and surfaces as RunResult.warning == "loop_detected".

run_results.json guardrails block

When loop detection, model-call limits, or thread-size tracking fire during a run, run_results.json includes an optional guardrails object on each result node (and nested dep_results):

{
  "warning": "loop_detected",
  "guardrails": {
    "model_calls": 18,
    "thread_chars_peak": 142000,
    "middleware_warning": "loop_detected",
    "loop_events": [
      {"detector": "same_tool_repeat", "level": "warn", "tool": "repo_search"}
    ],
    "tools_used_count": 2
  }
}

model_calls is populated when the model_call_limit middleware is enabled. thread_chars_peak tracks the largest message-thread size seen when loop detection is active (including when thread_chars_threshold is set). Omitted when nothing was collected.

run_warning and downstream handling

The enforcement mechanisms produce different RunResult.warning values:

Middleware run_warning value
AbtModelCallLimitMiddleware (tags LangChain limit exits) "budget_exhausted"
TokenBudgetMiddleware "budget_exhausted"
LoopDetectionMiddleware "loop_detected"
RunTimeoutMiddleware "timeout"

RunResult.warning is available to any caller of the SDK or CLI (run_results.json's result.warning field); use it to distinguish a graceful stop from a normal completion. ProgressTrackerMiddleware adds "stagnation_detected".

Stopped runs

Whichever guard ends a run, the result keeps two things apart:

  • RunResult.text is only what the model wrote. When a guard ends a run mid-investigation and has a synthesis_model (per-mechanism or the global one), that model writes the answer from the evidence already in the thread; this covers on_critical: synthesize, the token budget, the run timeout, the model call limit and the progress tracker. Without one, text is empty and the run is reported as stopped (Run stopped due to loop_detected before any response text was produced). terminate never calls a model. When the turn that tripped a guard is already the model's finished answer, the stop is recorded and the answer is left as written. A guard never writes its own sentence into the answer, and a synthesis_model that cannot be resolved or fails ends the run with no answer rather than an error.
  • RunResult.stop carries the typed reason (kind, detector, reason), also written to run_results.json as result.stop. These are operator diagnostics: they are never shown to the model that writes the answer, and never passed on to other agents.

The synthesis call is not streamed live: the answer reaches the user once, in the closing message. The synthesis model sees the conversation without the runtime notices the guards injected earlier ([loop_detection:…], [run_timeout], [model_call_limit]), because those are instructions for the agent, not findings.

A stopped agent with an answer still feeds downstream agents, but the next agent is told so. Its <upstream_agent> block is marked and one standing instruction is added to the context:

<upstream_agent name="investigator" status="stopped" stop="loop_detected">
…the investigator's partial answer…
</upstream_agent>
<upstream_notice>
An upstream agent was ended early by a runtime limit, so what came from it (an <upstream_agent> block
marked status="stopped", or text inserted into your task) is partial or empty. Report only what it
contains and say that it is incomplete. …
</upstream_notice>

The notice depends on where the content came from, not on how it arrived: a prompt node that inlines a stopped agent's output with {{ upstream('name') }} passes the stop on, so the agent that receives that task is told too.

A stopped agent with no answer fails its workflow node, so nothing downstream reports on it.

The stop is recorded on the run a guard ended. An agent that consumes a stopped agent's output (as a subagent result or as a workflow successor) is not itself marked stopped; it is told in its context to carry the caveat. Exposures deliver a stopped run's answer with a one-line note that it may be partial (PARTIAL_ANSWER_NOTE in abt.exposures.dispatcher).

Guard exits are built in one place, abt.infra.llm.run_stop; a unit test fails if any other module writes the stop markers.

recursion_limit vs model_call_limit middleware

These guardrails measure different things:

Setting What it counts Typical use
recursion_limit LangGraph graph steps — every before_model/after_model middleware hook is its own step, not just model turns (see below) Hard ceiling on graph depth; subagents get their own bound
model_call_limit middleware LLM invocations only (ModelCallLimitMiddleware) Graceful stop, independent of graph-step overhead

Each before_model/after_model hook is its own LangGraph node. One model round-trip costs 2 + (before_model hooks) + (after_model hooks) graph steps, not 1 — a typical stack (model_call_limit + token_budget + run_timeout + loop_detection) is already 8-9 steps per round-trip. A flat "3-4x model calls" sizing under-counts this: recursion_limit hits LangGraph's hard GraphRecursionError before model_call_limit.max_model_calls ever fires.

abt compile enforces this: for every agent with a model_call_limit.max_model_calls, it counts the per-round-trip node cost of the agent's middleware stack and fails with a recursion_limit=… is too low error if recursion_limit can't fit, so a bad pairing never reaches a run. Fix: raise recursion_limit or lower max_model_calls — the error states the minimum. The hooks abt adds to every agent (see middleware) are not part of that count: abt widens the limit it binds by their steps, so a recursion_limit keeps meaning the round-trips of the stack you declared.

Every agent is checked as the entry of its own run (abt run -s NAME, a workflow node, a trigger), against the top-level recursion_limit; each subagents: reference is also checked against the limit its target is built with (default_subagent_recursion_limit, 120 unless set, or the reference's recursion_limit). A top-level recursion_limit that fits does not cover a subagent: raise default_subagent_recursion_limit too. The check also runs on a cached compile, because the environment it reads (env_var() in middleware config) is not part of the cache key.

Compile builds the stack from stand-ins, so it only reports what it can prove: an agent whose middleware reads an env_var() that is unset at compile, or whose stack can't be built without live services, is skipped (with a log line). With strict_tools: true it assumes the model has native structured output, so a model without it needs one more step per round-trip than compile counts. If model_call_limit.grace_turn is also enabled (see middleware.md), that minimum doesn't account for grace_turn's one extra round-trip — leave a little headroom above it, or the nudge turn can get truncated by recursion_limit before it produces a real answer.

Loop detection (warn_threshold / critical_threshold) is a third layer: it fires on consecutive non-progress patterns in the message history, often stopping a run well before either limit is reached.

Relationship with Rubric Middleware

Rubric middleware is a complementary progress-detection system that uses an LLM grader (not message-pattern heuristics) to evaluate whether the agent is converging on a goal. Loop detection catches repetitive patterns; rubric middleware catches varied-but-futile activity. Both are infrastructure-level and fire independently.

Relationship with TokenAuditCallback

TokenAuditCallback is an observability-only callback. It emits [TOKEN_AUDIT] and [TOOL_METRIC] log lines for dashboards; it does not raise exceptions or enforce limits. If you see [TOKEN_AUDIT] warnings in your logs, they are informational — the run continues, and the budget middleware (if configured) terminates it gracefully once its own threshold is crossed.