How LLM API Costs Are Calculated: Unit Price, Caching, and Output Length

    LLM API spend is unit price times usage, not the per-token rate alone. This article explains input, output, and cached-token billing, a simple cost-ratio formula, task-based model routing, engineering ways to cut tokens, a sample cost estimator, rollout steps, and metrics to watch.

    Unit Price Is Only Half the Bill

    When teams compare large language model services, they often start with the price per million tokens. Unit price is a core variable, but it determines only part of the bill. Actual spend is unit price multiplied by usage. If either factor changes, total cost changes with it. A cost review should therefore look at unit price, tokens consumed per request, cache hits, and output length together.

    How Billing Is Structured

    Mainstream LLM APIs usually split charges into a few components:

    • Input tokens: the user prompt, system instructions, conversation history, and retrieved material all count.
    • Output tokens: the text the model generates. On most services, the output rate is higher than the input rate.
    • Cached input tokens: when the same prefix is reused and the service supports caching, those tokens are billed at a lower rate.

    Prices and billing rules differ by provider and change over time. Before a project starts, use the latest official price list and store those rates in the cost model’s configuration, not scattered through application code. When prices change, only one place needs to be updated.

    Estimating Total Cost as Price Times Usage

    Let the old plan’s total cost be C0 = P0 × U0 and the new plan’s be C1 = P1 × U1, where P is unit price and U is usage. The ratio is:

    C1 / C0 = (P1 / P0) × (U1 / U0)

    Here is a hypothetical example. If unit price falls by 20% and output tokens per task also fall by 20%, total cost is about 0.8 × 0.8 = 0.64 times the original, a drop of about 36%. This is only arithmetic. Real results depend on how usage is distributed in the actual workload. If input tokens change as well, calculate the input, output, and cache portions separately and then add them.

    Whether both price and usage actually fall must be confirmed by measurement, not inferred from marketing claims.

    Choose Models by Task Tier

    Not every request needs the strongest model. A common engineering pattern is tiered routing:

    • High-complexity tasks, such as multi-step reasoning, long-document synthesis, and complex code refactoring, use a more capable model.
    • Routine tasks, such as classification, information extraction, format conversion, and short rewrites, use a lower-cost model.
    • Requests whose difficulty is unclear can first be scored by a lighter model, which then decides whether to escalate to a stronger one.

    Tiering depends on an evaluation set. Sample real traffic, including normal and abnormal inputs, and record each model’s accuracy, latency, and cost per unit of work. Without that set, claims about cost reduction have no basis.

    Engineering Ways to Lower Cost

    1. Tighten prompts. Remove repeated instructions, put stable system guidance in the prefix, and put dynamic content at the end. A stable prefix improves cache hits.
    2. Limit output length. Specify the answer format and length in the request so the model does not add long explanatory text. Structured output with fixed fields, such as JSON, cuts unrelated content.
    3. Reuse results. For repeated questions or identical inputs, cache results in the application and set a reasonable expiration time.
    4. Control context length. In multi-turn chats, keep only the history that is needed. For long documents, narrow the scope with retrieval or summarization before calling the model.
    5. Batch non-real-time work. Combine requests to reduce call count and make scheduling and rate limits easier to manage.

    Sample Cost Estimation Code

    The functions below estimate the cost of one call and of a month of calls. The prices are sample values for demonstration. Replace them with the latest official rates before use.

    1. def estimate_cost(input_tokens, output_tokens, cached_tokens,
    2. price_in, price_out, price_cached, unit=1_000_000):
    3. """
    4. Estimate the cost of a single call.
    5. price_* is the price per `unit` tokens.
    6. cached_tokens is the number of input tokens served from cache.
    7. """
    8. if cached_tokens > input_tokens:
    9. raise ValueError("cached tokens cannot exceed input tokens")
    10. fresh_input = input_tokens - cached_tokens
    11. cost = (
    12. fresh_input * price_in
    13. + cached_tokens * price_cached
    14. + output_tokens * price_out
    15. ) / unit
    16. return cost
    17. def monthly_cost(per_call_cost, daily_calls, days=30):
    18. """Estimate monthly cost from average daily call volume."""
    19. return per_call_cost * daily_calls * days
    20. if __name__ == "__main__":
    21. per_call = estimate_cost(
    22. input_tokens=3000,
    23. output_tokens=500,
    24. cached_tokens=2000,
    25. price_in=2.0, # sample rate; replace with the latest official price
    26. price_out=8.0,
    27. price_cached=0.5,
    28. )
    29. print(f"Cost per call: {per_call:.6f}")
    30. print(f"10,000 calls per day for 30 days: {monthly_cost(per_call, 10000):.2f}")

    With these inputs, cost per call is 0.007000 and the 30-day cost is 2100.00, in the same units as the prices used. Teams can connect this logic to their logging system and replace the sample token counts with real usage to build a cost curve for the business.

    Rollout Steps and Metrics

    A practical sequence is:

    1. Inventory current call scenarios and group them by task type.
    2. Build an evaluation set for each type and define a quality pass bar.
    3. Compare candidate models on that set for quality, latency, and cost.
    4. Shift a small share of traffic first, and watch cost and quality together.
    5. Set budget-threshold alerts that notify the owner when spend exceeds the limit.

    Track average input and output tokens per request, cache hit rate, cost per task, quality pass rate, P95 latency, and retry count. These metrics can feed the monitoring, alerting, and logging stack already in use. If the workload runs on Baidu AI Cloud, the same existing monitoring setup can cover them.

    Things to Watch

    • Do not rely on unit price or promotional figures alone. Validate results with your own traffic.
    • A lower price does not mean quality improves. Run regression tests before switching models.
    • Cache hits depend on a stable request prefix. Frequent edits to the system prompt reduce the hit rate.
    • Requests that include personal or sensitive data should follow the organization’s compliance rules, and the service terms should be confirmed.
    • Prices, limits, and billing rules change. Review the cost model on a regular schedule so decisions are not based on stale numbers.