How to Calculate LLM API Costs and Control Budgets After Price Increases
This article explains how to estimate large language model API costs after pricing changes, covering cache billing rules, a reusable monthly cost formula, model selection trade-offs, a multi-model task allocation strategy, building a routing layer with budget controls, and a checklist for reviewing vendor pricing plans.
When teams use large language model (LLM) APIs, one of the first questions that comes up is how prompt caching is billed. Prompt Cache stores the common prefix that appears repeatedly in requests, such as system prompts, repository context, and few-shot examples. When a new request arrives with a prefix that matches the cached content, the server can reuse the previously computed intermediate results. In this case, the input is typically billed at a lower cached-read rate.
There are several boundary conditions for cache usage. First, the prefix must remain stable; even a single character change will invalidate the rest of the match. Second, cached entries have a time-to-live (TTL); if not accessed within that period, they expire. Third, most providers enforce a minimum prefix length before caching applies. Fourth, rules differ substantially across providers; some charge a cache write fee and others do not. As a result, one provider’s caching behavior should not be assumed to hold in all environments.
Budget changes mainly appear in scenarios where prefix tokens dominate the input. In code analysis, document Q&A, and multi-turn agent tasks, most input tokens are repeated prefixes, so changes in the cached-read price have an amplified effect. The exact increase varies by provider, model, and time, so always refer to the official pricing page rather than relying on multipliers published by others.
Monthly cost can be estimated with the following formula:
Monthly cost = cached-read tokens × cached-read price + non-cached input tokens × input price + output tokens × output price
If the plan also includes cache write fees, cache storage fees, per-request fees, or tiered discounts, add the corresponding items:
Monthly cost = the formula above + cache-write tokens × cache-write price + cache storage cost + request fees − tiered discount
When checking the numbers, confirm whether cache-write tokens are also counted as non-cached input. If they overlap, you may be double-billed.
The following example uses hypothetical values for illustration only; they do not represent any vendor’s actual prices. Assume the input price is 1 yuan per million tokens, the cached-read price is 0.2 yuan per million tokens, and the output price is 4 yuan per million tokens. A team used 100 million input tokens in a month, of which 80 million hit the cache, and generated 5 million output tokens. This example covers token fees only; cache write and storage fees are not included.
- Cached portion: 80 million × 0.2 yuan / million tokens = 16 yuan
- Non-cached input: 20 million × 1 yuan / million tokens = 20 yuan
- Output: 5 million × 4 yuan / million tokens = 20 yuan
- Total: 56 yuan
Both the cache hit rate and the cached-read price affect the result. The table below keeps 100 million input tokens and 5 million output tokens fixed (output cost remains 20 yuan) and varies only the hit rate and cached-read price:
| Cache hit rate | Cached-read price 0.2 yuan | Cached-read price 0.5 yuan | Cached-read price 1 yuan |
|---|---|---|---|
| 50% | 80 yuan | 95 yuan | 120 yuan |
| 80% | 56 yuan | 80 yuan | 120 yuan |
| 95% | 44 yuan | 72.5 yuan | 120 yuan |
A cached-read price of 1 yuan is an extreme illustration. When it equals the input price, cached reads are no cheaper than non-cached reads, and the total stays at 120 yuan regardless of the hit rate. When the cached price approaches the input price, the cost advantage of caching disappears. Teams need to reassess their prefix reuse strategy, such as shortening fixed prefixes, reducing duplicated content loaded repeatedly, or adjusting the context structure.
A drop in the hit rate is also a risk to monitor. If a system prompt is changed or requests arrive less frequently than the cache TTL, the hit rate may fall from 80% to 20%. With the same usage volume, the total would rise from 56 yuan to 104 yuan (cached portion 4 yuan, non-cached input 80 yuan, output 20 yuan). Therefore, teams should track the hit rate continuously before and after launch, rather than reviewing a single bill.
When calculating costs, confirm several definitions: whether cache writes are billed separately, the cache TTL period, the minimum prefix length eligible for caching, and whether expired cache entries are re-billed at the full rate. These conditions determine the real cost; looking only at unit prices can lead to incorrect estimates.
One Model Rarely Balances Both Quality and Cost
A common approach is to switch to a cheaper model. However, model capabilities vary significantly. Some models have weaker reasoning abilities and struggle with complex code refactoring; others may lose track of earlier information in long contexts, producing unstable outputs. These differences cannot be judged from a pricing table alone; they need to be validated with your own evaluation set.
An evaluation set can be constructed from recent production tasks. Sample from the last three months of real tasks and stratify them into simple, medium, and complex categories, with a similar number of samples per category. A total of at least 100 samples is recommended. Each task should have a clear acceptance criterion, such as passing tests, correct formatting, or agreement with a human-annotated reference.
Compare three metrics during evaluation:
- Pass rate: number of tasks that pass acceptance ÷ total number of tasks
- Manual revision count: average number of manual intervention rounds required per task
- Cost per task: total batch cost ÷ total number of tasks, including retry costs after failures
The pass threshold is set by the team’s current baseline. For example, a new model should have a pass rate no lower than 97% of the current model, no more than 1.2 times the baseline manual revision count, and a clearly lower cost per task before switching. Lower unit prices only matter when quality targets are met. Otherwise, the savings will be offset by rework and human review.
How to Split Work Between a Main Model and Sub-Agents
A more reliable approach is to split tasks by complexity and assign them to different tiers of models. The main model handles steps that require strong reasoning, such as solution design and core module modifications. Sub-agents handle high-volume, lower-complexity work such as batch summarization, classification, and candidate test case generation.
The table below outlines a common division of labor.
| Task type | Main model responsibility | Sub-agent responsibility | Quality acceptance metric | Fallback on failure |
|---|---|---|---|---|
| Requirement breakdown and solution design | Produce plan, interface definitions, and risk list | Not involved | Plan passes review; risk items complete | Human review, then main model rewrites |
| Complex code refactoring | Design transformation steps, modify core modules | Execute repetitive replacements, add unit tests | All tests pass; no more than 2 manual revision rounds | Escalate to main model and redo |
| Batch document summarization | Define summary template, revise sampled issues | Generate summaries per document | Sampled accuracy meets agreed threshold; output passes format validation | Retry once on format failure; escalate to main model if still failing |
| Log and ticket classification | Define classification standards, handle edge cases | Classify in batches using the standard | Agreement rate with human labels | Low-confidence samples go to main model |
| Test case generation | Review coverage scope | Generate candidate cases | Coverage rate and number of defects found | Human review after deduplication |
| Final pre-release review | Fully responsible | Not involved | All review checklist items completed | Human takeover |
The rules for assigning work are as follows. A task goes to the main model if any of these conditions is met: it involves architectural decisions or cross-module changes; an error would directly affect production data or users; or the task cannot be verified automatically. Other tasks go to sub-agents, but their outputs must pass structural validation, such as JSON Schema checks. Also set a budget cap for each task to prevent a single looping task from consuming tokens indefinitely.
Model Routing Layer and Vendor Isolation
Business code should not be bound directly to a specific vendor’s API. A better design is to insert a routing layer between the business and the model. Business code only calls a unified interface; the routing layer decides which vendor and model to use based on task type. When a vendor raises prices or imposes rate limits, only the routing configuration needs to change; business code remains untouched.
Each route should include the following fields:
- provider: vendor identifier
- model: model name
- timeout: timeout in seconds
- retry: maximum retry count, with a suggested upper limit
- fallback: fallback vendor and model
- budget_limit: monthly budget cap
A sample configuration is shown below; vendor and model names are placeholders:
routes:reasoning:provider: vendor_amodel: main-largetimeout_s: 120retry: 2fallback: vendor_b/main-largebudget_limit_cny: 5000bulk:provider: vendor_bmodel: light-smalltimeout_s: 30retry: 3fallback: vendor_a/light-smallbudget_limit_cny: 800
Budget breaking can be implemented in two stages. When spending reaches 90% of the budget, send an alert. At 100%, the routing layer automatically stops batch tasks, keeps only production-critical requests, and routes new requests to a lower-cost fallback route.
Retries also add cost. Each retry resends the full context; the longer the context, the more expensive a single failed retry becomes. Therefore, set a cap on retry counts and keep timeout values reasonable to avoid long connection holds that may lead to duplicate charges.
When falling back to another vendor, cached prefixes are not shared across vendors. Existing caches cannot be reused, so cost estimates should be recalculated based on the new vendor’s billing rules.
Checklist for Reviewing Pricing Plans
Before purchasing, normalize all vendor quotes into a single table with consistent fields.
| Field | What to record |
|---|---|
| Model | Specific model name and version |
| Region | Deployment or billing region |
| Input price | Price per million tokens for non-cached input |
| Cache write price | Whether a separate fee applies, and the rate |
| Cached-read price | Price for cache-hit input |
| TTL | Cache validity period, and whether it renews on access |
| Minimum cacheable length | Minimum number of tokens a prefix must have to be cached |
| Validation date | Date the official pricing page was checked |
Also review the contract terms item by item:
- Cache write fee: billed separately? Calculated by write tokens?
- TTL: validity period and renewal rules
- Minimum prefix: Are requests shorter than this length never cached?
- Tiered pricing: Starting point, and whether it is applied retroactively
- Rate limits: RPM and TPM caps, what happens when exceeded, whether requests are queued
- Plan validity: Do unused credits roll over, or do they expire?
- Price change notice: How many days of notice before a price change? Does the old contract retain the old price?
Implementation Steps
- Using the formula above, split the last month’s bill into four categories: cached reads, cache writes, non-cached input, and output.
- Build an evaluation set and compare the current model’s pass rate, manual revision count, and cost per task against candidate models.
- Add a routing layer between the business and the models, and write vendor parameters into the configuration.
- Review each vendor’s plan against the checklist, and only sign once the terms are confirmed.
