An API cost calculator multiplies each usage category by its current rate and the number of calls. Count input, output, cache write, and cache read separately, with every rate in one currency per 1,000,000 tokens. Never silently replace an unknown value with zero. Fill in one baseline request first, then add call count and cache hit rate.
Inputs Required by the Calculator
Prepare seven inputs for a text API:
input_tokens_per_call
output_tokens_per_call
cache_write_tokens_per_miss
cache_read_tokens_per_hit
calls
cache_hit_rate
prices_per_1m_tokens
Want to check the calculator forecast against a real call? You can create a BetterToken account and API key, take current rates from the pricing page, and send one controlled request. Compare the model, status, input, output, applicable cache tokens, and cost in the Dashboard to see which assumptions need to be corrected.
Caching behavior depends on the model and protocol. Before filling cache fields, check the BetterToken API reference, OpenAI Prompt Caching, or Anthropic Prompt Caching.
Universal Formula
Use these variables:
I — ordinary input tokens
O — output tokens
W — cache write / creation tokens
R — cache read / cached tokens
Pi — input price per 1,000,000 tokens
Po — output price per 1,000,000 tokens
Pw — cache write price per 1,000,000 tokens
Pr — cache read price per 1,000,000 tokens
Cost of one call:
C = I / 1_000_000 × Pi
+ O / 1_000_000 × Po
+ W / 1_000_000 × Pw
+ R / 1_000_000 × Pr
+ Cextra
Cextra covers separately billed units such as web search, images, audio, storage, hosted tools, or other operations. Set it to zero only when none apply. If you do not know whether an operation has an extra charge, keep the value unknown and check the documentation; zero would create false precision.
The most common manual mistake is forgetting to divide by one million. When a rate is quoted per 1,000,000 tokens, divide the token count by 1_000_000 before multiplying by the rate.
Copyable Python Calculator
The script contains no prices and no API Key. It asks for values and calculates one scenario. The result uses the same currency as the rates you enter.
from decimal import Decimal, InvalidOperation
MILLION = Decimal("1000000")
def read_decimal(label: str, *, allow_empty: bool = False) -> Decimal:
raw = input(label).strip().replace(",", ".")
if allow_empty and raw == "":
return Decimal("0")
try:
value = Decimal(raw)
except InvalidOperation as exc:
raise SystemExit(f"Invalid number for {label!r}") from exc
if value < 0:
raise SystemExit(f"Negative value is not allowed for {label!r}")
return value
input_tokens = read_decimal("Input tokens per call: ")
output_tokens = read_decimal("Output tokens per call: ")
cache_write_tokens = read_decimal("Cache write tokens per call: ")
cache_read_tokens = read_decimal("Cache read tokens per call: ")
calls = read_decimal("Number of calls: ")
price_input = read_decimal("Input price per 1M tokens: ")
price_output = read_decimal("Output price per 1M tokens: ")
price_cache_write = read_decimal("Cache write price per 1M tokens: ")
price_cache_read = read_decimal("Cache read price per 1M tokens: ")
extra_per_call = read_decimal("Extra cost per call (empty = 0): ", allow_empty=True)
per_call = (
input_tokens / MILLION * price_input
+ output_tokens / MILLION * price_output
+ cache_write_tokens / MILLION * price_cache_write
+ cache_read_tokens / MILLION * price_cache_read
+ extra_per_call
)
total = per_call * calls
print(f"Cost per call: {per_call:.8f}")
print(f"Total cost: {total:.8f}")
Save it as api_cost_calculator.py and run:
python3 api_cost_calculator.py
Do not enter the same token count under cache write or read when the endpoint does not expose those as separate categories. First map its usage into mutually exclusive groups so the same token is not counted twice.
Add Cache Hit Rate
For a request series, separate cache hits from misses:
N — total number of calls
h — cache hit rate from 0 to 1
Nhits — N × h
Nmiss — N - Nhits
Chit — cost of a call with cache read
Cmiss — cost of a miss or cache-write call
Total cost:
Ctotal = Nhits × Chit + Nmiss × Cmiss + Cextra_total
For planning, round Nhits down and Nmiss up to keep the estimate conservative. For an actual ledger, use the observed count of each call type.
Build Three Scenarios
Baseline
Use median input and output from recent tasks, the expected call count, and an observed cache hit rate. If no history exists, label those values as assumptions.
Favorable
Use a stable long prefix, high hit rate, bounded output, and no error retries. It provides a lower bound, not a budget promise.
Adverse
Include cache misses, longer output, one bounded retry, and separately billed tools. Do not inflate every variable arbitrarily; each assumption should correspond to a real process risk.
Record the result in a small sheet:
scenario, calls, hit_rate, input, output, write, read, extra, total
base, ..., ..., ..., ..., ..., ..., ..., ...
low, ..., ..., ..., ..., ..., ..., ..., ...
high, ..., ..., ..., ..., ..., ..., ..., ...
Estimate an Agent Workflow
One visible agent run may include several model calls: planning, tool call, tool result, retry, and final answer. To estimate it:
- run one safe test task;
- count actual API calls;
- group calls by model and usage category;
- apply the formula to each group;
- add tool or search units separately;
- compare the sum with the Dashboard.
Do not multiply one arbitrary call by the user count when request lengths vary widely. Create separate task classes instead: short question, file review, and agent task.
Compare Forecast with Actual Usage
After a test call, match:
- time and request status;
- Model ID;
- input and output tokens;
- cache category;
- number of retries;
- actual charge;
- currency and pricing date.
A difference between forecast and charge usually points to one of four places: the wrong rate, cached tokens counted twice, an unseen retry, or an extra billed operation.
For BetterToken, use the current pricing page, then verify the actual Dashboard record. Do not copy a rate from an old screenshot or article.
Calculator Limits
The formula covers only known categories. It does not predict exchange-rate changes, future pricing, dynamic routing, or agent step count. Image, audio, web search, storage, and some tools may use their own units.
The calculator also does not measure answer quality. A cheaper call that must be repeated manually can increase the cost of the whole task. That requires a separate experiment rather than an invented coefficient.
FAQ
What should I enter when cache is not used?
Enter zero for cache write and cache read only when the endpoint actually did not use cache. Verify an unknown value from usage first.
Which currency does the result use?
The same currency used for every rate and extra_per_call. Do not mix dollars and rubles without an explicit exchange rate and date.
Are cached tokens included in input tokens?
That depends on the API's usage shape. Check its documentation and map fields into mutually exclusive categories to avoid double counting.
How do I calculate a monthly cost?
Calculate one task class first, then multiply it by observed or forecast call count. Use separate rows for different models and task types, then add the totals.
Why is the actual charge higher than the estimate?
Inspect output length, retries, agent steps, cache misses, and additional tools. Match every usage row with the Dashboard instead of comparing only the grand total.