LLM Cost Optimization: A Technical Guide to Model Selection and Token Economics
This article breaks down large language model (LLM) invocation costs into measurable token tiers and shows how to build a quantitative framework for model selection. It explains why cache hit rates, input-to-output structure, and tiered routing determine your real effective price, provides a Python baseline script for calculating weighted unit price and monthly token capacity, and outlines budget guardrails, observability metrics, and a practical selection checklist. The goal is to turn pricing debates into repeatable calculations that stay resilient to price changes.
1. Reframing the Problem: From “Which Model” to “How to Measure Effective Cost”
The core of the discussion is not the merits of any specific product, but a more general engineering problem: when upstream model pricing changes (especially when cached input prices shift by a multiple), a plan that looked extremely cost-effective can quickly shrink in value. Teams need a quantifiable decision framework rather than switching models based on intuition.
Abstracted from the specifics, cost can be written as a simple formula:
Effective monthly output (tokens) ≈ plan budget / weighted average unit priceWeighted average unit price = Σ(token share per tier × unit price of that tier)
The “tiers” should be split into at least four buckets: uncached input, cached input, output, and retries/failed calls. Most teams watch only the output price, while overlooking that in scenarios like intelligent coding and long-document Q&A, input often accounts for a far larger share than output, and system prompts, repository context, and conversation history get resubmitted repeatedly. Cache hit rate therefore becomes the decisive variable.
2. Three Key Variables
2.1 Cache Hit Rate Determines the Real Unit Price
The cached input price is usually a fraction of the uncached price. If the cached tier’s price rises several times over, the weighted average unit price is pushed up significantly even when the list price stays unchanged. The original text mentions budget output shrinking “from roughly 7 billion to 1.4 billion” tokens; essentially, the price change on the cached tier drove the weighted unit price up by about five times. This is a conclusion you can reproduce directly with the formula, not an anomaly.
2.2 Input/Output Structure Determines Sensitivity
Different tasks vary enormously in sensitivity to price changes:
- Code completion, single-turn Q&A: short input, short output, sensitive to output price;
- Repository-level understanding, long-context refactoring: long and highly repetitive input, extremely sensitive to cache pricing;
- Batch summarization, data extraction: high concurrency and large volume, so any unit price change is amplified.
2.3 Tiered Scheduling Sets the Ceiling
Routing every request to the most expensive tier is the most common cause of runaway cost. The sensible approach is to tier by task value and let low-cost models handle exploratory, disposable calls.
3. Build Your Own Cost Baseline Table
Do not rely on any marketing figures. Use one week of real traffic to establish a baseline:
# Example: measure token share per tier and the weighted unit pricebuckets = {"input_miss": 0, "input_hit": 0, "output": 0, "retry": 0}price = {"input_miss": 3.0, "input_hit": 0.3, "output": 12.0, "retry": 3.0} # unit: CNY per million tokensdef weighted_price(buckets):total = sum(buckets.values()) or 1return sum(buckets[k] / total * price[k] for k in buckets)def monthly_capacity(budget, buckets):return budget / weighted_price(buckets) * 1_000_000
With this table, any price adjustment can be converted within minutes into “how many tokens can I still run this month,” and selection discussions shift from argument to calculation.
4. Tiered Routing: Pushing Exploratory Call Costs Toward Zero
The most typical waste in intelligent coding applications is having a high-capability model do high-failure-rate work like “find the relevant files” or “guess the implementation approach.” A more robust structure is:
Planning tier (strong model, low frequency): decompose tasks, define interface contractsExploration tier (small model, high frequency): retrieve candidate approaches, generate drafts, allowed to be discardedExecution tier (medium model, medium frequency): produce mergeable codeVerification tier (rules + tests, zero model cost): compile, unit tests, static checks
Example implementation:
def route(task):if task.kind in ("plan", "review"):return "strong"if task.kind in ("explore", "draft"):return "small"return "medium"
Combined with a policy where “exploration-tier failures do not count toward budget alerts,” overall effective output can increase several times over. This gain is independent of unit price and is the optimization most resistant to price volatility.
5. Budget Guardrails and Observability
Cost governance needs engineering safeguards:
- Quotas and rate limiting: set daily/monthly token caps per project and per user, and downgrade to a small model when exceeded rather than failing outright;
- Context governance: trim history, compress via summarization, and keep a stable prefix ordering to improve cache hit rate;
- Metrics dashboard: make cache hit rate, average input length, retry rate, and cost per task into monitored and alerted items;
- Invoicing and compliance: for enterprise procurement, prefer general-purpose cloud service categories that support formal invoices and usage details, which simplifies cost accounting.
6. Selection Decision Checklist
- Recompute the current weighted unit price with the baseline table instead of comparing list prices;
- Assess sensitivity to the “cached input tier” in any price adjustment;
- Check whether tiered routing is already in place; if not, optimize first before discussing a model switch;
- Keep at least one replaceable fallback channel to avoid single-vendor dependency;
- Consider the combined cost of general-purpose cloud capabilities (object storage, message queues, container platforms, log services, monitoring and alerting) together with model invocation.
7. Conclusion
A price adjustment itself is not frightening; what is frightening is lacking the ability to measure and schedule. Break cost into countable token tiers, tier requests by value, and turn the budget into an alertable guardrail, and any price increase becomes just a parameter update. If you need fuller elastic compute and supporting cloud products, you can build your own controllable model invocation gateway and cost dashboard on top of the relevant general-purpose capabilities from Baidu AI Cloud.
