LLM API Cost Calculation and Plan Selection: A Practical Guide
Comparing per-million-token prices across LLM API providers often leads to the wrong conclusion. This article breaks down real API cost into cache hit rate, input/output ratio, and time-of-day pricing, shows how each variable can reverse provider rankings, and provides a reusable Python script for replaying real logs. It also explains how to convert subscription plans into equivalent per-token prices and lists engineering actions for reducing cost.
1. Why “Price Comparison” Almost Always Leads to the Wrong Conclusion
In discussions about choosing an LLM API, the most common argument sounds like this: “Provider A charges 0.115 per million cached tokens, Provider B charges 0.05, so A is more than twice as expensive.” The flaw in this reasoning is that the cached-token price is only one component of the bill, and the bill itself is a weighted sum of several components based on usage. When cache hit rate, input/output ratio, and time-of-day distribution all change at the same time, the ranking by unit price and the ranking by total cost can completely reverse.
If we break down where the tokens of a single call go, we can write a general model:
Cost per call = C_hit × H + C_in × (1 - H) × R_in + C_out × R_outwhere:H Cache hit rate (0–1)R_in Non-cached input token shareR_out Output token shareC_hit Cached-token unit priceC_in Regular input unit priceC_out Output unit price
This formula tells us three things. First, the cached-token price only carries decisive weight when H is large. Second, although the output price is high in absolute terms, output usually accounts for a small share of total tokens, so it is easily obscured by the “per million tokens” narrative. Third, any conclusion about which unit price is higher that ignores H and the token mix does not hold.
2. How the Three Key Variables Change the Conclusion
2.1 Cache Hit Rate: The Switch on the Cost Curve
Using the magnitudes from the original example (the numbers are illustrative only, meant to explain the method rather than evaluate any specific service): with a mix of 98% cache hits, 1.5% regular input, and 0.5% output, the cost per 100 million tokens is about 12.57 for the first provider and 9.40 for the second, so the provider with the lower cached-token price wins. Drop the hit rate to 95% with the same mix, and the numbers become about 14.92 and 18.25 — the conclusion completely reverses.
The reason is easy to understand: when the hit rate falls, what gets “amplified” is the regular input portion, and the gap between the two providers’ regular input prices is often larger than the gap in their cached-token prices. So every percentage point drop in hit rate multiplies the cost increase by the input price several times over. The direct engineering implication is this: instead of repeatedly comparing prices between two providers, first push the hit rate from 95% to above 98% — that step usually pays off more than switching providers.
2.2 Input/Output Ratio: The Overlooked Weight
Agent-style applications (multi-turn tool calls, long-context replay) have input far exceeding output, with ratios that can reach 100:1 or higher, while content-generation applications see a clearly larger output share. A change in the ratio changes the weight of each component and therefore changes the ranking. When doing selection calculations, use real business logs to measure the ratio rather than applying an “officially recommended ratio.”
2.3 Time-of-Day Structure: Peak vs. Off-Peak Price Gaps
Many platforms use time-based pricing, with unit prices marked up during peak hours. The key is the difference in how “peak” is defined: some platforms count all working-day hours across the day as peak, while others only count four hours in the evening of working days. For a team that works mainly during the day, a four-hour window means the vast majority of requests fall in the off-peak range; a platform with a wider peak window will charge more of the same workload at a premium. When calculating, intersect the business’s request-time distribution with the platform’s peak definition instead of just looking at the listed price.
3. A Reusable Calculation Script
Turning the model above into code makes it easy to replay real logs:
def cost_per_100m(c_hit, c_in, c_out, hit_rate, in_ratio, out_ratio):"""Return cost per 100 million tokens; unit prices are per million tokens"""total = 1e8hit = total * hit_ratenormal_in = total * in_ratioout = total * out_ratioreturn (c_hit * hit + c_in * normal_in + c_out * out) / 1e6# Illustrative values: A is the high cached-price option, B is the low cached-price optionfor h in (0.98, 0.95, 0.90):a = cost_per_100m(0.115, 2.0, 8.0, h, 0.015, 0.005)b = cost_per_100m(0.05, 3.0, 10.0, h, 0.015, 0.005)print(f"hit={h:.0%} A={a:.2f} B={b:.2f} Winner={'B' if b<a else 'A'}")
It is advisable to collect the three log fields (cached tokens, regular input tokens, output tokens) along with the request timestamp, replay them weekly, and output a cost distribution rather than a single-point estimate.
4. How to Calculate the Equivalent Unit Price of Subscription Plans
The way to evaluate a monthly subscription plan is to “convert it into equivalent API value”: multiply the plan’s stated monthly token quota by the corresponding unit price to get the equivalent amount at original API rates, then divide the actual payment by that amount to get the discount range. In the original case, three plan tiers were equivalent to 160, 955, and 2229 at original API rates, with selling prices of 118, 538, and 1078 — discounts of roughly 50% to 70% of the original price.
This yields three selection rules:
- For teams with stable and predictable usage, the equivalent unit price of a plan is usually better than pay-as-you-go.
- For teams with large usage swings and clear peaks and valleys, pay-as-you-go combined with cache optimization is more controllable.
- A plan’s quota is a “ceiling,” not a guaranteed consumption level; evaluate quota utilization, since idle quota equals sunk cost.
5. Turning Cost Optimization into Engineering Actions
- Put stable prefixes first: place unchanged content such as system prompts, tool definitions, and long documents at the very front of the context to raise the probability of a prefix cache hit.
- Control context jitter: avoid inserting volatile fields such as timestamps and random IDs into the stable prefix; this is a common root cause of a falling hit rate.
- Shave request peaks: schedule deferrable batch jobs into off-peak windows.
- Constrain output: use structured output and length limits to suppress wasted output tokens.
- Observability: build token and cost dashboards in your logging service and monitoring/alerting system, broken down by business line, model, and time period, and establish a weekly review routine.
6. Conclusion
Real cost = cache hit rate × cached-token price + regular input share × input price + output share × output price, then weighted by request time period. Any conclusion that compares only a single unit price is not enough to support a decision. The right path is: first measure hit rate and token mix with real logs, then run a horizontal comparison with a unified model, and finally combine plan discounts and peak definitions for a portfolio selection. If you need managed model services with supporting data and monitoring capabilities, you can run the same calculation against the relevant Baidu AI Cloud product offerings — keeping the calculation basis consistent is what produces reproducible, auditable cost conclusions.
