How LLM API Pricing Works: Token Costs Explained and Cost Optimization Practices

    A practical guide to how token-based pricing works for large language model APIs, covering input vs. output costs, prompt caching, monthly cost estimation, and proven strategies to reduce your LLM spend.

    As large language models move from experiments into production, more and more teams are integrating model capabilities into their systems via APIs. Compared with running your own inference cluster, API calls eliminate hardware procurement, deployment, and scaling headaches—but they introduce a new core concern: cost management. Most mainstream LLM providers today bill by token usage, charging separately for input and output tokens, typically priced per million tokens. For example, a recently released next-generation model is publicly priced at roughly $3 per million input tokens (on cache miss) and $15 per million output tokens. This pricing structure is fairly representative of the industry, and this article uses it as a reference to explain how LLM API billing works and to share actionable cost optimization practices.

    Understanding Token-Based Pricing

    A token is the smallest unit of text a model processes—a Chinese character, a fragment of an English word, or even a punctuation mark can each count as one token. To understand the billing logic, you first need to distinguish the two directions of tokens:

    1. Input tokens: what you send to the model

    Input tokens include everything in the request: the system prompt, conversation history, reference documents injected via RAG, and the user’s current question. In long-context scenarios, input tokens are often the biggest cost driver. Take a typical multi-turn chat assistant: as the conversation grows, every request carries the full message history, so input tokens grow linearly or even worse.

    2. Output tokens: what the model generates

    Output tokens are the text the model actually generates. Note that most providers price output tokens significantly higher than input tokens—in the pricing structure above, output is about 5x the input price, which is common across the industry. The reason is that generation is autoregressive: each token requires a full forward pass, so GPU time costs far more than the parallelized prefill phase used to process inputs.

    The practical takeaway: controlling output length often saves more money than trimming input. Explicitly constraining output format and length in your prompts (e.g., “answer in no more than 200 words”) is a simple, effective cost control technique.

    Cache Hits: An Underrated Cost Lever

    If you look closely at the pricing, the input price is labeled “cache miss.” This refers to prompt caching: when consecutive requests share an identical prefix, the server can reuse previously computed KV cache and apply a steep discount to the matched input tokens—sometimes as low as 10% of the original price.

    To take full advantage of this mechanism, design your application architecture deliberately:

    • Stable prefix organization: Put the system prompt, tool definitions, and fixed business instructions at the very beginning of the request, and place variable user content at the end to maximize prefix reuse.
    • Avoid putting dynamic content first: Timestamps, random IDs, and per-turn variables embedded at the start of the prompt will immediately invalidate the cache.
    • Session affinity: Route requests from the same session to the same service instance when possible to improve cache hit rates.

    For applications with long system prompts and high call volumes (customer service bots, coding assistants, etc.), cache optimization can reduce costs by orders of magnitude—making it one of the highest-ROI optimizations available.

    Cost Estimation: From Unit Prices to a Monthly Bill

    Unit prices alone aren’t enough for budgeting—you need an estimation method. Here’s an illustrative calculation:

    1. def estimate_monthly_cost(
    2. daily_calls: int, # average daily calls
    3. avg_input_tokens: float, # average input tokens per call
    4. avg_output_tokens: float, # average output tokens per call
    5. cache_hit_rate: float, # input cache hit rate
    6. input_price_per_m: float, # input price (per million tokens)
    7. output_price_per_m: float, # output price (per million tokens)
    8. cached_discount: float = 0.1, # discount factor for cache hits
    9. ):
    10. effective_input_price = input_price_per_m * (
    11. (1 - cache_hit_rate) + cache_hit_rate * cached_discount
    12. )
    13. daily_cost = daily_calls / 1_000_000 * (
    14. avg_input_tokens * effective_input_price
    15. + avg_output_tokens * output_price_per_m
    16. )
    17. return daily_cost * 30
    18. # Example: 100,000 calls/day, 2,000 input tokens and 500 output tokens
    19. # per call on average, 60% cache hit rate,
    20. # input at 20 and output at 100 per million tokens
    21. cost = estimate_monthly_cost(100_000, 2000, 500, 0.6, 20, 100)
    22. print(f"Estimated monthly cost: {cost:.2f}")

    This model quickly validates two intuitions. First, although output tokens are priced higher, they aren’t necessarily the largest cost item as long as output length is kept under control. Second, raising the cache hit rate from 0% to 60% can cut input-side costs by more than 50%.

    Systematic Cost Optimization Strategies

    1. Context trimming and summarization

    Multi-turn conversations don’t need to carry full history indefinitely. Generate summaries of older turns and keep only the most recent exchanges verbatim, keeping input tokens at a reasonable level. For RAG scenarios, rank and truncate retrieved results by relevance rather than dumping entire documents into the context.

    2. Model tiering and routing

    Not every request needs the most powerful model. Add an intent classification or complexity assessment layer that routes simple Q&A to lightweight models and sends only complex reasoning tasks to the flagship model. Tiered routing typically cuts overall costs by 30% or more without a noticeable drop in user experience.

    3. Batch and asynchronous processing

    For offline workloads (bulk document summarization, data labeling, etc.), use batch APIs or non-realtime channels. These usually come with significant discounts and are perfectly adequate for latency-insensitive use cases.

    4. Output-side constraints

    Use structured outputs (e.g., JSON Schema constraints), explicit length limits, and streaming truncation to prevent the model from generating redundant content. Since output tokens cost several times more than input tokens, every wasted sentence burns money directly.

    5. Observability and budget alerts

    Hook up logging and monitoring, track token consumption by business line and by caller, and set daily or weekly budget threshold alerts. Cost optimization without measurement is guesswork—see where the money goes first, then optimize. General-purpose logging and monitoring products from major cloud platforms, such as those offered by Baidu AI Cloud, can support this kind of usage analysis.

    Conclusion

    Token-based API pricing effectively turns “intelligence” into a metered, optimizable resource. Developers should treat every model call the way they treat database connection pools or CDN bandwidth: understand the pricing structure, leverage caching, trim unnecessary context, tier model routing, and build usage observability. Once these practices become ingrained engineering habits, LLM costs stop being an uncontrollable black box and become a manageable technical investment. As model capabilities converge and price competition intensifies, teams with stronger cost engineering will gain a more durable competitive edge in bringing AI applications to market.