LLM API Cost Optimization: A Practical Guide for the Era of Falling Token Prices
As LLM API prices drop, bills do not necessarily follow. This guide breaks down the three-token billing model, explains how token mix and prompt caching drive real costs, and shows how to control spending through prefix stabilization, cache hit monitoring, input-output ratio governance, model routing, and budget circuit breakers. It includes practical code examples and a reference architecture built on Baidu AI Cloud.
1. The Trend: Lower Unit Prices Do Not Mean Lower Bills
A cloud provider recently adjusted the pricing of its latest-generation LLM API. For the flagship tier, input and output unit prices dropped by roughly 20% compared with the previous generation, while cached input prices fell by about 60%. The three prices are now approximately $8, $0.40, and $40 per million tokens. The lightweight tier keeps the previous generation’s pricing: approximately $2, $0.10, and $10 per million input, cached input, and output tokens.
The most important detail in these numbers is not how much prices fell, but the price structure across the three tiers. The output price is 5 times the input price, and there is a 20x gap between uncached input and cached input. This means your bill is determined not by how many times you call the API, but by the proportion of token types and your cache hit rate. Lower unit prices shift the entire cost curve down, but if your calling pattern stays the same, usage growth can easily cancel out the savings.
2. Understand the Billing Model First: Three Token Types and Amplification Factors
General LLM billing is usually split into three categories: regular input tokens, cached input tokens, and output tokens. Let the input price be P_in, the cached input price be P_cache, and the output price be P_out. The cost of a single request can be written as:
def request_cost(in_tok, cached_tok, out_tok, p_in, p_cache, p_out):# Prices are in USD per million tokensreturn (in_tok * p_in + cached_tok * p_cache + out_tok * p_out) / 1_000_000
Plugging in the price structure above makes the amplification effect clear. For a request with a 100,000-token context, if nothing is cached, the input-side cost equals the cost of 20,000 output tokens. If everything is cached, the input-side cost equals only 400 output tokens. The longer the context, the closer the difference between a cache hit and a miss approaches two orders of magnitude.
3. Cost Lever: Turn Long Context into an Asset
Long context capability is often treated as having no cost advantage, but it is actually the biggest variable in the cost structure. Reusable prefixes include system prompts, tool and API descriptions, a few examples, domain glossaries, and long document bodies. There are three things to do in engineering:
- Stabilize the prefix: Move volatile content (timestamps, session IDs, random numbers, user nicknames) to the end of the prompt to avoid cache invalidation caused by changing prefix bytes.
- Explicitly mark the cacheable range: If the platform provides cache point markers, use them to define the boundary of the stable prefix instead of relying on implicit inference.
- Make hit rate observable: Instrument cache hit rate as a first-class metric and put it on the same dashboard as time to first token and failure rate.
Illustrative example:
SYSTEM_PROMPT = "You are a senior coding assistant. Below are the project standards and API conventions..." # Stable; do not concatenate timestampsdef build_messages(user_input, session_meta):return [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": f"{user_input}\n\n[meta]{session_meta}"}, # Volatile content goes last]
Note that cache hits depend on the platform’s specific implementation and lifecycle policies. In engineering, design a fallback path on the assumption that “a hit is an optimization and a miss is the norm,” rather than betting correctness on the cache.
4. Input-Output Ratio Governance
Since the output price is far higher than the input price, “letting the model write more” is the most expensive operation. Practical constraints include: limiting output structure (fixed fields, enumerated values, explicit length caps), splitting long-form generation into small segments and validating each one, handing deterministic computation to code rather than the model, and adding automatic validation with a retry limit. Also avoid another kind of waste: setting the maximum output length too high for the sake of stability, so that actual generation is truncated or redundant, increasing both latency and cost.
5. Model Tiering and Routing
The output prices of the lightweight and flagship tiers differ by about 4x, which naturally supports tiered routing: intent recognition, format conversion, extraction, classification, and rewriting go to the lightweight tier; complex reasoning, long-document understanding, and code generation go to the flagship tier. The routing layer should be a configurable policy with a manual override switch:
def route(task):if task.type in {"classify", "extract", "format"}:return "light"if task.context_tokens > 60000 or task.type == "reasoning":return "flagship"return "light"
Routing must be closed-loop with quality evaluation: run regular regression tests on a small labeled set to avoid hidden costs such as “cost reduction causing quality degradation.”
6. Capacity and Budget: Convert Unit Prices into Unit Economics
Build a budget model around metrics like “cost per thousand business requests” and “monthly cost per user,” tying token consumption to business metrics. At the same time, set quotas and circuit breakers for traffic spikes to prevent bill spikes caused by abnormal loops (such as retry storms). Retries should use exponential backoff with a maximum attempt count, and results should be cached for idempotent requests.
7. Architecture: Building a Controllable Pipeline on Baidu AI Cloud
In a Baidu AI Cloud environment, you can wrap model calls in a unified gateway that handles authentication, quotas, routing, and auditing up front. Use object storage to archive request and response samples, a message queue to smooth peaks and support asynchronous batch processing, a container platform to host routing and validation services, and logging and monitoring with alerting to track token usage, cache hit rate, latency, and failure rate. Integrate all vendor-specific capabilities through generic categories to avoid tight coupling with a single implementation.
8. Conclusion
Price cuts are a trend, not a guaranteed windfall. What really determines your bill is token structure, cache hit rate, and model tiering strategy. Only by solidly executing these five things—prefix stabilization, hit-rate observability, output constraints, tiered routing, and budget circuit breakers—can you achieve certainty in cost, latency, and quality under the new pricing.
