An AI agent runaway token bill is almost never one big request. It is a loop that repeats a step, a retry layer that multiplies failures, or a history that gets longer on every turn, and the bill shows up before anyone reads a log. This post gives you what the top results for this topic do not: a calculator that models a loop with growing context, a table of what common agent frameworks cap by default (read from their own docs on 28 November 2026), six caps in the order we would add them, and a plain list of which of those caps One AI API Key enforces today and which it does not.
What does a runaway agent bill look like in practice?
Four public reports, all written by the people who paid for them, are enough to see the pattern. None is independently audited, and we say so in the last column. Dates are the dates the sources give.
| When | What looped | Size reported | Source and how solid it is |
|---|---|---|---|
| 22 to 28 October 2026 | A Stop hook and a PreToolUse hook disagreed about one file, so scheduled headless coding-agent sessions retried the same refused edit | About $9,364.52 of extra usage in the loop window, about 2.4 billion tokens, 18 automatic credit reloads that week | A user’s bug report on GitHub, opened 4 November 2026. The reporter’s own figures, offered with files on request |
| 6 June 2026 | A background “curator” job hit a file-read error and kept trying to fix it | 5,501 calls, 353.4 million tokens in 20 hours 25 minutes, a weekly quota at 98 percent | The team’s own post-mortem, published 7 June 2026 |
| November 2025 | Two of four chained agents traded open-ended “do more analysis” and “please verify” messages | About $47,000 over 264 hours, found on the billing dashboard | A case study that summarises the team’s post-mortem: second-hand, so a claim, not a measurement |
| October 2026 | A stricter review prompt rejected drafts in a nightly job, each rewrite re-sent a growing history | About 3 times a normal day of spend; the job ran six hours instead of 40 minutes | A first-person post-mortem on dev.to, 25 October 2026 |
Read the table for what the causes have in common, not for the dollar totals. A hook deadlock, an error retry, a verifier that never approves and a prompt change are four unrelated bugs. Each one ran with no ceiling per run, and each one was found by a bill, a quota meter or a daily alert, not by the agent.
A few numbers deserve a second look, because we did the arithmetic ourselves. The hook-loop reporter’s $9,364.52 over 2.4 billion tokens is a blended $3.90 per million tokens (9,364.52 divided by 2,400), which fits a workload that was almost all cache reads of the same context, as the reporter says. The Hermes job averaged 64,241 tokens a call at 269 calls an hour, so each call carried a very large history. And one retelling of the $47,000 story lists weekly totals of $127, $891, $6,240 and $18,400, which add to $25,658, not $47,000, and an 11 day run is not four weeks. We still cite the incident, because several write-ups repeat it, but we treat $47,000 as a headline claim. Our post on token billing audits shows how to check your own bill the same way.
Why does a stuck agent cost more with every step?
There are three separate multipliers, and caps work on different ones.
Repetition. The same call, again and again. This is the plain loop: a tool fails, the agent tries again, nothing changes. The cost is steps times cost per step, and a step limit or a repeat check stops it.
Retry multiplication. Retries stack across layers. The official OpenAI SDKs retry 429, 5xx and connection errors 2 times by default and time out after 10 minutes. If your own code adds 5 retries on top, one logical call can turn into (1 + 2) times (1 + 5) = 18 attempts. Our rate limits guide says to raise the SDK’s own retry setting instead of wrapping a second loop around it, for exactly this reason, and the 429 error post separates retryable errors from terminal ones. A timeout is the expensive case: the rate limits guide notes that a request you abandoned may still be billed for the tokens the model produced before it stopped.
Context growth. Every turn re-sends the whole conversation. If a step adds a tokens of tool output and reply to a starting context of B, step k sends B plus a times (k minus 1) input tokens, and the total after n steps is n times B plus a times n times (n minus 1) divided by 2. That second term is quadratic: doubling the steps roughly quadruples the input. It stops growing only when the context reaches the model’s window, after which every step costs the maximum. The cost-control docs say the same in one line: the whole conversation is billed on every turn.
The diagram shows the example used in the calculator below: a 20,000 token starting context, 3,000 tokens added per step and a 200,000 token window.
One stuck loop, step by step
How much does a loop cost? A calculator
Enter your own context size, growth per step and rates. The default rates ($2 in, $8 out per 1M tokens) are round illustrative numbers, not any vendor’s list price. For comparison, our own listing for qwen3.8-27b-abliterated is $0.51 in and $2.27 out per 1M on the uncensored model list, bought by email, and our Claude Fable 5.2 loop-math post works through $8 and $40. The calculator runs in your browser and sends nothing.
Cost of a runaway loop
- Steps until the window is full
- 61
- Input tokens billed
- 34,510,000
- Output tokens billed
- 160,000
- Total cost of the loop
- $70.30
- Average cost per step
- $0.3515
Assumes the context grows by the same amount each step until it reaches the window, then stays at the window (no compaction). Cached tokens are priced at the cached rate you enter; whether a provider applies one depends on the model.
With the defaults, 200 steps cost $70.30: 34,510,000 input tokens and 160,000 output tokens. The window fills at step 61, and the remaining 139 steps each re-send 200,000 tokens. At our listed rates for qwen3.8-27b-abliterated the same loop is $17.96; at $8 and $40 it is $282.48. Set the cached share to 80 and the 200 step loop falls to $20.61: cheaper, still unbounded.
Same loop, more steps (illustrative $2 and $8 rates)
- 25 steps$2.96
- 50 steps$9.67
- 100 steps$29.66
- 200 steps$70.30
- 400 steps$151.5851 times the cost of 25 steps for 16 times the steps
Two lessons come out of the numbers. First, output is a rounding error here: 160,000 output tokens are 0.5 percent of the tokens and 1.8 percent of the cost, so capping reply length alone does almost nothing against a loop. Second, the Hermes report’s 352 million input tokens would cost $715.12 at the illustrative rates and $182.68 at our listed rates for qwen3.8-27b-abliterated, if none of it was cached. That job ran on a provider quota, not a per-token bill, so this is arithmetic, not what the team paid.
What do agent frameworks cap by default?
Less than you would hope, and the defaults differ by two orders of magnitude. We read these on 28 November 2026.
| Tool | Setting | Default | Source |
|---|---|---|---|
| OpenAI Agents SDK | max_turns |
10 (DEFAULT_MAX_TURNS = 10 in the source); max_turns=None removes the limit |
Running agents and the source |
| LangGraph | recursion_limit |
10,007 super-steps from version 1.1.4 (10,000 from 1.0.6 to 1.1.3) | Graph API: recursion limit |
| Claude Code, print mode | --max-turns and --max-budget-usd |
Turns: no limit by default. Budget: only when you pass it, checked against a client-side estimate | CLI reference |
| An agent reported in the Hermes post-mortem | max_iterations |
Set to 9999 in a background job | The post-mortem |
| OpenAI SDKs | max_retries, timeout |
2 retries, 10 minute timeout | openai-python README |
A 10,007 step default is a limit in name only. At the calculator’s default step cost of $0.35 it would allow about $3,517.46 before it fires. A limit you choose from your own logs is a different thing: our advice is to take the longest legitimate run you have recorded and set the cap at 1.5 times that. The Claude Code CLI reference also warns that its budget check uses a client-side estimate that can differ from your actual bill, which is why a cap in the client is the first line of defence, not the only one. For a coding agent specifically, our guide to setting up a coding agent key and the post on subagent hangs and timeouts cover the knobs of the common tools.
Cap 1: how do you limit tokens per call?
Set an output cap on every request. OpenAI’s chat completions reference defines max_completion_tokens as an upper bound for a completion, including visible output tokens and reasoning tokens, and marks the older max_tokens as deprecated on that API. Our own examples send max_tokens, and the chat completions page lists the fields the gateway accepts, so check it for the name your client uses. On a reasoning model the thinking tokens count as output, as the reasoning guide explains, so a small cap can cut an answer off before it starts.
What this cap does: it stops one reply that never ends, the failure behind a model that keeps generating until its own limit. What it does not do: stop a loop, because each reply can be short and the loop still runs. Pair it with a second control on input size: trim old turns, summarise settled work, drop tool output you no longer need. The post on 10 tactics to cut LLM API costs has the arithmetic for each.
Cap 2: how do you stop a loop in the agent itself?
Three checks, all in your own code, because only your code can see what the agent is doing.
- A step limit. Count model calls and stop at a number you chose. Choose it from logs, not hope.
- A repeat check. Hash the tool name and arguments. When the same pair appears 3 times, stop. The hook-loop reporter points out that the client already sees every identical refusal, and that three in a row is a signal it could act on. You can act on it today in your own loop.
- A deadline. A wall-clock limit per run. It catches the slow loop that a step count misses, such as a tool that hangs.
The guard below implements those three, plus a token limit and a spend limit measured from the usage object in each reply. It also treats the gateway’s budget codes as the end of the run. A 429 with key_daily_budget, key_budget_blocked, account_spend_cap, end_user_budget or daily_limit_free means a limit you set is used up, so backing off and retrying only wastes time. MDN’s definition of 429 is “too many requests in a given time”, which is a retryable idea; these codes are the exception. The same mistake appears in the post on network storms and retry loops, where an unbounded reconnect loop is the whole incident.
import hashlib, json, os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.oneaiapikey.com/v1", api_key=os.environ["ONEAIAPIKEY_API_KEY"], max_retries=1, timeout=90)
MODEL = os.environ["MODEL_ID"] # placeholder: the id you call, for example a free id while you test
# 429 codes that mean "this key, account or free allowance is used up": stop the run, do not back off and retry.
TERMINAL = {"key_daily_budget", "key_budget_blocked", "account_spend_cap", "daily_limit_free", "end_user_budget"}
class RunStopped(Exception):
pass
class RunGuard:
def __init__(self, max_steps=25, max_tokens=400_000, max_usd=2.00, max_seconds=600, max_repeats=3,
usd_per_m_in=0.0, usd_per_m_out=0.0):
self.max_steps, self.max_tokens, self.max_usd = max_steps, max_tokens, max_usd
self.max_seconds, self.max_repeats = max_seconds, max_repeats
self.rin, self.rout = usd_per_m_in, usd_per_m_out
self.t0, self.steps, self.tokens, self.usd, self.seen = time.monotonic(), 0, 0, 0.0, {}
def after_call(self, usage):
self.steps += 1
self.tokens += usage.prompt_tokens + usage.completion_tokens
self.usd += (usage.prompt_tokens * self.rin + usage.completion_tokens * self.rout) / 1_000_000
if self.steps >= self.max_steps: raise RunStopped(f"step limit {self.max_steps}")
if self.tokens >= self.max_tokens: raise RunStopped(f"token limit {self.max_tokens}")
if self.usd >= self.max_usd: raise RunStopped(f"spend limit {self.max_usd:.2f} USD")
if time.monotonic() - self.t0 >= self.max_seconds: raise RunStopped(f"deadline {self.max_seconds}s")
def see_tool(self, name, args):
key = hashlib.sha256((name + json.dumps(args, sort_keys=True)).encode()).hexdigest()
self.seen[key] = self.seen.get(key, 0) + 1
if self.seen[key] >= self.max_repeats:
raise RunStopped(f"{name} called {self.max_repeats} times with the same arguments")
def run(messages, tools, call_tool, guard):
while True:
try:
reply = client.chat.completions.create(model=MODEL, max_tokens=800, messages=messages, tools=tools)
except RateLimitError as e:
body = e.body if isinstance(e.body, dict) else {}
if body.get("code") in TERMINAL:
raise RunStopped(f"gateway limit: {body.get('code')}")
raise
guard.after_call(reply.usage) # stops before the next call, so the overshoot is one step
msg = reply.choices[0].message
if not msg.tool_calls:
return msg.content
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
guard.see_tool(call.function.name, args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": call_tool(call.function.name, args)})Three honest limits of that code. It checks after each call, so a run can overshoot by one step. It computes spend from the rates you pass in, so it is an estimate, like Claude Code’s. And it does not help if the loop lives inside a tool you do not control; that is what the next caps are for.
Cap 3: how do you cap spend per key?
This is the cap a gateway can enforce for you, and it is where one key per job pays off. On One AI API Key each key can carry the settings below, all editable under Keys in the console. We checked each one against the authentication guide, the cost control guide, the console form and the gateway source on 28 November 2026.
| Setting | What happens at the limit | What your agent sees |
|---|---|---|
| Spend limit (USD, lifetime) | The key stops working. Your account balance still applies on top | 403 pre_consume_token_quota_failed while the rest is too small for one request, then 401 Invalid token |
| Spend budget (USD, resets daily at 00:00 UTC, weekly on Monday or monthly on the 1st) | Requests are refused until the reset. With “Block the key at its budget” ticked it stays blocked until you save the limits again | 429 key_daily_budget, or key_budget_blocked, with Retry-After |
| Warn at (percent of budget) | The key is marked in the console and a spend alert is sent | Nothing, requests still pass |
| Requests per minute | Requests over the rate are refused before they reach a model | 429 key_rate_limit with Retry-After |
| Spend per end user (hour, day, 7 or 30 days) | One end user, named in the user field, is refused |
429 end_user_budget |
| Model list | A model outside the list is refused | 403 This token has no access to model |
| Expiry date | The key stops at the end of that day | 401 |
Two details matter for loops. The spend limit and budget apply to any request made with the key, whatever the model, and the check fails closed: the gateway source refuses a request with a 503 when it cannot read the limits, instead of letting it through unchecked. And the requests-per-minute limit turns a loop’s speed into a ceiling. A key set to 10 requests per minute cannot make more than 600 calls an hour, however fast the agent spins. At the calculator’s $0.35 a step that is $210.90 an hour at most.
The gap to know about: these limits are per key and per account, not per run. There is no “this task may spend $2” setting. The practical substitute is to give each job or run its own key with a spend limit and an expiry date, which the docs allow up to 1,000 of. The key-per-project guide walks through the layout, and the post on one key for every model is honest about the trade-off: one key reaching many models is convenient, and the blast radius of that key is your job to bound.
Cap 4: how do daily limits and account caps help?
A key budget protects one key. An account spend cap protects the balance itself. Under Settings, the spend cap takes an amount per day, week or month (UTC) and counts every metered request on the account: every key, the console Playground and the browser chat. Key limits do not apply to the Playground and chat, which use a session and not a key, so the account cap is the control that covers them. At the cap, priced models are refused with 429 account_spend_cap and a Retry-After that counts down to the reset. A cap of $0 switches priced models off for the account without touching the keys. Free models still answer when it is reached. The cap check reads spend from billing records, so the request that crosses the cap still finishes and the total can end slightly above it.
There are two more daily limits built in. The first is the balance: priced use is prepaid, nothing renews or charges on its own, and requests stop when the balance reaches $0. That is a deliberate contrast with the hook-loop report above, where 18 automatic credit reloads kept a loop funded for six days. Paid credit here is added by email, so every top-up is a decision a person makes; our post on why paid access is by email and the guide to prepaid credits set out the trade. The second is the free lane: 48 ids ending in :free share 100 requests and 3,000,000 tokens a day per account, then answer 429 daily_limit_free. At the Hermes job’s 64,241 tokens a call, the token cap would end a loop after about 46 calls. That makes a free id a useful place to develop an agent: a bug costs $0 and the day ends the loop. The free tier comparison lists the other providers’ free limits.
One caveat from the gateway docs: before a request runs, the gateway reserves an estimate of its cost, so a request can be refused while the balance is still positive. Keep some headroom on keys that run long agent sessions, as the errors reference advises.
Cap 5: what should alerts do, and what can they not do?
Alerts tell you. They do not stop anything, and that distinction is the whole lesson of the public reports. The team behind the $47,000 case study is quoted as saying they had observability but not enforcement, and the Vertex post-mortem found that its only cost signal was a daily alert on billing data that is not real time. Alert on spend, but treat it as the fifth cap, not the first.
What exists here, per the gateway source and the console settings: a spend-jump alert, a budget warning at the percentage you set, a “key reached its budget” alert, an optional unused-key alert and a failing-requests alert, plus low-balance alerts by email or webhook. The spend-jump job runs every 5 minutes and fires when the last hour of spend is at least $2 and at least 5 times your average hour over the previous 7 days, or at least $20 in an hour for an account with no recent spend, once per 6 hours. For the calculator’s loop at 269 steps an hour and $0.35 a step, a new account reaches $20 in about 13 minutes. The alert then arrives within the next 5 minute check. The jobs only read; they never block a request. Every limit change also lands on the Security page, and the usage page shows each request with its model, key, tokens and cost, so you can see which key spent it. For a method to compare those records with your own token counts, see the billing audit guide.
Cap 6: what is a real kill switch?
A kill switch is a control that works without asking the agent to cooperate. Four of them are available here, and one you build outside the gateway.
- Disable the key. On the Keys page, Disable stops a key at once and every request answers 401 until you enable it; Revoke deletes it. Disable is the right first move, because it is reversible.
- Set the account cap to $0. Priced models stop for every key on the account. Free models keep answering.
- Expiry dates. A key made for one demo or one job ends by itself. This is the only kill switch that works while you sleep.
- Rotate if it leaked. If the cause is a stolen key and not a loop, the first-hour checklist is in the post on what to do when an API key leaks and the key security guide.
- A wall-clock limit around the process. The Hermes post-mortem notes that a detached background job had no way to be stopped from the keyboard. Wrap scheduled agents in an operating system timeout so a hung job ends whatever the agent does.
# A scheduled job that cannot run longer than 15 minutes, whatever the agent inside it does.
timeout --signal=TERM --kill-after=30s 15m python run_agent.py
# crontab: one key per job, and a wall-clock limit on the process
*/30 * * * * ONEAIAPIKEY_API_KEY="$(cat /etc/agent/curator.key)" timeout --signal=TERM 15m python /srv/agent/curator.pyPut one key on each scheduled job and the kill switch becomes surgical: disable that key and nothing else on the account notices.
Where each cap sits on the path
What does our gateway not do?
Because we publish this post and sell the product it describes, this section is the one to read twice. These are the gaps, from the docs, the console and the source:
- No per-run budget. Limits are per key and per account. Use one key per job.
- No loop detection. The gateway does not read tool calls, compare steps or spot repeats. Spend alerts catch the cost of a loop, not the loop.
- Overshoot. The request that crosses a budget or cap still finishes. Parallel requests and per-end-user spend are counted when their billing record is written, so they can end above the limit.
- Reservation. A request can be refused while the balance is still positive, because a cost estimate is reserved first.
- Per-model and metadata budgets are not live. The Settings page has forms for them, and it says enforcement is off on this gateway. Do not rely on them today.
- The requests-per-minute window lives in the gateway’s memory. A gateway restart empties it.
- Alerts inform, they do not block.
- Status and incidents. What the gateway can and cannot see is on the transparency page, and live checks are on the status page; the post on what an honest status page shows is a way to grade any provider.
Is a gateway better than going direct for this? Sometimes. If your agent talks to a single provider that already offers spend limits you trust, going direct is simpler, and our gateway versus direct API post says so. A gateway earns its place when you use several models and want one set of key limits across them. Whatever you choose, ask the same question of every provider: what is the hard stop, who sets it and how can I test it for free?
How do you test a cap without spending anything?
Do not trust a cap you have not tripped. A request-rate limit can be tested on a free id, which costs $0 and counts against the 100 request daily allowance. Create a key named cap-test under Keys with Requests per minute set to 2, then run the script below. You should see two answers with status 200, then 429 responses with a Retry-After header for the rest. The source and the error reference say the code is key_rate_limit; check the body yourself, since this is a test you run, not a result we are publishing. When it passes, delete the key. The same pattern, with a very small spend budget on a priced model, checks the budget code; paid models are set up by hand, so write to somdutt777@gmail.com if you want to test that path. The free gateway test protocol has seven more checks of the same kind.
export ONEAIAPIKEY_API_KEY="paste-the-cap-test-key-here"
export MODEL_ID="an-id-ending-in-:free" # pick one from the free models page
for i in 1 2 3 4; do
echo "request $i"
curl -s -o /dev/null -D - https://api.oneaiapikey.com/v1/chat/completions \
-H "Authorization: Bearer $ONEAIAPIKEY_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"model\": \"$MODEL_ID\", \"max_tokens\": 20, \"messages\": [{\"role\": \"user\", \"content\": \"Say ok.\"}]}" \
| grep -iE "^(HTTP|retry-after)"
doneWhich cap should you add first?
It depends on how the agent runs.
How does your agent run?
A coding agent in my terminal
A scheduled or headless job
Several agents calling each other
An app with end users
user field and set a spend per end user on the key, so one person cannot spend the key's whole budget. Add the account cap as the outer limit. The cost control guide has the field details.I am still building it
How do the six caps compare for a loop?
The table sorts the caps by what they bound and what each leaves open. Use it to see which gaps you still have after the caps you already run.
| Cap | Bounds | Stops a loop? | Leaves open |
|---|---|---|---|
| 1. Output cap per call | One reply | No | A short-reply loop of any length |
| 2. Step, repeat and deadline checks | One run | Yes, if you code it | A bug inside a tool you do not control |
| 3. Key budget and rate | One key, per period | Yes, after it spends the budget | Everything the key’s budget allows |
| 4. Account cap and balance | The whole account | Yes, at the cap | Spend up to the cap, across all keys |
| 5. Alerts | Nothing, it informs | No | The time between the spike and your reaction |
| 6. Kill switch | One key or the account | Yes, when you act | The time before you notice |
Audit your own setup
Runaway bill checklist
0 of 11 in place
Exposed
One bad night could be expensive. Add the step limit and a key budget first.
What would a loop cost you before a cap fires?
The first calculator showed the cost of a run. This one shows the cost of the time before somebody or something stops it. Enter the cost per step (the first calculator gives an average), how fast the agent runs, how long it goes unattended and the cap you set.
Loop spend with and without a cap
- Spend with no cap
- $1,134.00
- Spend per hour
- $94.50
- Hours until the budget is reached
- 0.21
- Spend with the budget in force
- $20.00
- Most steps an hour the rate limit allows
- 600
- Worst case per hour with the rate limit
- $94.50
Defaults: the 200 step average from the first calculator, 270 calls an hour from the Hermes report, an overnight 12 hours. The real stop is a little above the budget, because the request that crosses it still finishes.
With those defaults an unattended night costs $1,136.48 with no cap and stops near $20 with a budget, which the loop reaches in about 13 minutes. The cap does not make the agent smarter. It makes the worst case a number you chose in advance.
What do we recommend you do today?
- Put a step limit and a repeat check in the agent. It is an afternoon of work and the only cap that sees the loop itself.
- Give each agent or scheduled job its own key, with a spend budget, a requests-per-minute limit and, where the work is temporary, an expiry. Read the key security guide for the rest of key hygiene.
- Set an account spend cap as the outer wall.
- Turn on the spend alerts and send them to a place that is read at night.
- Trip each limit once, on a free id, before you rely on it.
- Run new agents on a free id first. A loop there costs $0.
If you want to try these caps with a real key, the sign-up is a Google login with no card field, the $10 sign-up credit pays for priced models first, and the free ids work at once; pricing lists the steps and the review of what the service gives and does not give is our own plain account. If you want to compare gateways before you choose, the LiteLLM alternatives post and the post on flat-price plan arithmetic show what to ask any seller. For an agent that uses a custom endpoint, the OpenCode provider setup shows the base URL change. If you run a third-party relay’s installer, read the seven installer checks first. When a model is down and your agent keeps retrying, the DeepSeek outage and fallback guide shows how to fail over without a retry storm. To turn token counts into dollars before you run anything, use the cost calculator and the monthly cost estimate guide.
Run your next agent on a key you can cap
$10 sign-up credit, 48 free models sharing 100 requests and 3,000,000 tokens a day, no card.
Frequently asked questions
What causes a runaway AI agent bill?
How do I put a spending limit on an AI agent?
Does max_tokens stop a runaway loop?
What does my agent see when a key budget or account cap is reached?
key_daily_budget, key_budget_blocked or account_spend_cap, plus a Retry-After that counts down to the reset (the error reference lists them). A spend limit that is fully used answers 401 like a disabled key. Treat the budget codes as the end of the run, not as a signal to back off, because retrying cannot help until the period resets or you change the limit.Can the gateway detect that my agent is looping?
How much can a loop cost per hour?
Will the free lane protect me while I build an agent?
:free cost $0 per token and share 100 requests and 3,000,000 tokens a day, so a loop on a free id cannot create a bill and ends with daily_limit_free at the daily cap. It does not protect a production agent on a priced model. The free tier comparison lists the limits.