How to Accurately Calculate and Compare LLM API Costs
Choosing an LLM API channel based on sticker price alone is misleading. This article explains why price lists cannot be compared directly, breaks down the four dimensions of API pricing, and shows how to build a reproducible cost model using weighted input/output ratios, cache hit rates, and currency normalization. It also covers version alignment, price data collection, engineering integration, and common pitfalls, so teams can make model and channel decisions grounded in real usage data rather than assumptions.
1. Why Price Lists Alone Cannot Guide Selection
The same model can cost several times more or less depending on the channel. The intuition that buying directly from the model provider is always cheapest, while intermediaries always cost more, does not consistently hold up under verification. Channel pricing is shaped by procurement costs, volume discounts, operational strategy, caching mechanisms, regional nodes, and promotional cycles—none of which are inherently tied to whether a channel is “official.”
Before selecting a channel, you need a reproducible comparison framework: a consistent method to decompose, calculate, and verify every quote, rather than relying on impressions.
2. The Four Dimensions of API Pricing
A complete pricing scheme typically includes the following four dimensions.
- Input price: billed per input token, covering system prompts, conversation history, retrieved document chunks, and tool outputs.
- Output price: billed per generated token. For most models, the output unit price is significantly higher than the input unit price.
- Cache price: when a request prefix hits the server-side cache, the cached input portion is billed at a lower rate. The higher the cache hit rate, the lower the effective cost.
- Version and tier: within the same model family, flagship, standard, lightweight, and coding-specialized versions differ in both price and capability. Comparisons must align versions first.
Some services also apply tiered pricing based on context length: once the input exceeds a certain threshold, the unit price increases across the board. Verify whether this rule applies to your workload before estimating costs.
3. Common Channel Types and How Their Pricing Works
Pricing logic varies widely across channels, which roughly fall into four categories.
- Direct from the model provider: the most complete billing rules, and new versions typically launch here first, but the selection is limited to that provider’s own product line.
- Cloud provider hosted services: built on the cloud platform’s account system, access control, networking, and audit capabilities, with charges usually consolidated into the cloud bill. Prices may differ across regions, and enterprise customers should also account for contractual discounts.
- Model aggregation platforms: provide a unified interface to multiple model providers, making switching and comparison easier. Common issues include delayed availability of new versions, missing versions, platform markups, and currency conversion effects.
- Independent inference providers: focus on hosting open-source or open-weight models, with pricing often tied to concurrency quotas, dedicated instances, and the inference framework used.
Channel type is only a reference dimension—actual prices still need to be verified one by one.
4. A Unified Cost Calculation Method
4.1 Weighted Unit Price Formula
If the input-to-output ratio of your workload is known, you can use a weighted unit price to express the blended cost per million tokens.
Blended price = input ratio × input unit price + output ratio × output unit price
The input and output ratios should come from real request logs, not estimates. Because tool call results are repeatedly appended to the context, agent-style workloads tend to have a high input ratio. The exact ratio varies by business and can only be determined from actual statistics.
4.2 Factoring in Caching
If a channel offers cache pricing, the effective input price should be weighted by the cache hit rate.
Effective input price = cache hit rate × cache unit price + (1 - cache hit rate) × standard input price
Cache hit rates should likewise be measured from logs and broken down by business module. Modules with fixed system prompts usually achieve high hit rates, while free-form user input can rarely be cached.
4.3 Example Code
The following code demonstrates the calculation flow. The prices shown are illustrative values only and do not represent any real quote.
from dataclasses import dataclassfrom typing import Optional@dataclassclass PriceCard:channel: strinput_per_m: float # price per million input tokens, in a unified currencyoutput_per_m: float # price per million output tokens, in a unified currencycache_per_m: Optional[float] = None # input price on cache hit, None if unavailabledef blended_price(card: PriceCard, input_ratio: float, cache_hit_rate: float = 0.0) -> float:"""Calculate the blended price per million tokens."""input_price = card.input_per_mif card.cache_per_m is not None and cache_hit_rate > 0:input_price = (cache_hit_rate * card.cache_per_m+ (1 - cache_hit_rate) * card.input_per_m)return input_ratio * input_price + (1 - input_ratio) * card.output_per_mcards = [PriceCard("Channel A", input_per_m=10.0, output_per_m=40.0, cache_per_m=1.0),PriceCard("Channel B", input_per_m=8.0, output_per_m=50.0),]INPUT_RATIO = 0.3 # derived from log statisticsCACHE_HIT_RATE = 0.5 # derived from log statisticsresults = sorted(((c.channel, blended_price(c, INPUT_RATIO, CACHE_HIT_RATE)) for c in cards),key=lambda x: x[1],)for name, price in results:print(f"{name}: {price:.2f} units per million tokens")
4.4 Currency Conversion
Cross-border channels are often priced in foreign currencies. Use a fixed exchange rate for conversion and record the rate date. If a price includes tax or platform fees, normalize these factors before converting.
5. Version Alignment and Comparability Checks
Price comparisons are only meaningful under identical conditions. Check the following items one by one.
- Version consistency: flagship and lightweight versions can differ greatly in price and must not be compared against each other.
- Record the collection time: prices may change within weeks, so every conclusion must be labeled with the data’s timestamp.
- Mark missing entries honestly: if a channel has not listed a particular version, mark it as “not available” instead of substituting a similar version, which would distort the comparison.
- Price does not equal capability: two versions at the same price may differ in output quality, long-context performance, and tool-calling stability. Cost comparison should be followed by quality evaluation.
6. Collecting and Verifying Price Data
Reliable price data comes from traceable sources. The recommended collection process is as follows.
- Use the official pricing page or console as the source of truth, and record the URL and collection time.
- Distinguish between regional prices and between tax-inclusive and tax-exclusive prices.
- If a page is rendered by front-end scripts, automated scraping may fail. In that case, take manual screenshots or refer to the provider’s pricing documentation instead.
- Keep original screenshots and page snapshots for later review.
- Re-verify on every version update or on a monthly schedule, and refresh the price table accordingly.
7. Integrating the Pricing Model into Engineering Practice
Pricing information should be part of system configuration, not scattered across business code.
- Externalize configuration: store unit prices, currencies, exchange rate dates, and channel information in configuration files or a config center, so changes do not require a release.
- Instrument usage: for every request, log input tokens, output tokens, and cache-hit tokens, linked to the business module and user.
- Aggregate costs: summarize spending by day, module, and model to identify where costs concentrate.
- Budget alerts: set daily and monthly budget thresholds; trigger alerts near the limit, and throttle or degrade service according to policy when the limit is exceeded.
- Model routing: route simple tasks (such as classification or format conversion) to lightweight models, and reserve flagship models for complex reasoning and code generation. Routing rules should be based on evaluation results, not subjective judgment.
8. Common Pitfalls
Pitfall 1: Assuming official channels are always the cheapest. Pricing strategies differ across channels and must be verified individually.
Pitfall 2: Looking only at input prices. Output tokens usually cost more per unit, and for workloads that generate long content, output is often the dominant cost.
Pitfall 3: Ignoring caching. Long system prompts and fixed knowledge bases can become significantly cheaper when cache hits occur. Excluding caching overestimates costs.
Pitfall 4: Comparing across different versions. When versions are not aligned, price comparisons have no reference value.
Pitfall 5: Ignoring exchange rates and taxes. Foreign-currency quotes and tax-inclusive prices can change the final ranking, so normalize these factors before comparing.
9. Selection Recommendations
Follow these steps to choose models and channels.
- From request logs, measure the input/output ratio, cache hit rate, and average daily call volume.
- Establish a unified pricing baseline covering currency, exchange rate, version, and tax rules.
- Collect prices by channel, retain sources and timestamps, and complete verification.
- Run quality evaluations on real business samples to confirm that lower-cost options meet performance requirements.
- Make a decision based on both cost and quality, and preserve the ability to switch channels so you can adjust quickly when prices change.
By following this process, selection conclusions stay synchronized with business data and market prices, instead of depending on one-time judgment calls.
