Breakwater

How to put a hard spending cap on OpenAI and Anthropic API calls from AI agents

30 November 2026 · 8 min read

Most teams that run agents have some form of spend alert: a billing threshold email, a dashboard, a Slack message when the daily total crosses a line. None of those stop anything. They tell you how much was spent after it was spent.

The incident everyone in agent ops has heard of makes the point. Four LangChain agents looped for 11 days in November 2025 and produced a $47,000 bill. The post-mortem named two root causes: no per-agent budget caps, and no mechanism to terminate before the next API call (write-up). Gartner reported in March 2026 that only 44% of organisations have financial guardrails for AI spend (summary).

This post covers what a hard cap actually requires, how to build a small one inside your process, where that breaks down, and how to enforce one at a proxy instead.

What "hard cap" has to mean

A cap is hard when the call that would exceed it is never sent. That needs four things:

  1. Identity per agent. One shared provider key means one shared budget. If the research agent loops, the support agent goes down with it, and you cannot tell which one spent the money.
  2. A check before the call. Cost is only known after the response arrives, so the check has to estimate: prompt size plus the maximum output the request allows.
  3. Metering from real usage. After the response, record the actual input, output and cached tokens the provider reports, priced per model.
  4. A state that stays stopped. When the cap is hit, the agent should stay blocked until a person decides otherwise. A cap that resets on the next retry is a speed bump.

Option 1: a guard inside your process

For a single script, a wrapper around the SDK client gets you most of the way. This one uses the OpenAI Python SDK; the Anthropic SDK works the same way with usage.input_tokens and usage.output_tokens.

import json, os, threading
from openai import OpenAI

# Your model's list price in USD per 1M tokens. Keep these next to the model name you deploy.
PRICE_IN = float(os.environ["PRICE_IN_PER_M"])
PRICE_OUT = float(os.environ["PRICE_OUT_PER_M"])

class BudgetExceeded(RuntimeError):
    pass

class CappedClient:
    def __init__(self, cap_usd: float):
        self.client = OpenAI()
        self.cap = cap_usd
        self.spent = 0.0
        self.tripped = False
        self.lock = threading.Lock()

    def _estimate(self, kw) -> float:
        prompt_tokens = len(json.dumps(kw.get("messages", []))) / 4   # rough: ~4 chars per token
        max_out = kw.get("max_tokens") or 1024
        return (prompt_tokens * PRICE_IN + max_out * PRICE_OUT) / 1e6

    def create(self, **kw):
        with self.lock:
            if self.tripped:
                raise BudgetExceeded("tripped; a human must reset this client")
            if self.spent + self._estimate(kw) > self.cap:
                self.tripped = True
                raise BudgetExceeded(f"would exceed ${self.cap} (spent ${self.spent:.4f})")
        r = self.client.chat.completions.create(**kw)
        u = r.usage
        with self.lock:
            self.spent += (u.prompt_tokens * PRICE_IN + u.completion_tokens * PRICE_OUT) / 1e6
        return r

llm = CappedClient(cap_usd=2.00)
reply = llm.create(model=os.environ["AGENT_MODEL"], max_tokens=500,
                   messages=[{"role": "user", "content": "Summarise the open incidents."}])

This is worth having even if you do nothing else. It refuses before sending, it uses real usage afterwards, and it stays tripped. But look at what it does not cover:

All five problems have the same fix: move the check out of the agent and into something every call has to pass through.

Option 2: enforce the cap at a proxy

A proxy that speaks the provider's API holds the real provider keys and hands each agent its own key. Agents change a base URL and an API key; nothing else in their code changes. Because every call passes through one place, the budget survives restarts, is shared across workers, and cannot be skipped.

AgentFuse is a hosted proxy built for this. Sign up and save your OpenAI or Anthropic key in the dashboard; it is stored encrypted and never returned, and your agents never see it.

Create one key per agent, with the budgets that agent should have. The dashboard does this in a form; with your org token it is one API call:

