LLM API Selection and Cost Optimization: A Practical Guide
This guide presents a vendor-neutral methodology for selecting large language model APIs by evaluating cost per completed task rather than token price alone. It covers core metrics such as first-pass rate, retry amplification, and cache hit rate; a three-layer evaluation framework for reproducible results; engineering tactics including tiered routing, prefix normalization, output constraints, and budget alerts; and how to interpret tiered pricing and discounts. A four-week rollout plan helps teams keep inference bills under control as model capabilities and prices change.
1. Background: Why Model Selection Has Become a Cost Problem
Once enterprise applications move into large-scale production, LLMs are no longer isolated experiments. They are embedded into long-chain systems such as customer support, risk control, content production, code assistance, and research data processing. One clear shift is that usage grows from a few hundred debugging calls per day to tens of millions of tokens of throughput per day. Small differences in per-model pricing are amplified by traffic into significant differences in monthly spend.
At the same time, engineering teams commonly face three tensions:
- Capability vs. cost: Higher tiers with stronger capabilities usually cost more per token, but the business may need only a small subset of those capabilities.
- Time to launch vs. long-term bills: Teams often pick a high tier for fast validation, then find it hard to adjust the billing structure after the system stabilizes.
- Inconsistent evaluation criteria: Different teams draw conclusions from different datasets, so selection meetings fail to converge.
This article does not compare specific vendors. Instead, it abstracts a general methodology: how to run a two-axis “effectiveness vs. cost” evaluation within the same capability tier, and how to use caching and routing to reshape the cost structure into a healthier one.
2. Core Metrics: Breaking “Cost Efficiency” into Measurable Quantities
2.1 Cost per Completed Task, Not Price per Token
Unit price is only part of the numerator. What should actually be optimized is:
cost per task = (input tokens × input price + output tokens × output price- cached tokens × cache discount) / completed tasks
This formula explains a common industry observation: two models may differ by less than half a point on coding benchmarks, yet one may cost only a fraction of the other per task. The reason is usually not unit price, but differences in the number of retries, context length, and tool-call rounds required to complete the task.
2.2 First-Pass Rate and Retry Amplification
Let the first-pass rate be p. The average number of retries is 1/p, so actual cost is amplified by roughly 1/p. If two models have similar capability, but model A has a first-pass rate of 0.9 and model B has 0.6, then B’s real cost is about 1.5 times A’s, which is enough to erase any unit-price advantage.
2.3 Cache Hit Rate
For highly repeated prefixes such as system prompts, knowledge base snippets, and code repository context, cache pricing is typically on the order of one tenth of the standard input price. Improving the hit rate often affects the bill more than switching models.
3. Evaluation Framework: Making Conclusions Reproducible
3.1 Three-Layer Evaluation Set
- Capability layer: Public benchmarks plus a private hard-case set, used to confirm whether a tier meets requirements.
- Task layer: Sampling of real business cases (500–2,000 recommended), tracking first-pass rate and manual correction time.
- Cost layer: Recording input, output, and cached tokens plus the number of rounds for each call, forming an auditable bill.
3.2 Stratified Sampling and Confidence Intervals
Do not look only at averages. Stratify by task difficulty, report P50/P90 cost, and provide confidence intervals to avoid wrong decisions caused by small-sample noise.
3.3 Example Evaluation Record Structure
{"task_id": "t-1024","tier": "mid","attempts": 2,"tokens": { "input": 5200, "cached": 4800, "output": 640 },"first_pass": false,"human_edit_seconds": 45}
With this structured data, a vague feeling that something is “more expensive” becomes a discussable conclusion such as “P90 cost is 37% higher.”
4. Four Categories of Cost Governance Engineering
4.1 Task-Tier Routing
Tag requests by complexity: simple requests go to a lightweight tier, while complex requests escalate to a high-capability tier. Routing signals can come from rules, a small classification model, or historical hit rates.
def route(req):if req.cached_prefix and req.max_output < 800:return "light" # high cache hit, short outputif req.tool_calls > 3 or req.max_output > 4000:return "strong" # multi-round tool calls, long outputreturn "mid"
4.2 Prefix Normalization and Cache-Friendly Design
Placing invariant content first and timestamps or random IDs last is the most effective engineering habit for improving hit rates. System prompts should be version-controlled to avoid frequent changes that invalidate the entire cache.
4.3 Output Length Constraints
Output tokens often cost several times more than input tokens. Limiting max_output, requiring structured short answers, and splitting long-form generation into streaming segments can all significantly reduce peaks.
4.4 Quotas, Observability, and Alerts
Establish quotas and budget alerts per business line. Combined with logging and monitoring capabilities, set a threshold on average cost per 10,000 calls and automatically downgrade to the lightweight tier when anomalies occur.
5. Reading Pricing Structures: Using Tiers and Discounts Correctly
Mainstream billing typically includes three token categories: standard input, cached input, and output. The pattern is that output is the most expensive and cached input is the cheapest. When a new generation of tiers is released, a common adjustment is a roughly 20% reduction in input and output prices and a larger reduction in cached input (for example, around 60%), while lightweight tiers often keep the previous generation’s pricing. This creates a clear cost-efficiency gap in the range where capabilities are close.
The engineering implications are direct:
- Migrate repeated context to the cache path first to take advantage of the steeper discount curve;
- For two tiers with similar capability, decide based on measured task cost rather than list price;
- Treat price changes as a window to rerun regression evaluations rather than reusing old configurations based on old conclusions.
6. Rollout Roadmap
- Week 1: Add instrumentation to collect token and round data, and build a cost dashboard.
- Week 2: Build a private task set and complete an A/B evaluation across two tiers.
- Week 3: Launch tiered routing and prefix normalization changes.
- Week 4: Set budget alerts and automatic downgrade policies, and review P90 cost.
If an organization already uses general capabilities such as Baidu AI Cloud’s container platform, logging service, and monitoring alerts to host an inference gateway, the instrumentation and routing logic described above can be deployed at the gateway layer to achieve unified metering and canary switching.
7. Conclusion
The essence of model selection has shifted from “pick the strongest” to “pick the most suitable total cost.” Only by unifying evaluation criteria around cost per completed task and applying engineering tactics to cache hit rate, output constraints, and tiered routing can bills stay controllable through cycles of capability refreshes and price adjustments.
