Understanding LLM Inference Costs: Pricing, Caching, and Model Selection in Practice

    This article breaks down the real cost drivers of large language model (LLM) API usage beyond per-million-token list prices. It explains how input, cached, output, and reasoning tokens affect your bill, how to build a per-request cost model, and how tiered pricing and long-context usage can create unexpected spikes. It also covers the hidden overhead of reasoning-capable models, ways to compare models based on cost per successful task rather than raw price, and how to evaluate accuracy and hallucination rates on your own data.

    Why Identical Unit Prices Produce Different Bills

    Most LLM API pricing pages show only two numbers: the price per million input tokens and the price per million output tokens. Many teams compare these two figures when choosing a model, only to see actual bills diverge significantly from expectations after launch. The reason is that the real cost of a single request is determined by several interacting factors:

    • Input tokens: system prompts, conversation history, retrieved document chunks, and tool outputs.
    • Cached tokens: input tokens that hit a server-side cache often have a lower unit price, while writing new entries into the cache may incur separate charges.
    • Output tokens: the visible content generated by the model.
    • Reasoning tokens: for models with reasoning capability, internal chain-of-thought tokens produced before the final answer. These are usually billed at the output rate, but not all of them are visible to the user.
    • Tool-call overhead: tool definitions, call arguments, and returned results all consume input tokens. As the number of tool invocations grows, the input size can expand accordingly.

    Therefore, evaluating cost requires considering unit prices, actual usage volumes, and the structure of each request. Looking only at advertised prices does not tell you what a real workload will cost.

    Building a Per-Request Cost Model

    The core of a cost model is breaking each request into billable components. The sample below uses placeholder unit prices only to illustrate the calculation method; they do not represent any product’s real pricing.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # price per million non-cached input tokens (USD)
    5. cached_per_m: float # price per million cached input tokens (USD)
    6. output_per_m: float # price per million output tokens (USD, includes reasoning tokens)
    7. def request_cost(p: Pricing, input_tokens: int, cached_tokens: int,
    8. output_tokens: int, reasoning_tokens: int = 0) -> float:
    9. fresh = input_tokens - cached_tokens
    10. return (
    11. fresh * p.input_per_m
    12. + cached_tokens * p.cached_per_m
    13. + (output_tokens + reasoning_tokens) * p.output_per_m
    14. ) / 1_000_000

    When calculating, you should take the token counts (input, cached, output, reasoning) directly from the usage fields in the API response. Do not use character counts or local tokenizers to estimate them roughly. Record these fields for every request and reconcile them with the monthly bill. If reconciliation shows discrepancies, it usually points to problems with cache policy, retry logic, or prompt concatenation.

    Tiered Pricing and Long-Context Risks

    Some services segment pricing by the input length of a single request. A common pattern is: if the input stays below a threshold, the base unit price applies; once the input exceeds that threshold, the entire request is billed at a higher rate — sometimes the output rate also increases. The key risk is that such pricing is not linear. The moment the input length crosses the threshold, the cost of a single request can jump noticeably.

    To mitigate this risk, consider the following measures:

    1. Set a per-request input token cap at the gateway layer, triggering truncation or summarization when exceeded.
    2. For long documents, use retrieval to bring only the relevant fragments into the model.
    3. Analyze the distribution of input lengths and observe the proportion of requests that fall near the threshold, then optimize for those cases.

    The code below uses a simplified assumption to estimate the impact of tiered pricing:

    1. def tiered_request_cost(p: Pricing, input_tokens: int, output_tokens: int,
    2. cached_tokens: int = 0, threshold: int = 200_000,
    3. multiplier: float = 2.0) -> float:
    4. # Simplified assumption: when the input exceeds the threshold, the entire
    5. # request is multiplied by the multiplier. The threshold and multiplier are
    6. # examples; actual rules should follow the provider’s official pricing page.
    7. # Some services only apply a surcharge to specific items.
    8. base = request_cost(p, input_tokens, cached_tokens, output_tokens)
    9. return base * multiplier if input_tokens > threshold else base

    Running a sensitivity test on requests that fall near the threshold often reveals that some workloads habitually stack long contexts for convenience, driving actual costs far above expectations.

    The Hidden Overhead of Reasoning Capabilities

    Reasoning capabilities improve success rates on complex tasks but also change the cost structure. Reasoning tokens are usually billed as output tokens, and the visible output is often much shorter than the internal chain-of-thought. Some services let developers set a reasoning effort or a thinking budget, while others let the model decide the length of thinking automatically based on question difficulty, with no full opt-out.

    This has three practical engineering implications:

    • The same task can consume very different token amounts under different reasoning efforts; you need to test with your own business samples.
    • Simple classification, information extraction, format conversion, and similar tasks usually do not require deep reasoning. They can be routed to lighter models, reserving more capable reasoning models for complex requests.
    • Cost analysis should rely on the reasoning token count returned by the API. Estimating cost by looking only at the length of the final answer will severely undercount the actual expense.

    In multi-turn agent scenarios, reasoning tokens accumulate across turns. If the thinking content from each turn is kept in the context, it also increases the input cost of subsequent turns. Therefore, you need a clear context pruning strategy that retains only the historical information required to complete the task.

    Comparing Models by Cost per Successful Task Instead of Unit Price

    When comparing different models, a more meaningful metric is the average cost to complete one valid task. A model with a lower unit price may require multiple retries or have a lower pass rate, resulting in a higher total cost.

    The formula is:

    Cost per successful task = Total spending ÷ Number of accepted tasks

    1. def cost_per_success(records: list[dict]) -> float:
    2. # Each record contains "cost" (spending for that attempt) and "passed" (whether it passed acceptance)
    3. total = sum(r["cost"] for r in records)
    4. passed = sum(1 for r in records if r["passed"])
    5. return total / passed if passed else float("inf")

    To make this metric reliable, you need a representative evaluation set. The eval set should cover the major task types and edge cases in your real business, with at least a few hundred samples. Each sample needs clear scoring criteria, such as answer correctness, output format compliance, and citation accuracy.

    Public benchmark scores should also be treated cautiously. When the score gap between two models is smaller than the statistical error, the ranking conclusion is not trustworthy. When comparing, calculate confidence intervals or estimate variance through repeated sampling before deciding whether to switch models.

    How to Measure Accuracy and Hallucination Rates

    There is no unified definition of hallucination rate. Some evaluations count only factual errors; others also include citation errors, fabricated tool results, or cases where the model answers despite lacking sufficient evidence. The task distribution and scoring methods also vary across different eval sets. Therefore, directly citing a hallucination rate published by someone else as a reliability metric for your system may not be valid.

    A more reliable approach is to define three types of metrics on your own business data:

    • Factual error rate: the proportion of statements in the answer that contradict the evidence or have no supporting basis.
    • Citation accuracy: whether the sources cited in the answer actually exist and genuinely support the corresponding claims.
    • Refusal rate: the proportion of cases where the model explicitly states it cannot determine an answer due to insufficient evidence. A very low refusal rate often indicates that the model tends to fabricate answers.

    Common engineering practices to reduce hallucinations include:

    • Using retrieval-augmented generation (RAG) and requiring answers to include verifiable source snippets.
    • Performing schema validation on structured outputs, with retry or fallback to human handling when validation fails.
    • Applying rule-based checks or secondary verification for key fields such as amounts, dates, and entity names.
    • Explicitly allowing the model to state “cannot determine” in the prompt, and tracking this outcome separately in the evaluation.