How to Calculate the Real Cost of LLM APIs After Peak-Valley Pricing Changes

    LLM API prices change often, and list prices alone do not show what a workload costs. This article explains how to split each call into uncached input, cached input, and output costs, how prefix caching affects agent workloads, how time-of-use (peak-valley) pricing works, and how to estimate and control the cost of multi-step tasks.

    1. Background: Why Price Changes Can Change Model Selection

    LLM API billing changes frequently. A provider may raise the price of certain request types, introduce time-based pricing that varies by period, or change how cached input tokens are billed. Each change affects how developers judge cost-effectiveness. Actual cost depends on the structure of each request, not on any single unit price.

    A common mistake is to compare only list prices, such as the price per million tokens. Two services can have similar list prices and still produce very different bills. The reason is that the ratio of input to output, the degree of context reuse, the length of model output, and the distribution of calls across time periods all affect total spending. The first step in assessing the impact of a price change is therefore to break each call into components that can be measured.

    2. Breaking Down the Cost of a Single Call

    Most pay-as-you-go LLM interfaces bill across three categories:

    1. Uncached input tokens: the part of each request that must be computed again. Their unit price is usually the highest.
    2. Cached input tokens: the part that exactly matches the prefix of an earlier request, so its computed results can be reused directly. Their unit price is usually much lower than the uncached input price.
    3. Output tokens: the content the model generates. Their unit price is generally higher than the input price. Some models produce reasoning-related output, which is also billed as output and should be checked separately in usage statistics.

    The cost of a single call can be calculated with the following formula:

    Cost = uncached input volume × uncached price + cached input volume × cached price + output volume × output price

    The code below converts this formula into a reusable function. Prices should be read from the provider’s currently published pricing rather than hard-coded in business logic. Otherwise, the estimate and the actual bill may diverge after a price change.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Usage:
    4. input_uncached: int # Uncached input tokens
    5. input_cached: int # Cached input tokens
    6. output: int # Output tokens
    7. @dataclass
    8. class Pricing: # Unit: CNY per million tokens, entered from the provider's published prices
    9. uncached: float
    10. cached: float
    11. output: float
    12. def request_cost(u: Usage, p: Pricing) -> float:
    13. per_m = 1_000_000
    14. return (u.input_uncached * p.uncached
    15. + u.input_cached * p.cached
    16. + u.output * p.output) / per_m

    3. Why Cached Input Dominates Costs in Agent Workloads

    Agent applications resubmit large amounts of context at every step. This context includes system instructions, tool definitions, conversation history, retrieval results, and intermediate state. As a task progresses, the context grows, and most of it stays the same between consecutive requests.

    Prefix caching works by letting the server reuse computed results for a stretch of content at the start of a request that matches exactly. Placing stable content at the beginning of the prompt and variable content at the end raises the cache hit rate. If timestamps, random IDs, or other fields that change on every turn are inserted at the beginning, the cache rarely applies. The same task is then billed at the uncached price for much more of its input.

    As a result, the cost of an agent application depends mainly on the cumulative volume of cached input. When the hit rate is high, total spending stays manageable even if the cached price is not the lowest. After a price change, a team should first check its cache hit rate and then look at the change in list prices.

    4. Peak-Valley Pricing: Mechanisms and Debate

    Peak-valley pricing, also called time-of-use pricing, means the same service charges different unit prices in different periods. Its design usually rests on the following ideas:

    • Load balancing: higher prices during peak hours encourage requests to shift to off-peak periods, which smooths the usage curve of computing resources.
    • Cost mapping: compute is scarce and queues are longer during peak hours, so the higher price can reflect this marginal cost.
    • Resource utilization: off-peak periods have idle capacity, so lower prices can attract non-real-time tasks.

    Whether peak-valley pricing is reasonable depends on the nature of the workload. Real-time interactive applications cannot freely choose when to run, so they bear a larger share of peak-hour prices. Offline batch processing, data labeling, and nightly aggregation can be scheduled for off-peak periods, where costs are usually lower.

    The debate over “price inversion” largely reflects different expectations of what price signals should do. Some users expect higher peak prices to spread demand. Others think prices should reflect the provider’s cost structure directly. Supply conditions, compute capacity build-out, and regulation differ widely across regions, so the same pricing approach may work differently in different markets. When discussing this topic, separate two questions: whether the pricing design is reasonable, and whether the price is cost-effective for your own workload.

    5. Estimating the Cost of a Task from Usage Data

    Consider a multi-step agent task. Assume the task runs for 10 rounds, and each round resubmits the full context, which grows with each round. To estimate the cost, follow these steps:

    1. Record the total input and output volume for each round.
    2. Use the usage fields returned by the service to separate cached from uncached input.
    3. Tag each round’s request with its time period, either peak or off-peak.
    4. Calculate the cost of each round and sum the results to get the total task cost.
    1. def task_cost(rounds: list[Usage], pricing_by_period: dict[str, Pricing],
    2. periods: list[str]) -> float:
    3. total = 0.0
    4. for usage, period in zip(rounds, periods):
    5. total += request_cost(usage, pricing_by_period[period])
    6. return total

    Splitting costs by round shows where spending comes from. You can identify which step produces overly long output, which round has the fastest context growth, and which requests can move to off-peak periods. This turns “how much did this task cost” into a figure that can be explained item by item.

    6. Evaluation Dimensions for Model Selection

    When comparing different services, or different billing plans from the same service, cover at least the following dimensions.

    Dimension Question to Ask Effect on Cost
    Price structure How far apart are the uncached, cached, and output prices? Determines the largest spending item
    Caching mechanism What are the prefix matching rules and cache lifetime? Sets the upper limit on the hit rate
    Time distribution Can the task be scheduled for off-peak hours? Determines whether the peak-valley price gap can be captured
    Output length Can response and intermediate step lengths be constrained? Directly amplifies output cost
    Stability What are the latency and failure rates during peak hours? Retries can generate extra usage
    Migration cost How much work is needed to adapt the interface and adjust prompts? Affects the cost of switching over the long term

    7. Engineering Recommendations

    1. Keep prompt prefixes fixed: place static content first and dynamic content last, and test that the prefix stays stable.
    2. Log usage fields: save input, cache hit, output, and time period data for each request to support review and reconciliation.
    3. Set budget alerts: define thresholds per day or per task, and notify or pause non-critical tasks when they are exceeded.
    4. Limit loop steps: set maximum rounds and timeouts for agents to prevent unproductive loops from increasing costs.
    5. Compress tool returns: pass only the necessary fields back to the model to slow the growth of context in each round.
    6. Schedule offline work: run batch processing, index building, and bulk evaluation during off-peak hours.

    The example below shows how to accumulate costs during task execution and stop the task when it exceeds the budget.

    1. class BudgetGuard:
    2. def __init__(self, limit: float):
    3. self.limit = limit
    4. self.spent = 0.0
    5. def charge(self, cost: float) -> None:
    6. self.spent += cost
    7. if self.spent > self.limit:
    8. raise RuntimeError(
    9. f"Task cost exceeded budget: {self.spent:.4f} > {self.limit:.4f}"
    10. )