Breakwater

How to estimate what an OpenAI or Anthropic API call will cost before you send it

2 December 2026 · 7 min read

The provider tells you exactly what a call cost, in the usage block of the response, after the money is spent. To stop a call that would blow a budget you need a number before you send it, and that number can only be an estimate. This post builds one from the request itself, with two answers (expected and worst case), shows how cached input changes it, uses it to refuse a call before it leaves your code, and covers where it goes wrong.

The formula

Both OpenAI and Anthropic bill per token, with separate prices for input and output, quoted per million tokens. Many models also have a lower price for input the provider serves from its prompt cache. So one call costs:

cost = (uncached input × input price
      + cached input   × cached-input price
      + output         × output price) / 1,000,000

Prices differ by model and change over time, so this post uses example numbers only: say $3 per million input tokens, $0.30 per million cached input tokens, and $15 per million output tokens. They are not any particular model's prices; take the real ones from your provider's pricing page.

Input tokens from prompt size

Everything you send counts as input: the system prompt, every message in the conversation so far, and the tool definitions. In an agent the conversation grows every turn, and the input term grows with it.

The cheap way to count is to serialise what you send and divide its length in characters by four. It needs no tokenizer and works the same for both providers. It is also only approximate: the ratio of characters to tokens depends on the model's tokenizer and on the text, and prose, source code, punctuation-heavy JSON and other languages can all come out differently. For images and files, base64 length is not a token count. Check the estimate against the usage numbers you get back. For an exact count before sending, use the provider's own token counting where it offers one (Anthropic has a /v1/messages/count_tokens endpoint), at the price of an extra round trip.

Output tokens: the max_tokens worst case

Output is the term you know least about: the answer might be ten tokens or two thousand. What you do know is the ceiling, max_tokens (or max_completion_tokens / max_output_tokens, depending on the API). That gives you two estimates:

If you do not set max_tokens, there is no worst case to compute. Set it on every call you want to budget.

Cached input

When a long, stable prefix (system prompt, tool definitions, a reference document) is served from the provider's prompt cache, those tokens are billed at the cached-input price: a tenth of the input price in our example, which adds up for agents that resend the same prefix every turn. You cannot know for sure before the call how much will hit the cache, so count it in the expected estimate and leave it out of the worst case.

The providers report cached tokens differently, which matters when you compute actual cost. OpenAI's prompt_tokens includes the cached tokens (broken out in prompt_tokens_details.cached_tokens). Anthropic's input_tokens excludes them; cache reads arrive as cache_read_input_tokens and cache writes as cache_creation_input_tokens. Mix those up and you bill cached tokens twice, or not at all.

The estimator

In Python, with no SDK dependency, taking the request body you are about to send:

import json

# Example prices in USD per 1M tokens. Not any real model's prices:
# copy the numbers for the model you call from your provider's pricing page.
PRICE_IN, PRICE_CACHED, PRICE_OUT = 3.00, 0.30, 15.00
CHARS_PER_TOKEN = 4          # rough average; the real ratio depends on tokenizer and text

def input_tokens(req):
    # Everything the provider reads counts: system prompt, messages, tool definitions.
    sent = {k: req.get(k) for k in ("system", "messages", "tools") if k in req}
    return len(json.dumps(sent)) / CHARS_PER_TOKEN

def estimate(req, cached_tokens=0, typical_output=None):
    tin = input_tokens(req)
    max_out = req["max_tokens"]                    # no ceiling, no worst case: always set it
    out = min(typical_output or max_out, max_out)
    cached = min(cached_tokens, tin)
    expected = ((tin - cached) * PRICE_IN + cached * PRICE_CACHED + out * PRICE_OUT) / 1e6
    worst = (tin * PRICE_IN + max_out * PRICE_OUT) / 1e6   # cache miss, full max_tokens
    return expected, worst

Take a request that serialises to about 24,000 characters (about 6,000 tokens), with 5,000 tokens expected from cache, max_tokens of 2,000 and a typical answer of 400 tokens:

expected:   1,000 × $3 + 5,000 × $0.30 + 400 × $15     per 1M  ≈ $0.0105
worst case: 6,000 × $3                 + 2,000 × $15   per 1M  ≈ $0.0480

The worst case is more than four times the expected cost, mostly from 1,600 output tokens the model probably will not write.

Pre-flight: refuse the call that would cross the budget

Keep a running total of actual spend from usage after each call, and before each call check whether this one would push the total past the budget:

class BudgetExceeded(Exception):
    pass

def preflight(req, spent, budget, strict=False, **kw):
    expected, worst = estimate(req, **kw)
    cost = worst if strict else expected
    if spent + cost > budget:
        raise BudgetExceeded(f"this call (~${cost:.4f}) would push spend ${spent:.4f} past ${budget:.2f}")
    return cost

With $1.96 already spent against a $2.00 budget, the request above passes the expected check ($1.96 + $0.0105) and is refused by the strict one ($1.96 + $0.048 is over $2.00). Expected lets more calls through and can end a little over budget; strict never lets one call's worst case cross the line, but refuses some calls that would have fit.

Refuse with an error your agent framework surfaces, not one it retries.

Where estimates go wrong

None of this makes pre-flight checks useless. It makes them a bound with a known margin, which beats an alert after the fact.

How AgentFuse does it

AgentFuse is a hosted proxy that runs this check before it forwards each OpenAI or Anthropic request, against each agent key's monthly, daily and per-run budgets. Concretely:

The same edges apply: a call whose estimate fits but whose real cost crosses the cap, and calls already in flight, are allowed and metered exactly; the key then trips and the next call is refused. For a tighter bound, use strict mode and set max_tokens in your agents. More on keys and per-run budgets in the hard spending cap post.

Let the proxy do the arithmetic

The AgentFuse Free plan includes 3 agent keys. Change a base URL and an API key, set a budget, and calls that would cross it get a 402 instead of a bill.

Launching soon About AgentFuse