Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
AI and machine learning

AI agent loops in production: budgets, checkpoints, backoff

Keep a production AI agent loop from spinning, flooding its context, failing silently or hammering a dead API, with stop rules, checkpoints and retry budgets.

CloudSat teamNovember 18, 20267 min read
Abstract illustration of a circular arrow passing through a row of glowing gates
On this pageSix symptoms, six controls

An agent loop is simple to write: ask the model what to do, run the tool it picks, append the result, repeat. That loop works in a demo and breaks in production in a handful of predictable ways. It never decides it is done. It fills its own context with tool output. A tool fails quietly and the model carries on as if it had succeeded. A crash throws away an hour of work. An outage turns retries into a flood. None of these needs a smarter model. Each needs a control in the code around it.

Six symptoms, six controls

Symptom Control
The run never ends, or ends only when money runs out A stop contract: step, time and token limits, plus an explicit finish action
The same action repeats with no progress Repetition detection on recent tool calls
Answers get worse as the run gets longer Context hygiene: cap tool output, keep bulk data on disk, pin the goal
The agent "succeeds" at doing nothing Tools that fail loudly and verify their own effects
A crash means starting over Checkpoints after every step and idempotent side effects
An outage multiplies into a request storm Backoff with jitter, retry budgets and a circuit breaker

1. Write a stop contract

Give the loop hard limits that the code enforces, whatever the model says: a maximum number of steps, a wall-clock deadline and a token or cost budget. Then give the model a clean way to stop, such as a finish tool whose arguments carry the final answer. Without it, many models keep exploring because nothing tells them that the job is complete.

When a limit trips, return what you have with the reason attached ("stopped at step 40 of 40: token budget") instead of throwing it away. A partial result with an honest label is useful; a silent timeout is not. To set the limits, run the task a few dozen times, look at how many steps successful runs needed, and set the cap a little above that.

2. Detect loops that make no progress

A model stuck on a failing command often retries the same call with the same arguments. Fingerprint each tool call (name plus arguments), keep the last few, and stop or change strategy when one fingerprint repeats. A softer check helps too: if several consecutive steps add no new files, facts or test results, inject a message that tells the model to summarize what it knows and choose a different approach, or end the run.

3. Keep the context clean

Every tool result stays in the conversation and is sent again on every later step. A single unfiltered log file or HTML page can push out the instructions that matter.

  • Cap what goes back to the model. Keep the first and last part of long outputs and say how much was cut.
  • Store bulk data outside the prompt. Write large results to a file and return the path and a short summary. The model can read more when it needs to.
  • Pin the goal. Research such as "Lost in the Middle" (Liu and colleagues, 2023) found that language models use information at the beginning and end of a long context better than information in the middle. Keep the task statement at the top, and restate the goal and constraints when you compact older history.
  • Compact on purpose. When the context grows past a threshold you choose, replace old tool results with a summary written by the model, and keep the summary in your checkpoint.

4. Make tools fail loudly

The most expensive failure is the quiet one. A search that returns an empty list because of a typo in the query, a write to the wrong directory, an HTTP call that got a 403 and returned an empty body: the model reads "nothing found" and moves on.

  • Raise an error for anything that is not a real success, and send it back to the model marked as an error, with the message.
  • Validate inputs before acting: paths inside the workspace, IDs that exist, amounts within limits.
  • Verify effects after acting: read back the file you wrote, check the status code, confirm the row count.
  • Count errors per run and stop when they pile up. Five failed tool calls in a row is information too.

5. Checkpoint every step

Persist the loop's state after each step: messages, step count, tokens spent, and anything the tools produced. Write to a temporary file and rename it, so a crash never leaves half a checkpoint. On start, load the checkpoint if one exists and continue from there.

Resuming is only safe if side effects are idempotent. Give each action that changes the outside world (sending an email, creating a ticket, charging a card) a key derived from the run ID and step number, and make the tool skip work whose key it has already seen.

6. Retry with discipline

