LLM API Cost Calculation: How Input, Output, and Caching Are Priced
Understanding how Large Language Model API billing works is crucial for managing development costs. This article breaks down the per-million-token pricing mechanism, explaining the billing rules for standard input, cache hits, and output tokens. It provides a cost estimation formula with Python code examples and explores model selection strategies. Additionally, it outlines practical engineering techniques to reduce API expenditure, such as controlling output length, stabilizing prefixes to maximize cache hit rates, and routing requests based on task complexity.
1. Why Cost Accounting is Based on Millions of Tokens
Large language model services are typically billed by the Token. A Token is the smallest unit of measurement for text processed by the model. In English, a word roughly corresponds to one or two Tokens, while in Chinese, a character usually corresponds to one or two Tokens, depending on the tokenization method. To facilitate comparison, service providers generally quote prices per 1,000,000 Tokens. Developers can then calculate costs by dividing usage by one million and multiplying by the unit price.
Understanding this metric is essential. For a single API call, the longer the input text and the more the model outputs, the higher the cost. Many teams only focus on the base unit price during the early stages of a project, only to find that their monthly bills far exceed expectations after launch. This is usually because they failed to distinguish between input and output, and did not estimate call volumes based on real business traffic.
2. Meaning of the Three Billing Categories
Bills for most general-purpose LLM APIs can be broken down into three parts, each with different optimization directions.
2.1 Standard Input Tokens
Standard input refers to all content in the request that does not hit the cache, including system instructions, conversation history, retrieved materials, and the user’s current question. You must pay for this part on every call; it is the most fundamental cost item.
2.2 Cache Hit Tokens
When the prefix content of multiple requests is the same—such as fixed system instructions, long descriptive documents, or tool definitions—the server can reuse previously computed intermediate results. Service providers typically charge a lower unit price for this portion of the input. The cache price is generally a fraction of the standard input price, with the exact ratio defined by the provider’s rules.
The benefits of caching depend on two conditions. First, the prefix content must be sufficiently stable. Second, the interval between two requests must fall within the cache validity period. If the beginning of the request is modified every time, the cache will almost never hit.
2.3 Output Tokens
Output refers to the content generated by the model, including answers, code, and structured results. Whether the model’s internal reasoning process is counted should be verified in the specific service’s billing documentation. In common pricing structures, the output unit price is significantly higher than the input unit price, often ranging from several times to more than a dozen times higher. Therefore, the longer the output, the faster the cost increases.
This is often underestimated. A task requiring a “detailed explanation” might produce an output ten times longer than a task asking for a “brief conclusion.” Even if the input is identical, the cost per call for these two could differ several times.
3. Establishing a Cost Estimation Formula
The cost of a single call can be estimated using the following formula:
Cost per call = Standard Input Tokens * Standard Input Price / 1,000,000+ Cache Hit Tokens * Cache Price / 1,000,000+ Output Tokens * Output Price / 1,000,000Monthly Cost = Cost per call * Average daily calls * 30
Once wrapped in code, different scenarios can be batch-tested before going live:
def estimate_cost(input_tokens, cached_tokens, output_tokens,input_price, cache_price, output_price):"""Calculate the cost of a single call. All prices are per million tokens."""per_million = 1_000_000return (input_tokens * input_price / per_million+ cached_tokens * cache_price / per_million+ output_tokens * output_price / per_million)def estimate_monthly(per_call_cost, calls_per_day, days=30):"""Estimate total monthly cost based on per-call cost."""return per_call_cost * calls_per_day * days
Before estimating, three metrics must be collected: input size per request, cache hit ratio, and average output length. This data should be derived from actual logs rather than estimated based on experience.
4. A Complete Calculation Using Hypothetical Figures
The unit prices below are entirely fictional and are used solely to demonstrate the calculation process; they do not correspond to any actual product.
Assume a customer service Q&A scenario with the following parameters: Each request contains 10,000 Tokens of fixed instructions and knowledge snippets, of which 8,000 can hit the cache, and the remaining 2,000 are newly added content for that specific call. The model outputs an average of 500 Tokens, with 10,000 calls per day.
Calculated across three hypothetical tiers, with prices in units per million Tokens:
| Tier | Standard Input | Cache Hit | Output |
|---|---|---|---|
| High-end | 10 | 1 | 40 |
| Balanced | 2 | 0.2 | 8 |
| Light | 0.5 | 0.05 | 2 |
Taking the High-end tier as an example, the calculation for a single call is as follows:
- Standard Input: 2000 * 10 / 1,000,000 = 0.02 units
- Cache Hit: 8000 * 1 / 1,000,000 = 0.008 units
- Output: 500 * 40 / 1,000,000 = 0.02 units
- Total per call: 0.048 units
The estimation results for the three tiers are as follows:
| Tier | Cost per Call (units) | Daily Cost (units) | Monthly Cost (units, 30 days) |
|---|---|---|---|
| High-end | 0.048 | 480 | 14400 |
| Balanced | 0.0096 | 96 | 2880 |
| Light | 0.0024 | 24 | 720 |
Two conclusions can be drawn from the results. First, in the High-end tier, output cost accounts for about 42% of the total per-call cost, making output length the primary cost driver. Second, the effect of caching is very significant. If all 10,000 input Tokens were billed at the standard price, the High-end tier’s per-call cost would rise from 0.048 to 0.12 units; caching reduced the cost by roughly 60%.
5. Model Tiering and Selection Strategy
Most service providers offer combinations of models with varying capabilities and prices. When selecting, models can be broadly categorized into three tiers.
- High-end tier: Suitable for multi-step reasoning, complex code generation, and comprehensive long-document analysis. The unit price is the highest, but the cost of failure on difficult tasks may be lower.
- Balanced tier: Suitable for most routine business needs, such as content rewriting, information extraction, and general Q&A. It is usually the most stable choice in terms of cost-effectiveness.
- Light tier: Suitable for high-frequency, low-complexity tasks like classification, keyword extraction, and format conversion. When call volumes are large, the unit price advantage is amplified.
Model selection should not be based solely on unit price. A more effective approach is to run the same batch of real samples across different tiers, record quality metrics (such as accuracy, human evaluation scores) and costs, and then calculate the “cost per valid result.” If a Light tier model meets the accuracy requirements for a specific task, there is no need to pay High-end tier prices for it.
6. Engineering Practices for Reducing Costs
6.1 Control Output Length
Specify the response format and length directly in the prompt, such as “Answer in no more than three bullet points.” Also, set an output Token limit in the request to prevent the model from generating excessively long content under anomalous conditions. Structured outputs (e.g., JSON with fixed fields) can also reduce irrelevant text.
6.2 Stabilize Prefixes to Increase Cache Hit Rates
Place unchanging content (system instructions, knowledge base descriptions, tool definitions) at the beginning of the request, and put content that changes each time (user questions, real-time data) at the end. Avoid embedding dynamic fields like timestamps or request IDs in system instructions; otherwise, the prefix changes every time, invalidating the cache.
6.3 Streamline Input
Regularly clean up redundant conversation history, keeping only the parts relevant to the current question, or compress early conversations into summaries. Knowledge base content should be retrieved as needed rather than dumped entirely into the context.
6.4 Route Based on Task Complexity
Use rules or a lightweight model to determine task difficulty first, routing simple tasks to the Light tier and escalating complex tasks to the High-end tier. The routing logic can be very simple:
def route(task_complexity: str) -> str:routes = {"simple": "light", "normal": "mid", "complex": "high"}return routes.get(task_complexity, "mid")
6.5 Use Batch Processing for Non-Real-Time Tasks
Tasks that do not require an immediate response, such as offline analysis or batch tagging, can be merged into single requests or use batch interfaces provided by the service, which typically offer a lower unit price. The exact pricing for these tasks should be verified against the provider’s current rules.
6.6 Establish Usage Monitoring and Budget Alerts
Log the input Tokens, output Tokens, and cache hits for every call, categorized by model, business line, and functional module, and aggregate the data daily. Set thresholds for daily and monthly costs to trigger alerts when exceeded. The usage fields returned by the API should be used as a basis for reconciliation and checked against bills regularly.
7. Precautions for Billing Details
- Prices are subject to change. The numbers in this article are for illustrative purposes only. Always consult the official prices published by the service provider before making actual decisions.
- Context length may affect unit price. Some services use tiered pricing for extra-long contexts, where the unit price increases after a certain length threshold is exceeded.
- Verification of statistical criteria. Whether internal reasoning processes, definition text for tool calls, or converted results from images or files are counted varies across services.
- Billing modes impact price. Standard calls, batch calls, and other priority modes typically have different unit prices. Choose based on your business’s time-sensitivity requirements.
- Cache validity periods are limited. Once the cache expires, it must be recalculated. In scenarios with low call frequencies, the benefits of caching may be minimal.
8. Conclusion
The cost of LLM APIs consists of three parts: input, cache hits, and output, with output typically carrying the highest unit price and being the most prone to spiraling out of control as business grows. When accounting for costs, first gather the real usage structure, then use a unified formula to estimate monthly costs. During model selection, measure cost-effectiveness by the “cost per valid result” rather than just looking at the unit price. The keys to cost reduction lie in controlling output length, stabilizing request prefixes, streamlining inputs, and routing by task difficulty, all backed by long-term usage monitoring.
