Estimating LLM API Costs: Key Variables in Pricing Structures

    This article explores the key variables that impact Large Language Model (LLM) API billing, moving beyond simple unit price comparisons. It covers basic cost formulas, tiered and time-based pricing, caching mechanisms, and non-core fees. A reusable Python script is provided to demonstrate how to explicitly encode billing rules for accurate cost estimation and informed decision-making.

    1. Why Comparing Unit Prices Alone is Inconclusive

    LLM API bills are determined by multiple variables. Even if two APIs list the same price “per million tokens,” actual costs can vary by several folds. Reasons include differing input-to-output ratios, varying numbers of reasoning tokens consumed for the same task, different tokenization methods yielding different token counts for the same text, and whether cache hits occur.

    Therefore, before comparing, you must standardize the metrics: the same task, the same token usage, and the same billing conditions. Only when these conditions are fixed does the unit price difference become meaningful.

    2. Basic Cost Formula

    The cost of a single request can be expressed as:

    Cost = Input Tokens × Input Price ÷ 1,000,000 + Output Tokens × Output Price ÷ 1,000,000

    The output price is typically higher than the input price. If a “thinking mode” (or reasoning mode) is enabled, the reasoning content generated before the final answer is also billed as output. When calculating output tokens, you must combine the thinking portion with the final answer; otherwise, you will systematically underestimate the cost.

    3. Tiered Pricing: Input Length Determines Applicable Unit Price

    Some services divide pricing tiers based on the input length of a single request, applying different unit prices to different tiers. Before estimating, you need to confirm two rules:

    1. Once a threshold is exceeded, is the entire request billed at the higher tier, or only the excess portion?
    2. Which tier does the exact threshold boundary value fall into?

    The difference between these rules becomes very apparent in long-document scenarios. It is recommended to explicitly encode threshold rules in your estimation script rather than using an average price across tiers.

    4. Time-Based Pricing and Load Fluctuations

    Some services offer time-based pricing, such as applying a higher unit price during specific peak hours on weekdays and a lower price during off-peak times. If your traffic is concentrated during peak hours, estimating based on a 24-hour average will result in an underestimation.

    When estimating, you should categorize requests by timestamp into their respective time slots and accumulate costs separately. Holiday schedules and timezone conversions must also be factored into the rules to avoid cross-timezone calculation errors.

    5. Cache Writes and Hits

    Long-context applications often repeatedly send the same system prompts or document prefixes. Server-side caching can reduce the billing for these repeated prefixes, but writing to the cache itself may incur costs. The write price varies by service—sometimes matching the standard input price, other times exceeding it. The cache validity period (TTL) also affects the hit rate.

    When estimating, separately account for write volumes and hit volumes to avoid double counting or missing fees.

    6. Isolating Non-Core Fees

    Extra features like batch APIs, free quotas, promotional discounts, web search, and document parsing tools will all alter the final bill. When making horizontal comparisons, you should first exclude these variables using a standardized rule, retaining only the base API call cost. Retry counts and manual processing costs should be listed as separate parameters and not mixed into the unit price comparison.

    7. Reusable Estimation Script

    The example below demonstrates how to encode the rules mentioned above. The thresholds and unit prices in the example are for illustration only; replace them with actual data from the official documentation when using it.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Tier:
    4. max_input: int # Maximum input limit per request for this tier, in tokens
    5. input_price: float # Price per million tokens for input
    6. output_price: float # Price per million tokens for output
    7. def request_cost(input_tokens: int, output_tokens: int, tiers: list[Tier]) -> float:
    8. # The entire request is billed according to the matched tier.
    9. # Tiers must be sorted in ascending order by their max_input limit.
    10. for tier in sorted(tiers, key=lambda t: t.max_input):
    11. if input_tokens <= tier.max_input:
    12. cost = input_tokens * tier.input_price + output_tokens * tier.output_price
    13. return cost / 1_000_000
    14. raise ValueError("Input exceeds the maximum limit of the highest tier")
    15. # Example data, not real prices for any service
    16. tiers = [
    17. Tier(max_input=128_000, input_price=1.0, output_price=8.0),
    18. Tier(max_input=256_000, input_price=2.0, output_price=16.0),
    19. ]
    20. print(round(request_cost(100_000, 20_000, tiers), 4)) # 0.26

    The key to this script is the explicit definition of rules. Tiers, time slots, cache, and extra fees are each treated as parameters, making it easy to repeatedly estimate the same set of tasks and quickly update results after price adjustments.

    8. Conclusion and Practical Recommendations

    When selecting a model, follow this sequence:

    1. Analyze the typical input and output length distribution of your tasks.
    2. Calculate the cost of a single request using standardized metrics.
    3. Apply time-based, tiered, and caching rules to obtain a monthly estimate.
    4. Validate the fluctuation range of reasoning tokens using real business samples.

    Unit price is just one input to the cost model. A comprehensive estimation must consider the pricing structure, usage characteristics, and business load simultaneously to support decision-making. For specific prices and rules, please refer to the official billing documentation of each service provider, such as the official billing documentation of Baidu AI Cloud.