Guardrails for unattended LLM jobs: caps, budgets, circuit breakers

A story many developers recognize: you set up an autonomous loop to clean up a repository overnight, go to bed, and wake up to hundreds of error notifications, a hot machine and a usage dashboard you are afraid to open. The loop did not do anything malicious. It just kept trying, and every attempt cost tokens.
Agent frameworks make it easy to start a loop and surprisingly hard to make it stop at the right time. This article is for anyone running unattended jobs against a paid or free LLM API. It covers why loops run away, the specific limits you should put in code, how to detect a stuck agent, and how to test all of this cheaply before trusting it with a real budget.
The examples use the OpenAI Python SDK, which works with OpenAI and with any compatible endpoint, including the keyless one on this site. This site is not affiliated with OpenAI; the guardrails apply equally to any provider.
Frequently asked questions
What is a runaway agent loop?
It is an agent that keeps calling the model and its tools without making progress, usually because an error is fed back as input, a goal is never marked complete, or two steps undo each other. Each iteration consumes tokens and time until something external stops it.
How does a step cap differ from a token budget?
A step cap limits the number of iterations regardless of size. A token budget limits the total input and output tokens the job may consume. You want both, because a loop can run few steps with huge contexts or many steps with small ones.
Which is better: provider spending limits or limits in code?
Use both. Provider limits are the last line of defense and catch everything, but they act late and coarsely. Limits in code stop a single job early, with a clear reason in the logs, before it affects other work.
Why do agents repeat the same failing action?
Models tend to retry what they just tried when the error message does not suggest an alternative. If your tool returns a vague error, the agent often calls it again with nearly identical arguments. Clear, specific tool errors reduce this dramatically.
Does a bigger context window make loops worse?
Often yes. Agents typically append every step to the conversation, so input size grows with each iteration and later calls cost far more than early ones. Summarizing or trimming history keeps per-step cost flat.
Can I test agent guardrails without spending money?
Yes. Point the agent at a free endpoint such as the free-ai model here and deliberately provoke failures: break a tool, give an impossible goal, or set a tiny budget. Verify that the job stops where you expect. The model differs from production, but guardrails do not depend on the model.
What does a 429 mean in the middle of a loop?
The provider is asking you to slow down. A loop should wait for the time in the Retry-After header, not retry immediately, and it should count those waits against its overall time budget so it cannot sit retrying forever.
Should an agent be allowed to retry its own errors?
A small number of retries with a changed approach is useful. Unlimited retries are the most common cause of runaway costs. Count consecutive failures and stop the job after a few in a row.
Why loops run away
Most runaway loops share a few root causes. The agent never receives a clear signal that the task is done, so it keeps looking for more to do. A tool fails and the failure text goes back into the prompt, prompting another attempt with the same inputs. Or two steps conflict, such as a formatter and a linter that keep changing each other's output.
Hardware and infrastructure add their own layer. A loop that spawns subprocesses or test runs on every iteration can saturate your machine, which slows tools down, which causes timeouts, which produce more errors for the agent to react to.
Missing stop conditions
If the goal is fuzzy, like clean up the repo, the model can always find one more thing. Define completion concretely: a list of files to process, or a check that must pass.
Error amplification
Every error message fed back to the model is new input. Long stack traces in particular inflate context quickly while adding little useful information.
Resource exhaustion
Loops that start processes, containers or test suites on every step can consume CPU and memory until the whole machine crawls. Limit concurrency for these tools separately from the model calls, and run long agent jobs in a container with memory and CPU caps so that a runaway job slows only itself, not your editor, database and everything else on the box.
The five limits every unattended job needs
Put limits in code, near the loop, where they are easy to read and adjust. Each one guards a different failure mode, and none of them depends on which model you use.
Log the reason whenever a limit triggers. A job that stops with budget exceeded after 40 steps tells you something very different from one that stops with five consecutive tool failures.
Pick conservative defaults
Start with low limits and raise them when you see legitimate jobs hitting them. It is much cheaper to rerun a job that stopped early than to pay for one that never stopped.
- Maximum steps per job.
- Maximum total tokens per job, input plus output.
- Maximum wall-clock time per job.
- Maximum consecutive failures before giving up.
- Maximum identical actions in a row, to catch repetition.

