LLM API Price Changes: Cost Optimization and Model Migration Guide
This article provides a practical framework for assessing and reducing costs after LLM API pricing changes. It explains how to calculate cost per successful task, tier workloads by difficulty and risk, use off-peak scheduling and prompt caching, build an evaluation set, run a canary migration, and manage multi-model routing through a unified gateway. It also includes code examples, common pitfalls, and an implementation checklist.
1. Understand the Structural Changes in Pricing
A price change is usually not just a per-unit increase. A single provider may adjust three dimensions at the same time: model tiers, billable token types (input, output, cache hits, and cache misses), and billing windows. Therefore, you cannot judge cost changes with one uniform percentage increase. You need to calculate each item based on your actual call structure.
The numbers below are fictional and are used only to illustrate the calculation method. Suppose a task consumes an average of 200,000 input tokens and 20,000 output tokens per call. The high-tier model costs RMB 2 per million input tokens and RMB 8 per million output tokens. The low-tier model costs RMB 0.5 per million input tokens and RMB 2 per million output tokens.
- High-tier model cost per call: 0.2 × 2 + 0.02 × 8 = RMB 0.56
- Low-tier model cost per call: 0.2 × 0.5 + 0.02 × 2 = RMB 0.14
Looking only at cost per call, the low-tier model is about 75% cheaper. But this is not yet the basis for a decision. The next section explains why.
2. Use Cost per Successful Task as the Core Metric
A cheaper call does not necessarily mean a lower total cost. If a cheap model has a high failure rate, retries, human review, and rework will push up actual spending. A more reasonable metric is cost per successful task:
Cost per successful task = Cost per call ÷ Task success rate
Using the example above, assume the high-tier model has a 95% success rate and the low-tier model has an 80% success rate:
- High-tier model: 0.56 ÷ 0.95 ≈ RMB 0.59
- Low-tier model: 0.14 ÷ 0.80 ≈ RMB 0.18
The low-tier model is still cheaper. If its success rate is only 40%, cost per successful task rises to RMB 0.35, which is still lower than the high-tier model. However, in scenarios that require human review, each failure also incurs labor cost, and the conclusion may reverse. Human review cost should be included in the calculation.
The following code provides a consistent calculation standard:
from dataclasses import dataclass@dataclassclass Price:cache_hit_in: float # Cache-hit input, RMB per million tokenscache_miss_in: float # Cache-miss input, RMB per million tokensoutput: float # Output, RMB per million tokensdef task_cost(p: Price, hit_tokens: int, miss_tokens: int, out_tokens: int) -> float:"""Calculate cost per call in RMB."""total = (hit_tokens * p.cache_hit_in+ miss_tokens * p.cache_miss_in+ out_tokens * p.output)return total / 1_000_000def cost_per_success(cost_per_call: float, success_rate: float) -> float:"""Calculate cost per successful task. Success rate must be in (0, 1]."""if not 0 < success_rate <= 1:raise ValueError("success_rate must be in (0, 1]")return cost_per_call / success_rate
It is recommended to run this calculation once a month using real logs and to report results separately by task type, so averages do not hide differences.
3. Tier Tasks by Difficulty, Latency, and Risk
Tiering is a primary way to control cost. To decide which model tier a task should use, consider four dimensions:
- Reasoning difficulty: Does the task require multi-step reasoning, cross-file understanding, or complex planning?
- Latency requirements: Is it real-time interaction, or an offline task that can wait in a queue?
- Cost of errors: If the output is wrong, will it affect production business, funds, or compliance?
- Token volume: Is the input very long, and is the output controllable?
Based on these dimensions, common tasks can be divided into several tiers:
| Tier | Typical tasks | Recommended strategy |
|---|---|---|
| High risk, high difficulty | Complex code changes, solution design, compliance text review | Keep the high-tier model and prioritize quality |
| Real-time, medium difficulty | Online customer support, interactive Q&A | High- or mid-tier model, with focus on caching and prompt structure |
| Offline, medium difficulty | Document summarization, batch content rewriting | Mid-tier model with off-peak scheduling |
| Low difficulty, structured | Classification, field extraction, tag generation | Low-tier model with format validation |
Pay attention to boundaries when tiering. If a task contains both simple and complex substeps, it can be split: send the simple part to a low-tier model, the complex part to a high-tier model, and apply structured validation to intermediate results.
4. Schedule Before Switching Models
Before changing models, first check whether call timing can be adjusted. Many providers use different prices for different time windows, and high-price windows usually correspond to business peaks. For tasks that do not need to return results in real time, off-peak execution can directly reduce cost without changing the model, so the quality risk is the lowest.
Suitable off-peak tasks include overnight batch evaluation, offline data cleaning, historical data summarization, and scheduled report generation. During implementation, note the following:
- Configure time windows according to the provider’s official documentation, and convert them uniformly to the team’s time zone.
- Off-peak tasks need deadlines and priorities to avoid backlog.
- Real-time tasks should not be blocked by off-peak scheduling logic.
The following example shows logic that decides whether to run immediately based on priority:
from datetime import datetime, timefrom zoneinfo import ZoneInfo# Example windows. For actual configuration, use the provider's published peak windows.PEAK_WINDOWS = [(time(9, 0), time(12, 0)),(time(14, 0), time(18, 0)),]def in_peak(now: datetime) -> bool:t = now.time()return any(start <= t < end for start, end in PEAK_WINDOWS)def should_run_now(priority: str) -> bool:"""Realtime tasks run immediately; other tasks run outside peak windows."""if priority == "realtime":return Truenow = datetime.now(ZoneInfo("Asia/Shanghai"))return not in_peak(now)
5. Reduce Input Costs with Caching and Prompt Structure
Input cost is often the largest part of API spending. If the service supports prefix caching, the unit price for cache-hit portions is significantly lower than for cache-miss portions. The key to improving hit rates is how the prompt is organized.
The basic principle is to put stable content first and dynamic content later:
- Place fixed content such as system instructions, role definitions, tool descriptions, and few-shot examples at the beginning of the request.
- Place variable content such as user input, retrieval results, and conversation history at the end.
- Avoid inserting timestamps, request IDs, or other fields that change on every request into the fixed prefix.
- Truncate retrieval results by relevance and keep only necessary snippets to reduce useless input.
In addition to caching, output length should also be controlled. Clear format requirements and a reasonable maximum output limit can prevent the model from generating verbose answers. For classification and extraction tasks, require output in a fixed JSON structure or enumeration values. This saves tokens and makes programmatic validation easier.
6. Use an Evaluation Set to Decide on Migration
Whether a model can be replaced depends on whether quality meets the bar, not on parameter count or reputation. It is recommended to build an evaluation set for your own business:
- Sample 200 to 500 examples from real traffic, covering various task types and edge cases.
- Define clear scoring criteria for each example, either through human labeling or rule-based validation plus light human review.
- Run the evaluation on each candidate model, and record quality scores, cost per successful task, average latency, and failure types.
The decision rule can be stated in one sentence: among candidate models whose quality score is not below the threshold, choose the one with the lowest cost per successful task. The threshold is determined by the business side, for example, requiring key-field accuracy to be no lower than a certain value, or requiring the human review pass rate to reach an agreed level.
The evaluation set should be updated regularly. Model versions, business scenarios, and input distributions all change, so the conclusion of a single evaluation should not be used for a long time.
7. Implement a Canary Migration
After the replacement plan is determined, migration should be phased and rollback capability should be retained:
- Establish a baseline: record the current model’s performance in success rate, latency, cost, and human review rate.
- Validate with small traffic: route about 5% of similar requests to the candidate model and compare metrics with the baseline.
- Expand gradually: after metrics are stable, increase to 20%, then 50%, and finally switch all traffic.
- Keep a rollback switch: switch models through configuration rather than code changes, so that recovery can be completed within minutes if an issue occurs.
- Monitor continuously: set alerts for quality degradation, latency increases, and cost anomalies.
During migration, it is recommended to compare the outputs of the old and new models for the same request in parallel. Focus on format errors, missing key information, and hallucination-type errors. Statistics on these issues are more informative than an average score alone.
8. Unified Gateway and Multi-Model Routing
When a team uses multiple models, it is recommended to manage routing, cost accounting, and fallback strategies through a unified gateway layer. Business code calls only the unified interface, and the gateway selects the model based on task type. This has three benefits: changing models does not require modifying business logic; costs can be reported by task type; and when the primary model has an issue, the system can automatically fall back to a backup model.
The following is a simplified routing configuration example:
ROUTES = {"classify": "small-model", # Classification, low difficulty"extract_fields": "small-model", # Field extraction, structured output"offline_summary": "mid-model", # Offline summarization, can run off-peak"code_review": "large-model", # Code review, high risk"agent_planning": "large-model", # Multi-step planning, high difficulty}def pick_model(task_type: str) -> str:# Unknown task types default to the high-tier model to avoid quality riskreturn ROUTES.get(task_type, "large-model")
If your team operates in a China-based cloud environment, you can also include large-model services from Baidu AI Cloud in the candidate list and evaluate them alongside other providers under the same evaluation and cost accounting framework. Specific pricing, quotas, and capabilities are subject to the official documentation, and evaluation results should be based on actual business data.
9. Common Pitfalls
- Comparing only unit prices without calculating the cost of failed retries and human review.
- Switching all traffic without evaluation, then discovering quality issues only after launch.
- Ignoring input bloat and appending conversation history and retrieval content to requests without limits.
- Sending all tasks to low-tier models, causing error rates to rise in high-risk scenarios.
- Focusing only on cost without monitoring quality and latency, making it impossible to judge whether the savings are worthwhile.
10. Implementation Checklist
- Review the last 30 days of API call logs, and count token structure and call volume by task type.
- Use the cost-per-successful-task formula to calculate the real cost of each task type.
- Divide tasks into high, medium, and low tiers, and define candidate models for each tier.
- Check whether non-real-time tasks can run off-peak, and configure deadlines.
- Optimize prompt structure by placing fixed content first and controlling output length.
- Build an evaluation set, set a quality threshold, and choose the lowest-cost model among qualified candidates.
- Migrate using canary steps, keep a rollback switch, and continuously monitor quality, latency, and cost.
After a price change, the most effective approach is to use data to understand the cost structure first, then tier and schedule tasks, and only then decide whether to switch models. This order keeps quality risk within an acceptable range while saving actual spending.
