How to Calculate the True Cost of LLM APIs: A Practical Guide

    Choosing an LLM API by its headline input price per million tokens is a common and costly mistake. Real bills combine three charges—cached reads, uncached input, and output—which can differ by several times, with output usually the most expensive. This article formalizes that three-part billing model, shows how to derive a comparable effective price per million tokens, and explains why the cache hit rate is the only variable that genuinely needs forecasting. It also covers tiered and time-based pricing, how to build a trustworthy cost ranking, and how to add quota, routing, and observability guardrails to control actual spend. Readers get calculation formulas, code examples, and a diagnostic order for investigating cost spikes.

    1. The Problem: Why the Lowest Listed Price Often Costs More

    When evaluating LLM APIs, the most common mistake is comparing only the “input price per million tokens” from a single price sheet. A real bill has three components: cached tokens that are read, uncached input tokens, and model output. Their unit prices often differ by several times, and output is usually the most expensive—yet the share of each component varies enormously across workloads.

    This creates a familiar paradox: the model with the lowest listed price can actually be cheaper for long-context, high-reuse workloads, while a mid-priced model can produce a surprisingly large bill for short prompts with long outputs.

    So the first step in cost accounting is not looking at prices, but defining the unit of measurement. Only once that is fixed does a side-by-side comparison mean anything.

    2. Formalizing the Three-Part Billing Model

    Suppose a request has the following token composition:

    • H: tokens that hit the cache and are read, billed at the read price;
    • M: input tokens that miss the cache, billed at the input price;
    • O: output tokens, billed at the output price.

    Let the unit prices be p_read, p_in, and p_out (in CNY per million tokens). The cost of a single request is:

    1. cost = (H * p_read + M * p_in + O * p_out) / 1_000_000

    From this we get the request’s effective unit price (the actual average per million tokens):

    1. p_eff = (H * p_read + M * p_in + O * p_out) / (H + M + O)

    This p_eff is the number you can actually compare across models. The p_in on the price sheet is only an upper bound; the two are equal only when the hit rate is zero.

    3. Hit Rate: The Only Variable Worth Forecasting

    The three prices are set by the vendor and the token volumes by your workload. The only thing that requires engineering judgment is the hit rate r = H / (H + M). Substituting it gives a formula that is handy for quick estimates:

    1. p_eff = (1 - h) * [ (1 - r) * p_in + r * p_read ] + h * p_out
    2. where h = O / (H + M + O) is the output share

    This decomposition is very useful: it splits the bill into an input-side cost and an output-side cost. The former falls linearly with the hit rate; the latter is completely unaffected by caching. For output-heavy tasks (code generation, long-form writing, large JSON payloads after structured extraction), cache optimization has limited payoff and you should prioritize shortening the output. For input-heavy tasks (long-document QA, repository-level code understanding, multi-turn conversations), raising the hit rate is the most effective way to cut cost.

    The hit rate is not a matter of luck. It depends on three things: whether the prefix is stable, whether the cache lifetime covers the reuse interval, and whether concurrency fragments the cache. The reliable engineering practice is to put invariant content first: system prompts, tool definitions, few-shot examples, and the body of long documents at the very front of the prompt, with the user input, timestamps, and random IDs that change over time at the end. Because prefix caching matches on the longest common prefix, any change early on degrades everything after it to a miss.

    1. # Bad example: volatile content first, hit rate approaches 0
    2. [timestamp][user ID][long document][fixed system prompt]
    3. # Good example: stable content first, hit rate rises with reuse
    4. [fixed system prompt][tool definitions][long document][timestamp][user ID][current question]

    4. Tiers and Time Windows: Putting Stepped Pricing into the Model

    Real price sheets are rarely a single number. They are tiered: one unit price applies when the context length is at or below a threshold and another above it; peak hours and off-peak hours have different prices; and different response-speed tiers (standard vs. high-speed) are priced separately. The calculation must express these tiers as conditional functions rather than picking a representative value:

    1. def unit_price(ctx_len, tier, peak):
    2. # Tiered input price (CNY per million tokens), illustrative structure
    3. base = 4.20 if ctx_len <= 256_000 else 6.00
    4. if peak:
    5. base *= 1.25 # peak-hour multiplier, illustrative
    6. if tier == "highspeed":
    7. base *= 1.50 # speed-tier multiplier, illustrative
    8. return base

    The key point: the tier is determined by the total context length of the current request, not by a historical average. This means a few very long requests can pull up the average price of the whole batch, so capacity planning should model percentiles (P50/P95) rather than the mean.

    5. How to Build a Comparable Ranking

    The source material presents a leaderboard sorted by effective unit price, which also includes entries marked “reference price unverified, not ranked.” That detail shows exactly why ranking methodology matters. A credible leaderboard must state at least four things:

    1. A unified workload profile: every candidate model runs under the same (h, r) assumptions, for example 30% output share and a 60% hit rate;
    2. A unified unit of measurement: all four segments—read, input, output—are converted into an effective unit price, with the original four prices retained for reference;
    3. A data-completeness threshold: if any segment’s price is missing, the entry is flagged as “not comparable” and listed separately rather than filled with 0 or an average;
    4. Reproducibility: provide the calculation script and the version of the input data so the conclusions can be audited.

    Illustrative implementation:

    1. def effective_price(p_in, p_read, p_out, h=0.30, r=0.60):
    2. if None in (p_in, p_read, p_out):
    3. return None # not comparable, excluded from ranking
    4. return (1 - h) * ((1 - r) * p_in + r * p_read) + h * p_out
    5. rows = [
    6. ("Candidate A", 1.09, 0.11, 3.28),
    7. ("Candidate B", 1.31, 0.13, 3.94),
    8. ("Candidate C", None, None, None), # reference price unverified
    9. ]
    10. ranked = sorted(
    11. [(n, effective_price(i, rd, o)) for n, i, rd, o in rows if effective_price(i, rd, o)],
    12. key=lambda x: x[1],
    13. )

    6. From Unit Price to Bill: Building Budget Guardrails

    The effective unit price answers “which one to pick.” Controlling “how much we spend” requires three more layers of guardrails:

    • Quota layer: set daily/monthly token budgets per business line, metering input, output, and cache reads separately so a total volume figure cannot hide a structural imbalance;
    • Routing layer: classify requests by difficulty, send simple ones to a low-cost model and escalate complex ones, with routing thresholds calibrated on an offline evaluation set;
    • Observability layer: log the three token counts and the hit flag for every request, and use monitoring and alerting to detect anomalies in sudden shifts of p_eff—a sudden rise in p_eff usually means the cache stopped working or the prompt structure was changed, not that prices were adjusted.

    A practical diagnostic order: first check whether p_eff has deviated from the baseline, then break it down into h (output share) and r (hit rate) to locate the cause, and only then suspect a price change.

    7. Common Pitfalls

    • Multiplying the input price by total tokens, ignoring the fact that output is more expensive;
    • Treating cache hits as free, when the read price is low but still billed;
    • Using the average context length to determine the tier, which systematically underestimates the budget;
    • Comparing different models under different workload profiles, making the conclusion non-transferable;
    • Filling missing prices with 0, which disguises non-comparable entries as the cheapest option.

    8. Summary

    The core of cost accounting is turning the price sheet into a reproducible calculation model: substitute the four prices individually, treat output share and hit rate as explicit variables, express tiers and time windows as conditional functions, and mark missing data as not comparable. With those four things in place, the selection discussion can move from “whose listed price is lower” to “whose effective cost is lower under my workload”—and that conclusion can be re-run by a script and verified against the bill.