Understanding and Controlling Costs After LLM API Upgrades

    This article explains why API bills can rise even when unit prices stay the same, and provides practical methods for calculating per-task costs, managing output token growth, leveraging prompt caching, using structured outputs, routing requests between models, and setting budget limits for agent workflows. It includes formulas, configuration examples, and a cost estimation table to help teams control LLM spend without sacrificing quality.

    Why Your Bill May Rise Even When Unit Prices Stay the Same

    LLM APIs typically charge separately for input tokens and output tokens. Newer models are more capable and often generate longer reasoning chains or more detailed answers when handling complex tasks, so output token counts increase. Even if the unit price per token is unchanged, the total cost for the same business request can be higher than with the previous generation. Therefore, cost changes should be evaluated by per-task cost, not by looking at the price list alone.

    Per-task cost can be calculated with this formula:

    Per-task cost = (input tokens not hitting cache × input unit price) + (cached input tokens × cache unit price) + (output tokens × output unit price)

    The total input tokens in the formula equal the sum of cached and non-cached input tokens. Do not add cache hit tokens on top of total input tokens, or you will overestimate the cost. Logging should record cache_hit and cache_miss input tokens separately, and output tokens should be recorded independently.

    Input and output token counts should be averaged from real business logs, not from a single test. The sample should cover common requests, long-tail requests, and abnormal requests. Sampling only a few ideal cases will make the statistics diverge from the actual bill.

    Evaluate Intelligence Scores Together with Cost

    Third-party evaluation platforms provide intelligence scores that are commonly used to compare model capabilities. However, benchmark scores depend on the test set, prompts, and scoring methodology. When referencing scores, teams should record the evaluation organization, model version, statistics date, and test set description so they can be reviewed later. The ranking of models may change on a different test set.

    For most business scenarios, a model that reaches an acceptable capability threshold is sufficient. Teams should first define a minimum quality bar—for example, the accuracy requirement for a classification task should be determined by the business owner—and then compare per-task costs among models that meet that bar. Beyond the threshold, chasing higher scores usually increases per-task cost noticeably while business gains remain limited.

    When two models have similar quality, and one has a lower per-task cost, you should run a complete evaluation on your own tasks before drawing conclusions. Do not directly rely on third-party numbers.

    In security auditing scenarios, models can assist in detecting code issues such as injection and privilege escalation, but they produce false positives and false negatives. The results still require human security engineers to review and cannot replace a full security test.

    Caching: A Primary Way to Reduce Repeated Input Costs

    Many model APIs offer a lower price for input tokens that hit the cache. The cache discount can be estimated with this formula:

    Cache discount = 1 − (cache unit price ÷ regular input unit price)

    For example, if the cache unit price is one-fifth of the regular input price, the discount is about 80%. This is only a calculation example. Actual discounts depend on the service provider’s published pricing, and teams should verify them before purchase.

    Cache rules vary significantly between providers. The following boundary conditions should be confirmed item by item:

    • Minimum cacheable prefix length: the prefix must reach a certain token count before it is cached.
    • Validity period: how long a cache entry is retained when there are no requests.
    • Billing basis: whether writing to cache incurs extra fees, and what unit price is applied to cached hits.

    In agent applications, system prompts, tool definitions, and conversation history often remain unchanged across multiple requests. Placing these stable contents at the beginning of the request can improve cache hit rates. Dynamic fields such as timestamps or random IDs should be placed after the stable prefix. If they are inserted in the middle of the prefix, the prefix changes with every request, causing cache misses and losing the discount.

    On the engineering side, you can unify the prefix template in an API gateway and log cache hit status for each call. Long reference documents and history records can be stored in object storage and retrieved before being appended to the request, avoiding the need to send all content into the context every time.

    Controlling Output Length with Prompts and Structured Output

    The most direct way to control output tokens is to improve prompts. Open-ended instructions tend to produce verbose answers, while clear output formats reduce irrelevant text.

    1. # Open-ended prompt: output length is uncontrollable
    2. Please analyze the issues in this code and give suggestions.
    3. # Structured constraint: fixed output fields
    4. Please output the code review result in JSON format with the following fields:
    5. {"has_issue": bool, "severity": "high/medium/low", "fix_code": "string"}
    6. Do not output explanatory text.

    Prompt constraints only increase the probability that the model follows the format; they do not guarantee it. The engineering side still needs to validate the output against a JSON Schema. If validation fails, retry a limited number of times—two retries per request is recommended. Each retry generates new token costs, so a limit must be set.

    Fallback trigger conditions should also be defined in advance. For example, if the same task fails JSON Schema validation twice consecutively, return the most recent cached result; if no cached result is available, move the task to a manual processing queue and log the failure reason.

    Model Routing and Monthly Cost Estimation

    Not every request needs the highest-tier model. Simple tasks such as intent recognition or short text summarization can be handled by lightweight models, while code generation and complex reasoning can be routed to newer models. Routing rules can be implemented in the API gateway based on request type, input length, or historical success rate, and the logs should be used to continuously calibrate the rules.

    The cost after routing depends on several variables: the proportion of calls between lightweight and newer models, per-task token counts, unit prices, and cache hit rates. The table below can be used to estimate monthly costs:

    Request Type Monthly Requests Newer Model Share Avg Input Tokens Avg Output Tokens Cache Hit Rate Monthly Cost Delta vs Baseline
    Intent Recognition
    Code Generation
    Complex Reasoning
    Total

    The baseline scenario refers to a setup without routing, where all requests use the newer model. The amount of cost reduction should not be promised in advance; it should be verified through A/B testing. The test should record sample size, statistics period, and quality metrics to confirm that cost savings are not achieved at the expense of business quality.

    Budget Boundaries for Agent Tasks

    Agent tasks typically include multiple rounds of tool calls, error reflection, and state maintenance, each consuming tokens. Without constraints, a failed task can execute repeatedly and lead to cost runaway. Teams should set a budget cap, a maximum step count, and a timeout for each task, and persist intermediate state. If a task is interrupted, it can resume from the checkpoint rather than starting over.

    Example configuration:

    1. task_budget:
    2. max_cost_usd: 0.50 # per-task cost cap
    3. max_steps: 20 # maximum steps
    4. timeout_seconds: 300 # timeout
    5. max_tool_retries: 2 # retry limit per tool call
    6. checkpoint: true # persist state every step

    When a tool call fails, distinguish between retryable and non-retryable errors. For example, network timeouts can be retried, while parameter validation failures should terminate the task and report the error.

    For each step in the logs, the following fields are recommended: task_id, step_index, model_name, cache_hit_tokens, cache_miss_tokens, output_tokens, step_cost, error_type. These fields help identify the most expensive part of the workflow.

    Conclusion

    New-generation model APIs maintain unit prices while improving capability, which makes cost issues more subtle. Teams need to calculate per-task costs, monitor changes in output tokens, and use caching, structured outputs, model routing, and budget controls to keep costs within an acceptable range. Before rollout, run A/B tests that observe both cost and quality metrics. All cost-reduction measures should be validated with actual data before being promoted.