OverpayingForAIPricing desk
8 min read·Last reviewed for accuracy · 2026-09-11·Prices verified · 2026-09-12

LLM Cost Control for Agents: 5 Guardrails to Limit Spend

Five guardrails that stop an AI agent from spending your month's budget in an afternoon, a priced example of a 200-step runaway loop on each flagship model, and a 30-line Python runner that aborts at a dollar cap.

The article text carries the review date. The rate table below is rebuilt from the live catalogue on every deploy.

Fastest win

Agent cost grows with the square of the step count, because every step re-sends everything before it. A healthy 12-step run on Claude Sonnet 5 costs about $0.39; the same agent stuck in a 200-step loop reads 36.7 million input tokens and costs about $74, and $185 on Claude Opus 5. A per-run dollar budget computed from the usage fields on every response, with a hard step cap, is the only guardrail that scales with the damage.

The short answer on limiting agent spend

A healthy 12-step agent run on Claude Sonnet 5 costs about $0.39. The same agent stuck in a 200-step loop costs about $74, because its context grows 1,800 tokens a step and every step re-sends all of it: 36.7 million input tokens in total. On Claude Opus 5 or GPT-5.5 the same loop is about $185. Five guardrails stop this: max_tokens per call, a step cap per run, an explicit stop condition, a per-run dollar budget computed from the usage fields on every response, and a per-day cap in the vendor console.

The first three are one line each. The fourth is the 30-line runner below. The fifth is a console setting. Do all five, because each catches a failure the others miss.

How runaway loops happen

Agents do not usually fail by producing one huge response. They fail by taking one small, reasonable-looking step over and over. The failure modes we see most often:

  • A tool that returns an error message the model treats as a prompt to try again, with the same arguments, forever
  • A "verify your work" instruction that the model satisfies by re-running the whole task
  • A search tool that returns slightly different results each call, so the model never feels done
  • Two agents handing a task back and forth, each believing the other is responsible for finishing
  • A stop_reason of max_tokens that the loop code treats as "call again" instead of "something is wrong"

None of these look expensive on step 5. They look expensive on step 80, when the context is 147,000 tokens and each step costs more than the first twenty combined. The mechanics of that growth are in [how much an AI agent costs to run](/guides/how-much-does-an-ai-agent-cost-to-run).

What a 200-step loop costs on each flagship

Reference trace: 4,000-token prefix, 500-token task, each step adds a 300-token tool call and a 1,500-token result. Input at step k is 4,500 + 1,800 × (k − 1). Summed over 200 steps: 200 × 4,500 + 1,800 × 19,900 = 36,720,000 input tokens. Output is 200 × 300 = 60,000 tokens. Context at step 200 is 362,700 tokens, which fits a 1M window; a 200K model such as Claude Haiku 4.5 would error out around step 109, which is an accidental guardrail, not a plan.

Model ($/1M in / out)Input costOutput cost200-step totalHealthy 12-step run
Claude Sonnet 5 ($2 / $10)36.72M × $2 = $73.4460,000 × $10 = $0.60$74.04$0.39
Claude Opus 5 ($5 / $25)36.72M × $5 = $183.6060,000 × $25 = $1.50$185.10$0.98
GPT-5.4 ($2.50 / $15)36.72M × $2.50 = $91.8060,000 × $15 = $0.90$92.70$0.50
GPT-5.5 ($5 / $30)36.72M × $5 = $183.6060,000 × $30 = $1.80$185.40$1.01
Gemini 3.1 Pro ($2 / $12)36.72M × $2 = $73.4460,000 × $12 = $0.72$74.16$0.40
Gemini 3.8 Flash ($0.75 / $3.75)36.72M × $0.75 = $27.5460,000 × $3.75 = $0.23$27.77$0.15
DeepSeek V4 Flash ($0.05 / $0.16)36.72M × $0.05 = $1.8460,000 × $0.16 = $0.01$1.85$0.009

Seventeen times the steps, roughly 190 times the cost. With prompt caching (cache reads at roughly 10% of list, writes at roughly 125% on Anthropic), the Sonnet 5 loop becomes 362,700 × $2.50 + 36,357,300 × $0.20 + $0.60 = about $8.78. Caching is worth having, as [prompt caching for AI agents](/guides/prompt-caching-for-ai-agents) shows, but 22 times a healthy run is still a bill you notice.

The five guardrails

1. max_tokens per call. Size it for the step, not the model's ceiling. A tool-calling step needs 512 to 2,048 tokens; a final report might need 4,000. One runaway 32,000-token response on Opus 5 is 32,000 × $25 = $0.80 by itself, and it then sits in context for every later step.

