Agent State Machines, Max-Step Budgets & Detecting Infinite Loops
How to stop runaway agents from burning $50 in an infinite loop: wrapping LLMs inside deterministic Finite State Machines, canonical tool-call hashing to catch Stutter & Ping-Pong cycles, and 4-layer termination guardrails.
Bounded Agent State Machines wrap the agent loop with explicit states, max-step budgets, and repeated-call detectors so execution always terminates cleanly.
Unbounded agent loops can get stuck retrying a broken search query 200 times in a row, silently burning hundreds of dollars in API tokens.
An unguarded autonomous agent stuck retrying a broken API at 3 AM can rack up $100+ in API bills in minutes — deterministic loop guardrails are mandatory in production!
Canonical JSON hashing (sort_keys=True) catches subtle loops where the LLM calls search(a=1, b=2) then search(b=2, a=1) with identical meaning!
Instead of hard-crashing on loop detection, injecting a nudge message ('You already tried this exact call; try a different strategy or summarize what you know') often recovers the task gracefully!
Hands-on coding favorite: 'Write a Loop-Guardrail Detector that catches both repeated identical tool calls AND alternating A→B→A→B ping-pong cycles!'
How should you construct a hashable signature for a tool call (name, args_dict) so your loop detector catches identical calls even when JSON keys appear in different orders?
- Wrap a stochastic LLM inside a deterministic Finite State Machine (INIT → THINK → GUARD → EXEC → DONE/ABORT)
- Detect all 3 infinite-loop failure modes: Stutter Loops (A→A→A), Ping-Pong Cycles (A→B→A→B), and No-Progress Drift
- Canonicalize tool-call signatures
(tool_name, json.dumps(args, sort_keys=True))so key-order differences don't fool your loop detector - Combine 4 defense-in-depth stop conditions: max_steps, repeated-action detector, token/dollar budget, and wall-clock timeout
Think of an LLM as a brilliant race-car engine, and the Finite State Machine + Guardrails as the brakes, rev-limiter, and steering column. You never let a race car run with no rev-limiter — every single tool call passes through a deterministic GUARD? checkpoint that checks step count, canonical loop hashes, token spend, and elapsed time BEFORE any external action fires!
1. Wrapping the LLM Inside a Deterministic Finite State Machine
Notice that the LLM NEVER invokes a tool directly — it only proposes an action, and your deterministic GUARD? state decides whether to execute, nudge, or abort!
Deterministic Harness Principle
Separating Proposal (LLM) from Execution (FSM Harness) guarantees that even if the LLM hallucinates, gets prompt-injected, or panics, your system's worst-case cost, latency, and blast radius stay 100% bounded!
2. Catching Stutter Loops, Ping-Pong Cycles & No-Progress Drift
Click 1× through 4× Same Call in the mini-lab below to see the exact tripwire threshold in action!
Catching Both Stutter & Ping-Pong in 4 Lines
Track a rolling history of canonical signatures sig = (name, json.dumps(args, sort_keys=True)):
- Stutter (Period-1): Last signatures are identical (
A, A, A). - Ping-Pong (Period-2): Suffix matches
[A, B, A, B]ORCounter(history[-6:])[sig] >= 3— catches both period-1 AND period-2/3 cycles cleanly!
Repeated Tool-Call Circuit Breaker (Threshold = 3)
3. The 4-Layer Termination Guardrail Stack
Never rely on max_steps alone — combine 4 orthogonal circuit breakers.
Defense-in-Depth Budgets
- Max Steps (
max_steps = 8–15): Caps total turns. - Loop Detector (
max_repeats = 3): Catches stuck retries immediately (even at step 3!). - Token / Dollar Cap (
max_tokens = 32K): Stops a single huge tool output from blowing up cost. - Wall-Clock Timeout (
timeout_s = 45): Protects user UX from hung upstream APIs.
Worked Example: Detecting an A→B→A→B Ping-Pong Cycle
History of canonical signatures: [S1, S2, S1, S2].
S2 != S1 → naive period-1 check MISSES the ping-pong loop!
Why is hashing (tool_name, json.dumps(args, sort_keys=True)) better than hashing only tool_name for loop detection?
When a Loop Guardrail trips at step 4, should you return a raw 500 Internal Error to the user, or do one final no-tools LLM call?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Track (sig, observation_status) — allow 1–2 exponential-backoff retries on transient 5xx errors (Module 2.3), while immediately flagging repeats that return the exact same empty/error observation!
Agent Loop-Guardrail Detector & Circuit Breaker Studio
Toggle the Loop Guardrail ON vs. OFF to see how hashing (tool_name, canonical_args) stops runaway retry loops.
(name, sorted_args) hashing to catch both Stutter and Ping-Pong loops and gracefully synthesize a fallback answer.Production Agent Circuit Breakers
Prevents runaway API spend and infinite retry storms in customer-facing and autonomous CI agents.
from collections import Counter
# Bounded Agent State Machine with Max-Step Budget & Infinite-Loop Detector
class LoopGuard:
def __init__(self, max_steps: int = 6, max_repeats: int = 2):
self.max_steps = max_steps
self.max_repeats = max_repeats
self.steps = 0
self.seen_calls: Counter = Counter()
def check_transition(self, tool_name: str, args_key: str) -> str:
self.steps += 1
if self.steps > self.max_steps:
return "STOP_MAX_STEPS"
sig = (tool_name, args_key)
self.seen_calls[sig] += 1
if self.seen_calls[sig] > self.max_repeats:
return "STOP_LOOP_DETECTED"
return "CONTINUE"
guard = LoopGuard(max_steps=6, max_repeats=2)
for call in [("search", "q=a"), ("search", "q=a"), ("search", "q=a")]:
status = guard.check_transition(*call)
print(f"Call {call} -> {status}")
current == previous (missing A→B→A→B ping-pong cycles).p ∈ {1, 2, 3} OR frequency counts over a sliding window!last_call == prev_call?