A minimal guarded agent loop
The code below shows the shape of a loop with step, token, time and failure limits. The tool layer is a stub; the point is where the checks sit. The usage object returned by the API reports prompt and completion tokens, which makes budget tracking straightforward.
Swap the base URL and model for your provider in production. During development, the keyless endpoint lets you run this as often as you like within its per-IP limits.
Truncate tool output
Notice the slice on the tool result. Feeding back only the first few hundred characters keeps the context small and prevents one huge log from blowing the token budget in a single step.
import time
from openai import OpenAI
client = OpenAI(base_url="https://api.apifreekeyopenai.com/v1", api_key="not-needed")
MODEL = "free-ai"
MAX_STEPS, MAX_TOKENS, MAX_SECONDS, MAX_FAILS = 15, 60_000, 600, 3
def run_tool(command: str) -> tuple[bool, str]:
# Replace with real tools; return (ok, short_result).
return True, f"ran: {command[:80]}"
def run_job(goal: str) -> str:
messages = [
{"role": "system", "content": "Reply with one command per turn, or DONE when finished."},
{"role": "user", "content": goal},
]
used, fails, last, start = 0, 0, None, time.monotonic()
for step in range(MAX_STEPS):
if time.monotonic() - start > MAX_SECONDS:
return "stopped: time limit"
r = client.chat.completions.create(model=MODEL, messages=messages, max_tokens=300)
used += r.usage.total_tokens if r.usage else 0
if used > MAX_TOKENS:
return "stopped: token budget"
action = (r.choices[0].message.content or "").strip()
if action.upper().startswith("DONE"):
return f"done after {step + 1} steps, {used} tokens"
if action == last:
return "stopped: repeated action"
last = action
ok, result = run_tool(action)
fails = 0 if ok else fails + 1
if fails >= MAX_FAILS:
return "stopped: consecutive failures"
messages += [{"role": "assistant", "content": action},
{"role": "user", "content": result[:500]}]
return "stopped: step limit"
print(run_job("List three files you would check first in a Python repo."))Detecting a stuck agent
Identical consecutive actions are the easiest signal, but agents often vary their wording slightly while doing the same thing. A more robust check normalizes the action, for example by lowercasing and stripping whitespace, and keeps a small window of recent actions to look for cycles.
Progress signals are better still when you have them. If the job processes a list of files, count how many are finished. If that number stops moving for several steps, the agent is stuck regardless of how different its messages look.
Cycle detection
Keep the last six normalized actions. If any action appears three times, stop. This catches A-B-A-B oscillation, which a simple repeated-action check misses.
Ask for a status line
Instruct the model to start each reply with a short progress note. It is not proof, but a sudden repetition of the same status is a useful hint in logs.

Handling rate limits inside the loop
An agent that hits a 429 and immediately retries can create its own storm, especially if several jobs share an IP or a key. The SDK has built-in retries; keep them modest and make sure the total waiting time counts against the job's clock.
Busy servers may answer 503. On the free endpoint, wait two to five seconds before trying again, and never run more than two requests in parallel from one IP. The same discipline keeps you well inside commercial limits.
Separate retries from steps
A retried API call is not a new agent step. Count them separately so that a rough patch of rate limiting does not silently use up the step budget, and so that endless retries cannot hide inside a single step.
Kill switches and alerts
Limits in code protect against expected failures. You also want a way to stop everything by hand. A simple pattern is a flag file or environment value that every loop checks at the top of each iteration. Delete the file, and all jobs end cleanly at their next step.
Pair that with alerts that fire on behavior rather than on bills. A notification when a job has run more than twice its usual duration, or when the daily token count passes a threshold, gives you time to act. Waiting for the invoice does not.
Avoid notification floods
Hundreds of identical alerts are as useless as none. Batch them: one message when a job fails, with the reason and the step count, is enough.
- Check a stop flag at the start of every step.
- Alert on duration, token count and failure rate.
- Send one summary notification per job, not one per error.
- Set a monthly budget in the provider console as the final backstop.

Testing guardrails cheaply
The best time to find out that your limits work is before they guard real money. Run the loop against the free endpoint with deliberately bad conditions: a tool that always fails, a goal that can never finish, a token budget of a few thousand. Each test should end with the expected stop reason.
Because guardrails are just code around the API call, the model behind the endpoint does not matter for these tests. Once they pass, point the same code at your production model with confidence. If you want to know more about using a free endpoint in a test pipeline, read free OpenAI-compatible APIs for testing.
Keep the tests in the repo
Guardrail tests are easy to break during refactors. Keep them with the agent code and run them in CI so a change that removes a limit fails loudly.
Simulate a slow model
Wrap the client in a test double that adds random delays and occasional 503 responses. This shows whether your time limits and retry counting behave correctly when the model is slow, which is exactly the situation in which overnight jobs tend to misbehave and pile up retries without anyone watching.
Designing tasks that end on their own
The cheapest loop is one that knows when to stop. Give the agent a finite, checkable task: process these twelve files, make this test pass, answer these five questions. Avoid open-ended goals for unattended runs.
Where an open-ended goal is unavoidable, break it into stages with a human checkpoint between them. An agent that proposes a plan, waits for approval, then executes a bounded set of steps is slower but far safer than one left alone overnight. Structured outputs help here too, as described in reliable JSON output.
Prefer plans you can inspect
Ask the model for a numbered plan first, store it, and execute against it. You can then cap steps at the plan length plus a small margin.

Send a prompt to the keyless free-ai endpoint from the home page and see a reply in seconds, no sign-up needed.
Read also
- How do you keep API keys and secrets out of prompts you send to AI?
- How to get reliable JSON output from a chat completions API
- Can agent tools run on a ChatGPT subscription instead of an API key?
- How to translate subtitle files with an OpenAI-compatible LLM API
- Why do API answers differ from what the ChatGPT app tells you?