How to Calculate True LLM Usage Costs from Logs After Price Changes

    After a large language model (LLM) provider adjusts its pricing, the actual impact on your bill depends heavily on your usage patterns rather than just the unit price. This article explains how to calculate your true usage costs by breaking down token billing items, measuring cache hit rates from logs, and estimating available requests based on your budget. It also provides guidance on choosing the right billing model and implementing engineering strategies to reduce overall LLM costs.

    1. Why Price Changes Alter Model Selection Conclusions

    LLM service pricing typically consists of multiple billing items, including uncached input, output, and, for some providers, context caching. After a price increase, the change in your actual expenditure depends on three factors: call structure, cache hit ratio, and output length.

    A unit price change does not equal a proportional change in your final bill. Two teams looking at the same price list may reach completely different conclusions. For example, programming assistant scenarios that rely on large, repetitive long prefixes are highly sensitive to changes in cache billing. Conversely, short Q&A scenarios are primarily affected by the base unit price.

    Therefore, before selecting a model, you should convert the “price per million tokens” into a “unit task cost.” Only then can different solutions be compared on the same scale.

    2. Breaking Down Cost Composition and Unit Conversion

    2.1 Three Token Billing Items

    • Uncached input: The input content in a request that is not reused by the server. This usually has the highest unit price.
    • Cached input: The portion that matches a historical request prefix and is reused by the server. The unit price is typically lower than uncached input.
    • Output: The content generated by the model. The unit price is usually higher than input.

    The settlement cycle might be daily or monthly. Whether caching is billed separately depends on the provider’s rules. You should always refer to the official terms of service and pricing documentation for the exact definitions.

    2.2 Weighted Cost Formula

    Assume the number of requests in a month is N. The average uncached input tokens per request is a, the average cached input tokens is c, and the average output tokens is o. The three unit prices are pa, pc, and po, all priced per million tokens. The monthly cost can be written as:

    Monthly Cost = N × (a × pa + c × pc + o × po) ÷ 1,000,000

    Dividing by 1,000,000 is necessary because the unit price is quoted per million tokens, while usage is measured by actual token count. Forgetting this step will inflate the result by a million times.

    The key to this formula is that the higher the cache hit ratio, the greater the impact of pc on the total cost.

    2.3 Calculating Monthly Cost with Code

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. uncached_input: float # Uncached input, price per million tokens
    5. cached_input: float # Cached input, price per million tokens
    6. output: float # Output, price per million tokens
    7. @dataclass
    8. class Usage:
    9. requests: int # Monthly requests
    10. avg_uncached_input: int # Average uncached input tokens per request
    11. avg_cached_input: int # Average cached input tokens per request
    12. avg_output: int # Average output tokens per request
    13. def validate(p: Pricing, u: Usage) -> None:
    14. if min(vars(p).values()) < 0 or min(vars(u).values()) < 0:
    15. raise ValueError("Unit prices and usage cannot be negative")
    16. per_request_fields = [
    17. u.avg_uncached_input, u.avg_cached_input, u.avg_output
    18. ]
    19. if max(per_request_fields) > 1_000_000:
    20. raise ValueError("Tokens per request exceed one million, please check for unit errors")
    21. def monthly_cost(p: Pricing, u: Usage) -> float:
    22. validate(p, u)
    23. per_request = (
    24. u.avg_uncached_input * p.uncached_input
    25. + u.avg_cached_input * p.cached_input
    26. + u.avg_output * p.output
    27. ) / 1_000_000
    28. return per_request * u.requests

    The prices in the code should be replaced with the actual values from the pricing documentation. The usage fields should come from real logs rather than rough estimates.

    2.4 Measuring Cache Hit Rate from Logs

    Most server responses include usage information that distinguishes between cached and uncached token counts. The field names vary by provider, but common data points you need to log include:

    • Request time and model name
    • Total input tokens
    • Cached input tokens
    • Output tokens
    • Request success status

    After aggregating this by day, the cache hit rate can be calculated as follows:

    Cache Hit Rate = Cached Input Tokens ÷ Total Input Tokens

    A drop in the hit rate usually indicates that system prompts are changing frequently, or the arrangement order of the context is unstable. Section 5 will explain how to stabilize prefixes.

    3. Usage Estimation and Budget Reverse Calculation

    3.1 Sensitivity to Cache Pricing Changes

    The table below provides a sensitivity analysis based on relative proportions. Assuming the uncached input price is 1, and the baseline cached input price is 0.1, calculating only the input portion:

    Cache Price Change Available Quota at 60% Hit Rate Available Quota at 90% Hit Rate
    No change 100% 100%
    Doubled ~88% ~68%
    Quintupled ~66% ~35%

    The calculation is as follows. At a 90% hit rate and no cache price change, the weighted cost per unit of input is 0.9 × 0.1 + 0.1 × 1 = 0.19. If the cache price quintuples to 0.5, the weighted cost becomes 0.9 × 0.5 + 0.1 × 1 = 0.55. With a fixed budget, the available quota is approximately 0.19 ÷ 0.55, or 35%.

    This shows that high-hit-rate scenarios are the most sensitive to cache billing. Even if the base price remains unchanged, as long as the cache portion price increases, workflows relying on long-context reuse will shrink rapidly.

    This table is only for judging sensitivity. Actual pricing should be based on the provider’s latest pricing terms.

    3.2 Reverse Calculating Available Requests from Budget

    Once the budget is determined, the available number of requests can be estimated as:

    Available Requests = Monthly Budget ÷ Average Cost Per Request

    The number of requests is more intuitive than unit price and is suitable for explaining resource consumption to management.

    It is recommended to perform a worst-case scenario calculation for each solution. For example, assume the monthly budget is halved while the hit rate drops, causing the per-request cost to rise. An example is shown below for demonstration purposes only:

    • Average cost per request is $0.02, monthly budget is $4000, available requests are 200,000.
    • In the worst case, the budget drops to $2000, per-request cost rises to $0.025, and available requests are 80,000.

    If the number of requests in the worst-case scenario can still cover business peaks, the solution carries lower risk.

    4. Choosing a Billing Model: Pay-as-you-go, Packages, and Subscriptions

    4.1 Three Common Models

    • Pay-as-you-go: Costs scale linearly with usage. Highly flexible, suitable for projects with fluctuating call volumes or those still in the exploration phase.
    • Packages: Pay a fixed fee that includes a certain amount of usage. Overage may result in rate limiting, service degradation, or pay-as-you-go top-ups. Suitable for teams with stable and high usage.
    • Subscriptions: Similar to packages but usually auto-renews per cycle. Pay attention to renewal terms and cancellation rules.

    4.2 Break-even Point for Packages

    Assume the package monthly fee is F, and the unit cost for the same usage on pay-as-you-go is p. If the total cost of the package is only F, then the package is more cost-effective when monthly usage exceeds F ÷ p.

    Example: Package monthly fee is $2000, pay-as-you-go unit cost is $0.02 per request, the break-even point is 100,000 requests. If monthly requests exceed this value, the package saves money; if below, pay-as-you-go is better.

    If the package includes a quota of Q, and overage is billed at a top-up price p′, the total cost is:

    Package Total Cost = F + max(0, N − Q) × p′

    Compare this value with the pay-as-you-go cost N × p to find the break-even point. If unused quota is cleared at the end of the cycle, the actual unit cost must be recalculated based on true usage.

    4.3 Package Boundary Checklist

    Before signing, it is recommended to verify the following items:

    • Whether the quota is measured by requests, token count, or duration.
    • Whether overage results in rate limiting, degradation, or pay-as-you-go billing.
    • Whether unused quota is cleared or can be rolled over.
    • Conditions for auto-renewal and the latest deadline for cancellation.
    • Whether there is a notification period before price adjustments, and whether existing users can keep the original price.
    • Whether quotas are universal across different models.
    • Whether rate limit thresholds will affect calls during peak business hours.

    All terms should be subject to the latest content published by the service provider’s official documentation.

    5. Task Tiering and Engineering Cost Reduction

    5.1 Routing by Task Difficulty

    Not all requests require the most powerful model. You can categorize tiers based on task types:

    • Tasks like classification, format conversion, and simple Q&A can be handled by lower-cost models.
    • Tasks like complex reasoning and code generation should be handled by higher-cost models.

    Each tier should have a quality threshold. If the output of a lower-cost model fails to meet the standard, it should automatically fall back to a higher-cost model.

    5.2 Stabilizing Cache Prefixes

    Cache hits rely on prefix consistency. The following practices can help:

    • Keep system prompts fixed and place dynamic content at the end.
    • Avoid inserting timestamps, request IDs, or other frequently changing content into the prefix.
    • Segment long documents in a consistent manner to facilitate reuse.

    5.3 Limiting Output Length

    The unit price for output is usually higher than input, so controlling output length yields obvious cost savings.

    • Set a max_tokens limit for each task type.
    • Require the model to output in a fixed structure to reduce repetitive explanations.