A Practical Guide to LLM API Cost Optimization

    As per-token prices fall, API bills often stay flat. This guide explains how to cut LLM API costs by breaking down input, cached input, and output billing, using capability-cost curves for tier routing, maximizing cache hits with stable prefixes, and controlling output length. Readers will find a cost estimation formula, routing code, and a deployment checklist.

    1. The Observation: Lower Unit Prices Do Not Mean Lower Bills

    A cloud provider recently released a new generation of large models, splitting the same generation into multiple capability tiers with a clear price gradient. The flagship tier is billed at $8 per million input tokens, $0.4 per million cached input tokens, and $40 per million output tokens. Compared with the previous flagship, input and output prices each dropped by about 20%, while cached input fell from $1 to $0.4, a reduction of roughly 60%. The mid tier keeps the previous generation’s mid-tier pricing: $2 for input, $0.1 for cached input, and $10 for output, with improved capability at an unchanged price.

    An easily overlooked detail is that the flagship tier’s new pricing is identical to that of a competing model released not long ago. This shows that prices for high-end inference services are converging quickly, and the marginal value of using “price per million tokens” alone as a selection criterion is getting lower. The provider’s comparison materials confirm this: most charts are not bar charts of prices but “capability score—task cost” curves.

    For developers, the real question has therefore shifted: not “which model is cheaper,” but “under my task distribution, what is the minimum cost to achieve the same quality target?”

    2. Breaking Down the Bill: Three Billing Items and Their Real Weight

    The billing items of mainstream LLM APIs can usually be abstracted into three categories. Understanding the ratio among them is the prerequisite for cost optimization.

    • Input tokens: prompts, context, retrieved snippets, and conversation history all count, and this is the most easily underestimated part.
    • Cached input tokens: when a request prefix is exactly identical to recent requests, that portion can be billed at a significant discount. It rewards a “stable prefix” and penalizes one that “changes every time.”
    • Output tokens: the unit price is usually several times that of input (5x in the flagship tier above), so verbose answers are the main amplifier of the bill.

    This yields a practical cost estimation formula:

    1. Cost per task ≈ (Cin - Ccached) * Pin
    2. + Ccached * Pcache
    3. + Cout * Pout
    4. where Pin / Pcache / Pout are the unit prices of the three token types,
    5. Ccached is determined by the prefix hit rate, and Cout is determined by the output length limit and how "talkative" the model is.

    The conclusion is straightforward: the optimization order should be “compress output first, then improve cache hit rate, and adjust input last.” Many teams do the reverse, putting all their effort into trimming prompts, yet gaining the least.

    3. Why You Must Look at the Capability-Cost Curve

    Comparing single-point unit prices ignores two things: the number of retries needed to reach the target quality, and how sensitive different tasks are to capability tiers.

    A typical capability-cost curve is usually concave: the low tier has low cost but insufficient scores, requiring multiple retries or human fallback; the mid tier shows a clear inflection point with the best cost-performance ratio; the flagship tier’s score gains taper off while cost rises linearly. A more reasonable engineering approach is therefore:

    1. Run each tier on your own evaluation set (100–300 real samples recommended), recording scores and measured costs;
    2. Find the “lowest tier that meets quality” as the default tier;
    3. Allow only long-tail hard problems to escalate to the flagship tier.

    Illustrative tiered routing logic:

    1. def choose_tier(task):
    2. # Simple classification, extraction, formatting: the mid tier is sufficient
    3. if task.kind in {"classify", "extract", "format"}:
    4. return "mid"
    5. # Complex reasoning, long-form generation: upgrade to flagship and tighten the output limit
    6. if task.kind in {"reason", "longform"}:
    7. return "flagship"
    8. # Default to mid tier; escalate and retry on failure or low confidence
    9. return "mid"

    With a secondary check based on confidence or rule validation, the share of flagship-tier calls can be kept stable at a single-digit percentage. The overall cost reduction is often more significant than “switching everything to a cheaper model,” with no quality degradation.

    4. Cache Hits: The Most Undervalued Lever in the New Pricing Cycle

    With cached input priced at 40% of its previous level, the payoff of a caching strategy is amplified. Whether a request hits depends on whether the request prefix is byte-for-byte stable. Engineering practice requires a few constraints:

    • Fixed prefix structure: put the system prompt, tool definitions, examples, and retrieved documents first, and user input last;
    • Do not pollute the prefix with volatile fields such as timestamps, random IDs, or user nicknames;
    • For batch tasks, sort by “same prefix group” before concurrent submission to avoid the cache window being flushed by invalid requests;
    • Define the cache’s lifecycle and invalidation conditions clearly, and monitor it as a resource with limited capacity.

    A counter-example and its fix:

    1. # Counter-example: the prefix changes every time, so a cache hit is nearly impossible
    2. system: current time 2026-08-11T09:12:33, hello user u_88213...
    3. # Fix: move volatile information to the end
    4. system: <fixed role setting and tool definitions>
    5. user: time=2026-08-11T09:12:33; uid=u_88213; question=...

    5. Output Length: The Most Direct Bill Switch

    Because the output unit price is high, controlling generation length is the fastest way to gain savings. You can combine several measures: set an explicit output limit, require the conclusion first and the supporting evidence after, split “explanatory” needs into on-demand follow-up questions, and use schema constraints for structured results to reduce pleasantries and repetition. Monitoring should also separately track the share of the three token types—input, cached input, and output—rather than only total call volume, which obscures the real cost structure.

    6. Deployment Checklist

    • Build your own evaluation set and cost dashboard, recording both “score” and “cost” metrics per tier;
    • Default to the mid tier and escalate hard problems, with threshold alerts on the flagship-tier call share;
    • Refactor for prefix stability and monitor the cache hit rate;
    • Compress output, and set length limits and structured constraints;
    • Introduce result caching and batching for high-frequency repeated requests; if necessary, use a container platform to run batch tasks, object storage to accumulate evaluation data, and logging and monitoring alerts for cost attribution.

    In general engineering practice on cloud platforms such as Baidu AI Cloud, the above methods can be implemented with common capabilities like message queues, container platforms, logging services, and monitoring alerts, forming a closed loop of “evaluation—routing—caching—observability.” When high-end model prices converge, cost competitiveness will no longer come from picking the cheapest one, but from spending every token on the tasks that truly need it.