Cost Engineering for LLM APIs: How to Control Costs When Prices Stay Flat but Bills Rise

    This article explains why a new-generation LLM can improve benchmark scores while keeping the same per-million-token API price, yet still increase your bill. It breaks down input, output, and cached-input pricing into a per-task cost model, shows how to compare models using a consistent task set and actual billing data, and covers the main cost drivers after an upgrade: output token inflation and cache hit rate. It also provides practical guardrails, including budget checks in CI, output structure and length limits, stable prompt prefixes for prompt caching, and cost controls for long-running agent tasks. You will get code and configuration examples you can adapt to your own stack.

    1. Flat Pricing Does Not Mean a Flat Bill

    A common pattern is emerging in the industry: a new-generation model posts clearly higher overall benchmark scores, while the official API price per million tokens stays the same as the previous generation. On the surface, this looks like a free performance upgrade. From an engineering perspective, however, the cost needs to be recalculated for three reasons:

    1. Pricing is based on tokens, not tasks. Vendors charge separately for input, output, and cached input, while the business side perceives the cost of completing a task.
    2. More capable models tend to generate longer reasoning and explanation content. As output token volume rises, the bill grows disproportionately, because the output price is usually significantly higher than the input price.
    3. The cached-input discount is a structural discount. Whether you actually receive it depends on how the calls are made, not on the model itself.

    As a result, evaluating a model upgrade requires looking at at least four metrics at the same time: input price, output price, cached-input price, and average consumption per task.

    2. Translating the Price List into a Cost Model

    Using a common pricing tier in the industry as an example (per million tokens): input is about 1.4, output about 4.4, and cached input about 0.26. Cached input is roughly an 81% discount relative to standard input, which makes it the most worthwhile area for engineering investment.

    The cost per task can be approximated as:

    1. Cost_task = (In + Cached * 0.19) * P_in
    2. + Out * P_out

    Here, In is the input tokens that miss the cache, Cached is the input tokens that hit the cache, and Out is the output tokens. This formula shows two things: first, the output term is usually the dominant one; second, every 10 percentage point increase in the cache hit rate reduces input-side cost by roughly 9%.

    A sample budgeting script can be used to plug this model into CI and prevent hidden overspending caused by version upgrades:

    1. def estimate_cost(in_tok, cached_tok, out_tok,
    2. p_in=1.4, p_out=4.4, cache_ratio=0.19):
    3. return (in_tok + cached_tok * cache_ratio) * p_in / 1e6 \
    4. + out_tok * p_out / 1e6
    5. # Per-task budget guardrail: block the release if the threshold is exceeded
    6. BUDGET = 0.001
    7. assert estimate_cost(12000, 48000, 1500) < BUDGET

    3. Cost per Task: The Right Basis for Cross-Model Comparison

    Cost-per-task data from industry evaluation platforms (for example, about 0.68 per task for a certain new-generation model, about 0.84 for another model in the same tier, and about 1.23 for a higher-priced model) reveals a key conclusion: when the intelligence level is similar, the cost difference can exceed 20%.

    The correct comparison approach has four steps:

    • Fix the same task set and the same scoring system to avoid comparing different tasks with different scores;
    • Record the three token categories for each task: input, cache hits, and output;
    • Validate the results against the actual bill rather than estimates based on unit prices;
    • Include the consumption from failed retries and timeout reruns in the total cost.

    From an engineering standpoint, it is advisable to turn this approach into a regression test: every time the model version changes, run the task set once and produce a two-dimensional “score–cost” report instead of looking at the score alone.

    4. Output Inflation: The Most Overlooked Variable After an Upgrade

    If a new-generation model needs about 20% more output tokens to complete the same task as the previous generation, output-side spending rises proportionally while the output price stays unchanged. If output already accounts for more than 60% of total cost, the overall bill may rise by more than 10%, offsetting the benefit of flat pricing.

    Governance measures, ordered by cost-effectiveness:

    1. Constrain the output structure: use a JSON Schema or a strict template to limit fields and reduce free-form generation.
    2. Set an explicit length limit: configure max_output_tokens and add a business fallback for truncation when the limit is exceeded.
    3. Separate reasoning from presentation: internal reasoning does not need to be returned; return only the conclusion and the necessary evidence.
    4. Remove redundancy from prompts: delete repeated background explanations and replace long documents with retrieved snippets.

    Sample configuration:

    1. {
    2. "max_output_tokens": 1200,
    3. "response_format": "json_schema",
    4. "temperature": 0.2
    5. }

    5. Cache Hit Rate: Actually Capturing the Discount

    Whether the cached-input discount materializes depends on whether the prefix is stable. Key practices:

    • Place the system prompt, tool definitions, and domain specifications at the very front of the request and keep them byte-for-byte stable;
    • Move volatile content such as timestamps, random IDs, and user nicknames to the end of the request;
    • Avoid whitespace differences introduced by template rendering inside a long prefix;
    • Build a semantic cache layer for high-frequency questions, so that a hit skips the model call entirely.
    1. [Stable prefix: system prompt + tool schema + long document] ← aim for a cache hit
    2. [Volatile part: conversation history + current question + timestamp] ← place at the end

    6. Cost Control for Long-Running Tasks

    Coding, defensive security analysis, and long-running agent tasks are the areas where capability improvements are most visible right now, and they are also the scenarios with the most concentrated token consumption. Control strategies include: setting both a step limit and a budget limit for agents; summarizing and compressing tool outputs before putting them back into the context; splitting large tasks into independently verifiable subtasks; and using a small model for intermediate steps while calling the strong model only at key decision points.

    1. while step < MAX_STEPS and spent < MAX_BUDGET:
    2. plan = planner(task, context) # lightweight model
    3. result = actor(plan) # strong model, only at key steps
    4. context = compress(result) # compress before re-entering the context
    5. spent += measure(plan, result)

    7. Conclusion

    “Flat pricing, much higher scores” is good news for developers, but the real cost is determined by the token structure. Only by writing the cost model into code, putting budget guardrails into the pipeline, and treating caching and output length as first-class concerns can you achieve a lower cost per task at the same intelligence level. This is also the core competitive point for model selection and architecture design in the next stage. If you use Baidu AI Cloud’s general capabilities (such as monitoring and alerting, log services, and container platforms) to run the accounting and regression processes described above, you can further turn cost governance into a sustainable engineering practice.