curl -s https://<your AgentFuse URL>/api/keys \
  -H 'authorization: Bearer af_org_...' -H 'content-type: application/json' \
  -d '{"name":"research-agent",
       "policy":{"monthly_budget_usd":50,"daily_budget_usd":5,"per_run_budget_usd":2}}'
# -> {"key":{...},"raw_key":"af_live_...","note":"raw_key is shown once; store it now"}

Point the agent at it. Both official SDKs read these variables:

export OPENAI_BASE_URL=https://<your AgentFuse URL>/openai/v1     OPENAI_API_KEY=af_live_...
export ANTHROPIC_BASE_URL=https://<your AgentFuse URL>/anthropic  ANTHROPIC_API_KEY=af_live_...

Every request is now checked against the key's monthly, daily and per-run budgets before it is forwarded. The estimate uses prompt size and max_tokens, as in the in-process guard. If the call would cross a cap, AgentFuse answers itself with HTTP 402 and the provider never sees the request. After a forwarded call, it meters the real usage (streamed or not, cached tokens included) and, if spend has reached the monthly or daily cap, trips the key so the next call is refused.

Scope a budget to one run

Monthly caps protect the invoice. Per-run caps protect you from one bad task. Send a run ID with each request and the per-run budget applies to that ID only:

from openai import OpenAI, APIStatusError
import os, uuid

client = OpenAI()   # reads OPENAI_BASE_URL and OPENAI_API_KEY
run_id = str(uuid.uuid4())

try:
    r = client.chat.completions.with_raw_response.create(
        model=os.environ["AGENT_MODEL"], max_tokens=500,
        messages=[{"role": "user", "content": "Plan the migration."}],
        extra_headers={"X-AgentFuse-Run": run_id},
    )
    print("cost:", r.headers.get("x-agentfuse-cost-usd"),
          "left this month:", r.headers.get("x-agentfuse-month-remaining-usd"))
except APIStatusError as e:
    if e.status_code == 402:      # budget, loop or tripped breaker
        print("stopped by AgentFuse:", e.message)
    else:
        raise

Here is what that looks like from the proxy's side when a run with a $0.03 budget tries a call after spending $0.0175:

HTTP/1.1 402 Payment Required
{"type":"error","error":{"type":"agentfuse_budget_would_exceed","code":"budget_would_exceed",
 "message":"AgentFuse blocked this request: budget_would_exceed (this call (~$0.0126) would push run spend past $0.03). ...",
 "scope":"run","limit":0.03,"spent":0.0175}}

A different run ID on the same key goes through, because the per-run budget is tracked per ID.

Choosing the numbers

Caps that are too tight get turned off. Start from data:

  1. Run your agents through the proxy for a few days with generous caps. Non-streamed responses carry x-agentfuse-cost-usd, and the dashboard shows spend per key.
  2. Set the per-run cap at a few times the cost of your most expensive normal run. A run that costs ten times the usual is almost always a bug.
  3. Set the daily cap so that one bad day is an annoyance, not a budget meeting.
  4. Set the monthly cap to what you would sign off on without asking anyone.
  5. Turn on alerts (any webhook, Slack included) so you hear about 80% of budget and abnormal burn rate before the cap trips.

What a cap does not do

Be clear about the edges. The pre-flight check is an estimate, so the call that crosses the cap, and any call already in flight at that moment, is allowed and metered exactly; the key trips afterwards. If you need a stricter bound, set "preflight": "strict" on the key to assume every call uses its full max_tokens, and set max_tokens explicitly in your agents. A proxy is also in the request path: if it is unreachable, calls fail rather than go around the budget. That is the point of a hard stop, and it is worth knowing before you rely on one.

Spend caps also do not catch a loop early. An agent repeating itself will burn through its budget before it is stopped. The next post, how runaway agent loops burn budget and how to detect them, covers that.

Try it on one agent

The AgentFuse Free plan includes 3 agent keys and needs no SDK changes. Put your noisiest agent behind it and see what it actually spends per run.

Launching soon About AgentFuse