2. Max steps per run. Pick a number from your traces: the p95 of successful runs plus a margin. For most tool loops that is 15 to 30. A run that hits the cap should fail loudly, not silently return whatever it had.

3. An explicit stop condition. Give the model a finish or report tool and end the loop when it is called or when stop_reason is end_turn. Also detect degenerate progress: the same tool called with the same arguments twice in a row is a loop, and the run should abort.

4. A per-run USD budget from usage. Every response reports input, cached and output tokens. Multiply by the model's rates, accumulate, and abort when the total passes the cap. This is the only guardrail whose threshold is in the unit you actually care about.

5. A per-day account cap in the vendor console. Anthropic and OpenAI let you set spend limits per workspace or project with alerts; Google Cloud budgets alert and can be wired to stop spend. This is the backstop for the bug you have not thought of yet.

What retries and backoff cost

SDK clients retry rate limits and server errors by default, usually two or three attempts with exponential backoff. A rejected request is generally not billed, but a request that times out after generation has started often is, and an application-level retry of a step re-sends the whole context again.

At step 100 of the reference loop the context is 4,500 + 99 × 1,800 = 182,700 tokens. One attempt on Sonnet 5 uncached is 182,700 × $2 = $0.37; three attempts are $1.10 for zero progress. Cached, each attempt is roughly $0.04. Two rules follow: keep the SDK's retry count, never wrap it in your own retry loop, and if you must retry a failed run from scratch, count it against the same per-run budget rather than starting a fresh one.

A BudgetedRunner in 30 lines

This Python runner drives a Claude tool loop and stops when either the dollar cap or the step cap is hit. The same shape works on OpenAI with responses.create and usage.input_tokens_details.cached_tokens.

from anthropic import Anthropic

PRICES = {"claude-sonnet-5": (2.0, 2.5, 0.2, 10.0)}  # $/1M: input, cache write, cache read, output

class BudgetedRunner:
    def __init__(self, model, system, tools, budget_usd, max_steps=25):
        self.client, self.model, self.system, self.tools = Anthropic(), model, system, tools
        self.budget, self.max_steps, self.spent = budget_usd, max_steps, 0.0

    def cost(self, u):
        i, w, r, o = PRICES[self.model]
        return (u.input_tokens * i + (u.cache_creation_input_tokens or 0) * w
                + (u.cache_read_input_tokens or 0) * r + u.output_tokens * o) / 1e6

    def run(self, messages, execute_tool):
        for step in range(1, self.max_steps + 1):
            resp = self.client.messages.create(model=self.model, max_tokens=1024,
                system=self.system, tools=self.tools, messages=messages)
            self.spent += self.cost(resp.usage)   # e.g. 24,300 in × $2 + 300 out × $10 = $0.052
            if self.spent > self.budget:
                raise RuntimeError(f"budget ${self.budget} exceeded at step {step}: ${self.spent:.3f}")
            messages.append({"role": "assistant", "content": resp.content})
            if resp.stop_reason != "tool_use":
                return resp, self.spent
            results = [{"type": "tool_result", "tool_use_id": b.id,
                        "content": execute_tool(b.name, b.input)}
                       for b in resp.content if b.type == "tool_use"]
            messages.append({"role": "user", "content": results})
        raise RuntimeError(f"step cap {self.max_steps} hit after ${self.spent:.3f}")

Set budget_usd from your traces: three times the median successful run is a reasonable start. For the Sonnet 5 reference run that is about $1.20, which the 200-step loop would hit at step 24, roughly $73 before the console would notice.

How to alert before the bill arrives

A budget stops one run. Alerting tells you that runs have started needing it.

  • Log cost per run, not per call, with the model, step count and stop reason
  • Tag every run with the feature or customer that triggered it, so a spike has an owner
  • Alert on the p99 cost per run and on the share of runs that hit the step cap or the budget; both climbing together means a new failure mode, not a busy day
  • Reconcile weekly against the vendor's usage report, because a runner bug that under-counts tokens is itself a runaway

If you route through OpenRouter, per-key credit limits give you a second, vendor-independent cap; the trade-offs are in [OpenRouter vs direct API](/compare/openrouter-vs-direct-api).

Cheapest model that still does this, and when to pay for the flagship

Guardrails bound the damage; model choice sets the slope. For a well-specified loop, DeepSeek V4 Flash ($0.05 / $0.16) turns the 200-step disaster into a $1.85 annoyance and Gemini 3.8 Flash ($0.75 / $3.75) into $28. In our experience both are reliable at structured tool calls when the task is clear, and the [Gemini agent API cost](/guides/gemini-agent-api-cost) article covers the Gemini side.

