LLM API Selection and Cost Optimization: A Practical Guide
Rising prices for next-generation flagship models can break the unit economics of API-driven applications. This guide explains how token-based billing works, why output tokens dominate cost, and how to cut spend without sacrificing quality—using a performance-per-dollar framework, tiered model routing, context engineering, output and batch controls, and cost observability. It also includes a four-week rollout plan.
1. Background: How Next-Generation Model Price Increases Hit Your Costs
Public list prices for the latest generation of flagship large models have risen sharply: roughly $10 per million input tokens and $50 per million output tokens, compared with about $4 and $20 for the same tier in the previous generation—an increase of roughly 2.5x overall.
For applications where API calls are the core cost item, this is not a small percentage change you can overlook. It is a structural variable that directly reshapes the unit economics.
This article does not evaluate or recommend any specific vendor’s products. Instead, it frames the “flagship price increase” as a general engineering problem: when more capable models get significantly more expensive, how should you redesign your calling architecture to bring costs back into a manageable range? The methodology applies to any cloud provider’s model services, including the general-purpose large model offerings available through Baidu AI Cloud.
2. Read the Bill First: The Structural Features of Token-Based Pricing
Most large model APIs bill input and output separately, and the output rate is typically 3–5x the input rate. The reason is that autoregressive decoding cannot be parallelized as fully as the prefill stage, so compute utilization is lower. Understanding this leads to three main cost-reduction levers:
- Compress the input: system prompts, retrieved passages, and conversation history are billed every time they are sent and are the most easily overlooked fixed costs.
- Constrain the output: output has the highest unit price, and its length directly drives latency, so it should be your first optimization target.
- Increase cache hit rate: reusing repeated prefixes can substantially reduce marginal cost.
A rough cost estimation model:
def estimate_cost(reqs, in_price=10.0, out_price=50.0):# in_price / out_price: USD per 1 million tokenstotal = 0.0for r in reqs:total += r["in_tokens"] * in_price / 1e6total += r["out_tokens"] * out_price / 1e6return total# Example: 200,000 requests/day, averaging 1,800 input and 400 output tokensreqs = [{"in_tokens": 1800, "out_tokens": 400}] * 200_000print(estimate_cost(reqs)) # ~$7,600 per day
Notice that output tokens account for only about 18% of total tokens but contribute roughly 53% of the cost. That is your basis for prioritizing optimizations.
3. Performance-Per-Dollar: Don’t Judge by Unit Price Alone
A high unit price does not necessarily mean a high total cost. Evaluations should incorporate three dimensions:
- Task success rate: a 10-percentage-point improvement in first-attempt success is often worth more than a 10% price cut, because failed requests trigger retries, and retries are the primary source of hidden costs.
- Average number of interaction turns: a stronger model may compress a three-turn conversation into one, reducing total token consumption.
- Total cost per completed task: measure by “one business task completed,” not by “per million tokens.”
We recommend building an internal benchmark set (50–200 real business samples) and running A/B evaluations on candidate models, recording success rate, average token consumption, and P95 latency. Then compute cost per successful task = total cost / number of successful tasks. Only this metric allows meaningful comparison across model tiers.
4. Tiered Routing: Put Expensive Models Where They Matter Most
The most effective and broadly applicable architectural technique is model tier routing. Use a lightweight classifier (keyword rules, a small model, or vector similarity) to judge request complexity, then decide the routing target:
def route(req):if req["complexity"] == "simple": # extraction, formatting, classificationreturn "small_model"if req["complexity"] == "medium": # summarization, rewritingreturn "mid_model"return "flagship_model" # complex reasoning, code generation
In practice, simple traffic often accounts for 60%–80% of requests. Routing all of it to cheaper tiers can cut the overall bill by several times. At the same time, you must put a fallback path in place: when the flagship model is rate-limited or times out, automatically fall back to the mid-tier model and log the degradation event, so availability is never held hostage by a cost strategy.
5. Context Engineering: Cutting Costs on the Input Side
- Stabilize prompt prefixes: put fixed instructions, tool definitions, and few-shot examples at the very front to improve prefix cache hit rate. Most platforms require an exact prefix match for caching, so any timestamp or random ID will invalidate the cache.
- Rerank retrieved passages: retrieve 50 candidates first, then use a reranking model to narrow them down to 5–8. This often halves input tokens without hurting accuracy.
- Summarize conversation history: replace full history with rolling summaries, reducing the input cost of long conversations from linear growth to something close to constant.
- Constrain output structure: use explicit field descriptions and examples instead of lengthy natural-language instructions, shortening both input and output.
6. Reducing Output Costs and Batch Processing
Output is the most expensive part, so set an explicit max_tokens limit with truncation protection, and use “key-points” prompts for summarization tasks to keep the model from free-forming. For offline, non-real-time tasks (log analysis, bulk labeling, offline report generation), prefer asynchronous batch interfaces, which usually yield better unit pricing and higher throughput. Real-time paths can use streaming responses to improve perceived latency, but keep in mind that streaming does not reduce total cost.
7. Observability and Cost Governance
No measurement, no optimization. We recommend collecting the following fields and feeding them into a logging service with monitoring and alerting: request ID, routing tier, input/output tokens, cached token volume, task success rate, number of degradation events, and cost per successful task. Set quotas and budget alerts by business line and by tenant to prevent runaway bills from abnormal recursive calls. On the engineering side, also implement idempotency keys and retry caps to prevent retry storms during failures from amplifying costs.
8. A Rollout Roadmap
- Week 1: Instrument token-level telemetry and produce a real cost baseline.
- Week 2: Ship tiered routing and the fallback path, and quantify the savings.
- Week 3: Rework the context—stabilize prefixes, rerank retrieval, summarize history.
- Week 4: Migrate offline tasks to batch processing, and set up budget alerts plus a monthly review process.
Conclusion
A 2.5x flagship price increase does not make applications infeasible. It shifts the competitive focus from “use the strongest model” to “use the most appropriate model.” Breaking costs down to token granularity, routing traffic by complexity, keeping the context clean, and filling in observability gaps is the reliable way to keep your unit economics healthy through an upward price cycle. If you need managed model services, object storage, message queues, container platforms, and monitoring and alerting to support this architecture, Baidu AI Cloud provides these as general-purpose capabilities that can be combined as needed; see the official documentation for details.
