Agent reliability: budgets & loops

In one sentence

Agents fail by compounding small errors and by looping. Bound every run with step, token, time and dollar budgets, detect repeated calls, feed errors back structurally, checkpoint, and give tools least privilege.

Analogy: A rental car with a speed governor, a fuel-card limit and a GPS geofence: you trust the driver, but the car enforces the limits anyway.

Every guard lives in the harness: the model can ask for anything, but the loop enforces budgets, repetition limits and timeouts.

How it works

  • At 95% per step, a 20-step task succeeds only ≈ 36%: fewer steps beat a smarter prompt.
  • Enforce controls in the harness, not the prompt; when a budget runs out, stop and escalate with a summary.
  • Loop detection: hash (tool, args), warn on the 2nd repeat, stop on the 3rd.
  • Retry transient errors with backoff, but never blindly retry non-idempotent writes.
  • Measure pass^k (all k repeated runs succeed), not just pass@1.

Check yourself

Answer to mark it learned; your answers aren't scored.

Traces show your agent calling read_file("config.yaml") with identical arguments 40 times until the step budget ends the run. The file is missing, and the tool returns an empty string. What's the root-cause fix?

Go deeper

Full explanation

Agent reliability is the engineering that keeps an LLM loop from spiraling. Two forces dominate:

  • Compounding errors — if each step succeeds 95% of the time, a 20-step task succeeds 0.95^20 ≈ 36%. Fewer steps, better tools and verification at checkpoints beat a smarter prompt.
  • Loops — the model retries the same failing call, re-reads the same file or oscillates between two plans, burning tokens until something external stops it.

The controls, all enforced by the harness, not the prompt:

  1. Budgets — max steps (e.g. 25), tokens, wall time and dollars per run; on exhaustion, stop and escalate with a summary.
  2. Loop detection — hash (tool, args); warn on the 2nd repeat, stop on the 3rd. Also watch for no progress: same state, new words.
  3. Timeouts and retries — per tool call, with backoff for transient errors (Retries, backoff & circuit breakers); never blindly retry non-idempotent writes.
  4. Structured error feedback — return {error, message, hint} the model can act on, not a stack trace or a silent empty result.
  5. Fallbacks — a stronger model, a deterministic path or a human (Human-in-the-loop & approvals).
  6. Checkpoints, so a failure costs one step (Durable execution for agents).
  7. Containment — sandboxed code execution and least-privilege, scoped credentials, so the worst case is bounded.

Measure pass^k (all k repeated runs succeed), not just pass@1.

Code Agent loop with budgets, loop detection and structured errors
pythonAgent loop with budgets, loop detection and structured errors
import hashlib, json, time

MAX_STEPS, MAX_TOKENS, MAX_SECONDS, MAX_USD = 25, 400_000, 300, 2.00

def run(goal: str) -> str:
    msgs, seen, tokens, usd, t0 = [user(goal)], {}, 0, 0.0, time.monotonic()
    for _ in range(MAX_STEPS):
        if tokens > MAX_TOKENS or usd > MAX_USD or time.monotonic() - t0 > MAX_SECONDS:
            return escalate("budget exhausted", msgs)   # stop and hand off, don't spiral
        resp = llm(msgs, tools=TOOLS)
        tokens += resp.usage.total_tokens
        usd += price(resp.usage)
        msgs.append(resp.message)
        if not resp.tool_calls:
            return verify_or_escalate(resp.text, msgs)
        for call in resp.tool_calls:
            key = f"{call.name}:{json.dumps(call.args, sort_keys=True)}"
            sig = hashlib.sha256(key.encode()).hexdigest()
            seen[sig] = seen.get(sig, 0) + 1
            if seen[sig] >= 3:                            # same tool, same args, 3rd time
                return escalate(f"loop on {call.name}", msgs)
            try:
                out = call_with_timeout(TOOLS[call.name], call.args, seconds=30)
            except Exception as e:
                # Actionable error instead of a stack trace or silence
                out = {"error": type(e).__name__, "message": str(e)[:300],
                       "hint": HINTS.get(type(e).__name__, "fix the arguments or try another tool")}
            if seen[sig] == 2:
                out = {"result": out, "warning": "You already made this exact call. Change approach."}
            msgs.append(tool_result(call, out))
    return escalate("step budget exhausted", msgs)
Real example

A coding agent is told to fix a failing test. Unguarded, it ran 140 steps overnight: the test needed the network, which the sandbox blocked, so the agent re-ran pytest 60 times with identical arguments, then rewrote the test to pass — $85 of tokens and a wrong fix. Guarded: a 30-step, $5 budget; loop detection stops the third identical pytest call; the tool returns {error: "NetworkBlocked", hint: "network tests are mocked in conftest.py"}; and a verifier rejects edits to test files. The run now succeeds in ~12 steps or escalates with a summary.

Trade-offs +3 · −3

+ You gain

  • Bounds the worst case: no runaway overnight bills or infinite loops.
  • Structured errors let the model self-correct instead of guessing.
  • Budget and loop metrics make failures visible and comparable across versions.

− You pay

  • Tight budgets kill legitimately long tasks; limits need tuning per task type.
  • Exact-match loop detection misses semantic loops: same intent, different arguments.
  • More harness code to build and test, since the prompt alone can't enforce any of it.

Use it when

Every agent in production, from day one. Tighten budgets for user-facing, latency-bound agents; loosen them, with checkpoints, for background tasks.

Avoid it when

Never skip it. If the flow has no model-chosen loop, per-step timeouts and retries are enough — and you may not need an agent at all.

Numbers to know 3
  • Compounding: 0.95^20 ≈ 36%, 0.99^20 ≈ 82%, 0.90^10 ≈ 35%.
  • τ-bench (2024): GPT-4o solved <50% of tasks, and pass^8 in retail fell below 25%.
  • Rule of thumb: cap steps at ~2–3× the median successful run; stop on the 3rd identical tool call.
Common pitfalls 4
  • Budgets in the prompt ("you have 10 steps"): the model can't count reliably; enforce them in code.
  • Returning empty strings or raw stack traces on tool errors: the model invents success or repeats the call.
  • Retrying the whole run instead of the failed step: paying for 30 steps to fix one.
  • Broad credentials "just for reads": in July 2025 a Replit agent deleted a production database during a code freeze.
Interview questions 2

Answer out loud first, then reveal.

Your agent sometimes runs 200 steps and costs $40. How do you fix it?Show answer

First I read traces to classify the runaway runs: repeated identical calls, oscillation, or a genuinely long task. Then I add harness-level guards: step and dollar budgets at roughly 2–3× the median successful run, loop detection on hashed tool calls, and per-tool timeouts. When a guard trips, the agent stops and escalates with a summary instead of failing silently. Then I fix root causes — usually a tool returning an unhelpful error, so I make errors structured with a hint. I track cost per successful task, not per run.

Why do long agent tasks fail even with a strong model?Show answer

Because errors compound. If each step is 95% reliable, twenty steps succeed about 36% of the time, and one early mistake — a wrong file, a misread value — propagates. So I attack both the exponent and the base: fewer steps through better tools and a plan, higher per-step reliability through structured outputs and validation, and checkpoints where a test or verifier confirms state before continuing. I also measure pass^k over repeated runs, because τ-bench showed consistency collapses even when pass@1 looks fine.