LLM API Price Increases: How to Calculate and Optimize Real Costs

    Token unit prices alone don't tell you what an LLM actually costs to run. This article breaks down how real API bills are structured—input, output, and cached tokens—why output is priced higher, and how caching can cut request costs significantly. It introduces the concept of unit task cost, walks through a worked cost estimation example with code, and shares practical optimization tactics: cache-friendly prompt design, output length control, tiered model routing, and budget management. If your provider just raised prices, this framework will help you respond with data instead of guesswork.

    Why Sticker Prices Alone Don’t Work for Decision-Making

    When news of an LLM API price change breaks, many teams immediately compare “price per million tokens.” That comparison is useful but incomplete. Your actual bill is made up of several components:

    1. Input tokens: system prompts, conversation history, retrieved document snippets, and tool definitions all count as input.
    2. Output tokens: every token the model generates is billed, usually at a higher rate than input.
    3. Cached tokens: when the prefix of a request matches a previous one, the server can reuse already-computed intermediate states, billed at a much lower rate.

    As a result, the same model can cost several times more in one business scenario than in another. Judging whether a price is reasonable requires calculating against your own request patterns—not just reading the list price.

    Understanding Layered Pricing and Where Costs Come From

    Why output costs more. When generating output, the model decodes autoregressively, token by token. Each step requires reading the context and performing a forward pass—it can’t be parallelized the way input processing is. Output is therefore computationally more expensive, and pricing reflects that.

    Why input is relatively cheap. Input can be processed in parallel batches efficiently. However, input length keeps accumulating, especially in multi-turn conversations and agent workflows, where every round resends all previous content.

    Why caching saves money. The server reuses computation results for identical prefixes, so repeated content costs far less. The catch: the prefix must match exactly. Even a single extra space in the middle can invalidate the cache.

    Watch out for rule differences. Providers differ on cache writes, cache lifetime, minimum cacheable length, and whether storage fees apply. Some services also price by context length tiers, raising rates above certain thresholds. Always verify these rules against the official documentation and check each item when estimating.

    From Unit Price to Unit Task Cost

    A price increase doesn’t necessarily mean total costs go up. A better metric is unit task cost: on average, how much money it takes to complete one business goal. It can be approximated as:

    Unit task cost = average cost per request × average requests per task ÷ task success rate

    This formula has three variables. First, per-request cost is determined by the mix of input, output, and cached tokens. Second, average requests per task reflects whether the model needs multiple calls to finish a job. Third, the task success rate determines the waste from failed retries.

    If a new model costs more per token but solves the task in a single call with far fewer retries, your unit task cost may actually drop. Conversely, if prices stay flat but outputs become verbose, costs still rise. Evaluate all three variables using real business samples.

    Estimating the Cost of a Single Request

    The following code calculates per-request cost across the three token types. Assume cached tokens are included in total input, i.e., total input = cache hits + cache misses.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Pricing:
    4. input_per_m: float # Price per million input tokens (USD or CNY), cache-miss portion
    5. output_per_m: float # Price per million output tokens
    6. cached_per_m: float # Price per million cache-hit tokens
    7. def request_cost(
    8. price: Pricing,
    9. input_tokens: int,
    10. cached_tokens: int,
    11. output_tokens: int,
    12. ) -> float:
    13. """Compute the cost of a single request. cached_tokens is treated as a subset of input_tokens."""
    14. if cached_tokens > input_tokens:
    15. raise ValueError("Cached tokens cannot exceed total input tokens")
    16. fresh_input = input_tokens - cached_tokens
    17. cost = (
    18. fresh_input * price.input_per_m
    19. + cached_tokens * price.cached_per_m
    20. + output_tokens * price.output_per_m
    21. )
    22. return cost / 1_000_000

    Here’s a worked example with hypothetical prices. These numbers are for illustration only and are not the pricing of any real product:

    • Total input 8,000 tokens, of which 6,000 are cache hits; output 1,000 tokens
    • Hypothetical rates: input 10/million, output 50/million, cached 1/million

    The calculation:

    • Missed input: 2,000 × 10 = 20,000
    • Cache hits: 6,000 × 1 = 6,000
    • Output: 1,000 × 50 = 50,000
    • Total 76,000, i.e., about 0.076 per request

    Without any cache hits, the same request would cost 0.13. In this example, caching reduces per-request cost by roughly 41%. The higher your cache hit rate in production, the larger the savings.

    Designing Cache-Friendly Prompt Structures

    Cache benefits depend on how you organize your prompts. Common practices:

    1. Put stable content first. System role definitions, tool descriptions, and fixed specifications rarely change and make ideal shared prefixes.
    2. Put variable content last. The user’s current question, this round’s retrieval results, and other dynamic parts should go at the end so they don’t disrupt the cached prefix.
    3. Avoid dynamic values in the prefix. Timestamps, request IDs, or randomly shuffled examples break prefix consistency the moment they change.
    1. def build_messages(system_prompt: str, tool_schema: str, history: list[dict], user_query: str) -> list[dict]:
    2. # Stable content first, dynamic content last
    3. messages = [
    4. {"role": "system", "content": system_prompt + "\n" + tool_schema},
    5. ]
    6. messages.extend(history)
    7. messages.append({"role": "user", "content": user_query})
    8. return messages

    Continuously monitor your cache hit rate: cache-hit tokens divided by total input tokens. If this metric stays low, it usually means dynamic content has crept into your prompts, or that requests are spaced too far apart and the cache has expired.

    Controlling Output Length

    Output is the most expensive component, so reining it in has a direct cost impact. Three approaches:

    • Set a reasonable maximum output length in the request to prevent runaway generation.
    • Explicitly instruct the model to be concise—for example, restrict output to structured fields, or return only conclusions and necessary evidence.
    • Use fixed templates for formatted output to cut redundant explanatory text.

    Note that over-compressing output can hurt accuracy and increase retries. Judge by unit task cost, not output length alone.

    A Practical Budget Management Workflow

    1. Map your typical request patterns. Measure the distribution of input and output lengths, and the proportion of reusable prefixes in your scenarios.
    2. Estimate costs with real samples. Multiply per-request cost by daily request volume to get daily and monthly cost ranges.
    3. Set cost alerts. Define budget thresholds per project, user, or feature module, triggering notifications or rate limiting when exceeded.
    4. Use tiered routing. Route simple tasks—classification, format conversion—to cheaper models; escalate complex reasoning tasks to higher-capability models.
    5. Review regularly. Re-run your sample estimates periodically, since model versions, pricing rules, and traffic patterns all change.

    Common Pitfalls

    Comparing only unit prices. Ignoring input/output ratios, cache hit rates, and task success rates leads to wrong conclusions.

    Overlooking compounding multi-turn calls. In agent workflows, every round resends prior history, so input grows with each turn. Without context trimming or summarization, costs climb quickly.

    Ignoring failed requests. Timeouts, format errors, and retries are all billed. Factor failure rates into your cost model.

    Treating the cache as free. Cache writes, lifetimes, and storage rules may incur fees or limits—include them in estimates per the official rules.

    Missing context-length tiered pricing. If pricing is tiered by length, calculate each tier separately; don’t substitute an average rate.

    The core of LLM cost management is to break the bill apart, estimate using your real request patterns, and keep optimizing through prompt design, output control, and tiered routing. A price increase is a signal—it’s your cue to build this measurement discipline sooner rather than later.