How to Cut API Costs with Multi-Model Routing Without Sacrificing Quality
Lowering LLM API costs with multi-model routing only works if your quality comparisons are trustworthy. This article covers how to build a reproducible cost-comparison experiment, how to create versioned cost profiles for each candidate model, how to implement tiered routing with quality thresholds, and how to handle fallbacks, canary rollouts, and monitoring in production. A minimal Python skeleton demonstrating profile-based candidate selection, cost estimation, retry with timeout, and graceful degradation is included.
1. Making Cost Comparisons a Reproducible Experiment
The prerequisite for multi-model cost reduction is that your comparison conclusions are credible. Many comparison results fall apart, and the problem usually lies in the testing methodology. A test that can support real decisions should fix at least the following six items.
Model and version. Record the provider, model name, version number, and call date. Providers iterate on models quickly, so conclusions have a shelf life, and reports need to state when testing took place.
Task and data. Taking information extraction as an example, describe the data source, sample size, text length distribution, and how ground truth was produced. Ground truth should ideally be annotated by business staff based on the original text, not generated by some model. When the sample is too small, a handful of samples can flip the ranking, so estimate the required sample size and express result uncertainty with confidence intervals. For field accuracy, for example, you can use Wilson intervals or bootstrap methods. Two models whose intervals clearly overlap should not be declared better or worse than each other.
Output constraints and scoring criteria. Specify the fields, types, and required items in the JSON Schema. Define three categories of metrics: field completeness (whether all required fields exist), field accuracy (whether values match ground truth), and format compliance (whether the output parses correctly). Scoring rules must be fixed. Ideally, two people annotate independently, then compute agreement rate or Cohen’s Kappa. When disagreement is large, revise the annotation guidelines first, then re-annotate.
Repetitions and stability. The same prompt run multiple times may produce unstable results. Record multiple runs per sample and compute variance or agreement per field. If a sample varies widely across runs, count these unstable samples separately and note them in the report. They tend to be the inputs most likely to fail in production as well.
Token accounting conventions. Record input tokens, output tokens, and reasoning tokens (for reasoning models) separately. Some platforms only return a total; in that case, note the convention in the report, otherwise costs across models are not comparable. Cached input tokens should also be counted separately.
Billing rules. State the unit price for each token type, the currency, the billing cycle, and whether cached-token pricing and batch discounts apply. Prices change, so the report must state the date prices were recorded.
The conclusions in this section apply only to the tasks and data used in the test. Readers should verify with their own samples and bills, rather than transplanting someone else’s results directly into their own business.
2. Building Model Cost Profiles
After testing, organize each candidate model into a cost profile. Profiles are the input to routing decisions; store them in a configuration repository and version them together with test results.
A profile should contain at least the following fields:
- Model identifier and version number, consistent with the provider’s documentation.
- Unit prices for input, output, and reasoning tokens, plus the cached-input price.
- Batch discount rules, such as the minimum call volume and the discount mechanism.
- Quality metrics per task type, i.e., field accuracy or format compliance from offline testing.
- P95 latency and rate limits. Latency should come from load testing or production monitoring, not vendor marketing figures.
- Date of statistics and data source.
The cost of a single call can be calculated as follows:
Cost per call = fresh input tokens × input price + cached input tokens × cache price + output tokens × output price + reasoning tokens × reasoning price
Two things to note. First, output token prices are usually higher than input token prices, so the cost ranking for output-heavy tasks may differ from that for input-heavy tasks. Second, reasoning tokens have a large impact for reasoning models. If you leave them out, the underestimated cost concentrates on certain models.
Cost profiles are not a one-time artifact. Prices, versions, and latency all change. Regenerate the profile after every price change or model upgrade, and keep historical versions so you can trace the causes of billing changes.
3. Tiered Routing and Quality Thresholds
The core of routing is: choose the cheapest model that meets the quality requirement. In implementation, process each request with the following flow.
Step 1: classify the task tier. Rules can be based on text length, number of fields, whether amounts or legal clauses are involved, and so on. Simple tasks are extractions with few fields, short text, and clear rules. Complex tasks involve many fields, reasoning, or ambiguity. High-risk tasks — those affecting transactions or compliance judgments — should go directly to the high-quality tier and not compete on cost.
Step 2: set quality thresholds. Thresholds should not be set by gut feel. A common practice is to use the current primary model’s metrics on the same test set as the baseline, then let the business team decide the allowable drop. Set thresholds per task type, and base them on offline test results, not a single experiment.
Step 3: filter candidate models. Candidates must satisfy both the quality threshold and the latency requirement. A model that exceeds latency cannot enter the candidate set even if it is cheap — otherwise user experience suffers.
Step 4: pick the cheapest. Within the candidate set, compute each model’s estimated cost using the formula above and select the lowest. Estimated cost uses the historical average token usage for that task type, so historical data needs periodic updating.
Step 5: log routing results. For each request, record the selected model, task tier, actual token usage, and elapsed time. These logs are the basis for later retrospectives and canary analysis.
The tiered design doesn’t need to be complex at the start. Two tiers (a low-cost model and a high-quality model) usually cover most scenarios. As tiers increase, so do maintenance cost, testing cost, and debugging difficulty — add tiers only when data clearly supports it.
4. Fallbacks and Canary Monitoring
Once the routing strategy is live, exception handling determines whether it runs stably.
Timeouts and retries. Set a timeout for each call; on timeout, retry with exponential backoff, capped at a maximum number of attempts. Retry the same model only once or twice, then switch to the next candidate. Unlimited retries amplify failures and increase cost.
Format validation failures. When the output can’t be parsed as JSON or required fields are missing, retry once. If it still fails, switch to a higher-quality model. Log format-failure samples — they are valuable material for improving prompts and annotation guidelines.
Graceful degradation. When all candidate models fail, the system should not return an error directly to the user. Options include returning a cached result, routing to a manual review queue, or asking the user to retry later. The degradation plan should be confirmed with the business side in advance and documented.
Canary rollout. Don’t roll out a new routing strategy to full traffic at once. Start with a small percentage of traffic while comparing quality metrics, cost, and latency. During rollout, if key quality metrics fall below the threshold or error rates rise noticeably, roll back to the old strategy immediately. Rollback conditions should be defined before launch to avoid after-the-fact disputes.
Monitoring metrics. At minimum, monitor sampled field accuracy per task type, format compliance rate, P95 latency, call share per model, cost per request, and fallback trigger count. Cost metrics should be aggregated daily and reconciled against the bill.
Data security. Before sending test sets or production samples to external models, remove sensitive fields such as national ID numbers, phone numbers, bank card numbers, and addresses, or replace them with placeholders. Evaluation sets should not contain real customer data. If the business must use sensitive data, confirm the relevant compliance requirements first and choose a deployment option that meets them.
5. Checklist and Code Skeleton
Before going live, check each of the following:
- The test report records model names, version numbers, and call dates.
- Sample size was estimated, and results include confidence intervals.
- The source of ground truth is documented and stored separately from model outputs.
- Inter-annotator agreement for dual annotation was computed, and disputed samples were resolved.
- Token accounting conventions (input, output, reasoning, cached) are stated.
- Unit prices, currency, billing cycle, and date of statistics are recorded.
- Quality thresholds are set for every task type, based on offline testing.
- Candidate model latency has been verified with load tests or production data.
- Timeouts, retry counts, and degradation paths are written into configuration.
- Canary ratio, monitoring metrics, and rollback conditions are defined.
- Test and production samples have been de-identified.
Below is a minimal runnable skeleton demonstrating profiles, candidate filtering, cost calculation, timeout-retry, and degradation. client.invoke is a hypothetical client interface and must be replaced with an actual SDK call. Price fields should be filled with the provider’s prices as of the date of statistics.
import jsonimport timefrom dataclasses import dataclass, fieldclass ModelError(Exception):pass@dataclassclass ModelProfile:name: str # Model identifierversion: str # Version number; must be recorded in the reportprice_in: float # Price per 1M input tokensprice_out: float # Price per 1M output tokensprice_think: float # Price per 1M reasoning tokens; 0 if not applicableprice_cached: float # Price per 1M cached input tokensp95_latency_ms: int # P95 latency from load testing or production monitoringquality: dict = field(default_factory=dict) # Task type -> field accuracyclient: object = None # Hypothetical client providing invoke(prompt, timeout)def estimate_cost(p: ModelProfile, usage: dict) -> float:cached = usage.get("cached_in", 0)fresh_in = usage["in"] - cachedtotal = (fresh_in * p.price_in+ cached * p.price_cached+ usage["out"] * p.price_out+ usage.get("think", 0) * p.price_think)return total / 1_000_000def select_chain(task, profiles, thresholds, avg_usage, max_latency_ms):"""Return candidate models sorted by estimated cost ascending; first is primary."""candidates = [p for p in profilesif p.quality.get(task, 0) >= thresholds[task]and p.p95_latency_ms <= max_latency_ms]return sorted(candidates, key=lambda p: estimate_cost(p, avg_usage[task]))def invoke_with_retry(model, prompt, timeout_s, max_retry=1):for attempt in range(max_retry + 1):try:return model.client.invoke(prompt, timeout=timeout_s)except (TimeoutError, ModelError):if attempt == max_retry:raisetime.sleep(2 ** attempt)def parse_valid(text, required_keys):try:data = json.loads(text)except json.JSONDecodeError:return Noneif not isinstance(data, dict) or not all(k in data for k in required_keys):return Nonereturn datadef extract(prompt, required_keys, chain, timeout_s=10):for model in chain:try:raw = invoke_with_retry(model, prompt, timeout_s)except (TimeoutError, ModelError):continue # Switch to the next candidate modeldata = parse_valid(raw, required_keys)if data is not None:return {"model": model.name, "version": model.version, "data": data}# Format non-compliant: move to the next candidate and log the sample for reviewreturn {"model": None, "status": "queue_for_manual"} # Degrade: route to manual queue
This skeleton only demonstrates the call chain. Before integrating into production, you still need to add logging and metrics instrumentation, hot configuration updates, rate limiting, and unit tests. High-risk tasks should have their chain restricted to high-quality models, keeping them out of the low-cost candidate pool.