When a model API or a tool's backend fails, naive retries make it worse: every agent retries at once, on the same schedule, and the service never recovers.

  • Retry only what can succeed later: rate limits (429), server errors (5xx) and timeouts. Never retry a 400; fix the request.
  • Honor Retry-After when the server sends it.
  • Back off exponentially with full jitter: wait a random time between zero and min(cap, base × 2^attempt), so clients spread out instead of retrying in lockstep.
  • Count your layers. The official Anthropic and OpenAI Python SDKs already retry some errors twice by default. Your own retry loop on top multiplies the attempts.
  • Add a circuit breaker. After several consecutive failures, stop calling the service for a cooldown period, then let one trial request through before resuming.
import random
import time

class TransientError(Exception):
    def __init__(self, message, retry_after=None):
        super().__init__(message)
        self.retry_after = retry_after

def with_retries(fn, attempts=5, base=1.0, cap=30.0):
    for attempt in range(attempts):
        try:
            return fn()
        except TransientError as exc:
            if attempt == attempts - 1:
                raise
            delay = exc.retry_after or random.uniform(0, min(cap, base * 2 ** attempt))
            time.sleep(delay)

A loop skeleton with the controls wired in

This sketch is provider-neutral: call_model wraps whichever SDK you use (with retries inside it), and the attributes on reply and call stand in for that SDK's response fields.

import hashlib
import json
import time
from pathlib import Path

MAX_STEPS, DEADLINE_S, TOKEN_BUDGET, MAX_OUTPUT, MAX_ERRORS = 40, 1200, 400_000, 8_000, 5
STATE = Path("run-state.json")

class StopRun(Exception):
    pass

def save(state):
    tmp = STATE.with_suffix(".tmp")
    tmp.write_text(json.dumps(state))
    tmp.replace(STATE)

def run(task, call_model, tools):
    state = json.loads(STATE.read_text()) if STATE.exists() else {
        "messages": [{"role": "user", "content": task}], "step": 0,
        "tokens": 0, "errors": 0, "recent": [], "started": time.time()}
    while True:
        if state["step"] >= MAX_STEPS:
            raise StopRun("step limit")
        if time.time() - state["started"] > DEADLINE_S:
            raise StopRun("deadline")
        if state["tokens"] > TOKEN_BUDGET:
            raise StopRun("token budget")
        reply = call_model(state["messages"], tools)
        state["tokens"] += reply.input_tokens + reply.output_tokens
        state["messages"].append(reply.as_message())
        if reply.finished:
            save(state)
            return reply.final_answer
        for call in reply.tool_calls:
            key = hashlib.sha256((call.name + ":" + json.dumps(call.args, sort_keys=True)).encode()).hexdigest()
            state["recent"] = (state["recent"] + [key])[-6:]
            if state["recent"].count(key) >= 3:
                raise StopRun(call.name + " repeated with the same arguments")
            try:
                content, failed = json.dumps(tools[call.name](**call.args))[:MAX_OUTPUT], False
            except Exception as exc:
                content, failed = ("ERROR " + type(exc).__name__ + ": " + str(exc))[:MAX_OUTPUT], True
                state["errors"] += 1
            state["messages"].append({"role": "tool", "id": call.id, "content": content, "is_error": failed})
            if state["errors"] > MAX_ERRORS:
                raise StopRun("too many tool errors")
        state["step"] += 1
        save(state)

Catch StopRun at the top level, attach the reason to whatever partial result the run produced, and report it.

Watch it run

Log one structured line per step: run ID, step, tool, duration, tokens, and whether the call failed. Alert on runs that hit a limit, not only on crashes, because a budget stop is often the first sign of a prompt or tool regression. Keep the checkpoints of failed runs for a while; they are the best debugging record you will get.

Because the loop spends most of its time waiting on the network, its workers need little compute. A small Cloud VPS per environment is usually enough, run under systemd as described in the unattended agents guide.

FAQ

Should the model or the code decide when to stop?

Both. The model signals completion through a finish action, and the code enforces limits the model cannot override. Never rely on the model alone to notice that it is going in circles.

Do agent frameworks handle this for me?

Some provide pieces, such as turn limits or retry settings. Check which of the six controls your framework covers, and add the rest around it. The controls matter more than the framework.

How do I test these guards?

Inject failures on purpose: a tool that returns an error, an API stub that answers 429 with Retry-After, a process kill in the middle of a run. If the run resumes, backs off and stops where it should, the guards work.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.