Pay for Claude Sonnet 5, GPT-5.4 or a flagship when the task is ambiguous or the loop is long, because those are the runs where a cheap model is most likely to wander and wandering is what the table above prices. Whatever you pick, the runner above works unchanged; only the PRICES row differs. Price your own trace in the [calculator](/calculator), and see [Claude agent API cost](/guides/claude-agent-api-cost) for the per-vendor usage fields.

Key Takeaways

  • A 200-step loop is 36.7M input tokens: $74 on Claude Sonnet 5, $93 on GPT-5.4, $185 on Opus 5 and GPT-5.5, $28 on Gemini 3.8 Flash, $1.85 on DeepSeek V4 Flash
  • That is roughly 190 times the cost of the healthy 12-step run, from 17 times the steps; cost is quadratic in steps
  • Five guardrails: max_tokens per call, max steps per run, an explicit stop condition, a per-run USD budget from usage, and a per-day cap in the vendor console
  • A retry at step 100 re-sends about 183K tokens: $0.37 per attempt on Sonnet 5 uncached, roughly $0.04 cached
  • Prompt caching cuts the 200-step disaster to about $8.78 on Sonnet 5, still 22 times a healthy run
  • Log cost per run and tag runs by feature; a p99 that jumps is your first warning

Editorial context

Who is this for?

Developers and platform teams running tool-calling agents in production who need a spend ceiling that holds when a run goes wrong.

When NOT to use this

One-off scripts and notebooks where a human is watching every step; the guardrails still help, but the per-run budget is overkill.

Pricing insights

The same agent costs $0.39 for 12 steps and $74 for 200 steps on Claude Sonnet 5, because every step re-sends the growing context.

Alternatives to consider

Vendor-side workspace limits, OpenRouter per-key credit limits, and a cheaper loop model all reduce exposure but none replaces a per-run budget.

Final verdict

Put a dollar cap on every run before you put the agent in front of users. It is 30 lines of code and it is the difference between a $0.39 run and a $74 one.

Frequently Asked Questions

How do I limit how much an AI agent can spend?

Use five controls together: max_tokens on every call, a maximum step count per run, an explicit stop condition the model can trigger, a per-run dollar budget computed from the usage object on each response, and a daily or monthly cap in the vendor console. The per-run budget is the one that actually tracks damage, because agent cost grows with the square of the step count.

What does a runaway agent loop cost?

A 200-step loop with a 4,500-token starting context that grows 1,800 tokens per step reads about 36.7 million input tokens. That is roughly $74 on Claude Sonnet 5, $93 on GPT-5.4, $185 on Claude Opus 5 or GPT-5.5, $28 on Gemini 3.8 Flash and $1.85 on DeepSeek V4 Flash. A healthy 12-step run of the same agent is about $0.39 on Sonnet 5.

How do I compute cost per run from the API response?

Every response carries a usage object. On Anthropic multiply input_tokens, cache_creation_input_tokens, cache_read_input_tokens and output_tokens by their per-million rates; on OpenAI use input_tokens, input_tokens_details.cached_tokens and output_tokens; on Gemini use usage_metadata. Sum it across the loop and abort when the total passes your cap.

Do retries cost money?

A request rejected with a rate-limit error is generally not billed, but a request that times out after the model has started generating usually is, and an application-level retry of a whole step re-sends the entire context. At step 100 of the reference loop that is about 183,000 tokens, roughly $0.37 per attempt on Claude Sonnet 5 uncached. Set the SDK retry count deliberately and never wrap it in another retry loop.

Can I set a hard spend limit in the vendor console?

Yes, with differences. Anthropic and OpenAI both let you set spend limits per workspace or project with alert thresholds, and requests fail once a hard limit is reached. Google Cloud budgets alert by default and need extra configuration to stop spend. Treat the console cap as the last line, not the first, because it stops every run, not the one that is misbehaving.

Does prompt caching protect me from runaway loops?

It softens them. With cache reads at roughly 10% of list, the 200-step Claude Sonnet 5 loop drops from about $74 to about $8.78. That is still 22 times a healthy run, so caching is a cost optimisation, not a guardrail. Keep the step cap and the dollar budget regardless.

Related

Free courses · no sign-up

Still deciding? Learn the basics first, then come back to the prices.

If our calculators helped you cut down on hidden AI wallet leaks, thanks for using them. A tiny fraction of your savings is what keeps our pricing indexes updated daily.

Not sure which AI is cheapest for your use case? Find out in 30 seconds — no signup required.

AI cost intelligence

Stop overpaying for AI tools

Join the OverpayingForAI list for pricing updates, cheaper alternatives, and practical buying guidance.

Now tracking 50+ AI tools, models, platforms, subscriptions, coding tools, and automation products.

We use your email only for OverpayingForAI updates. Unsubscribe anytime.