Multi-Model Integration Guide: Model Selection, Routing, and Fallbacks
Learn how to design a multi-model LLM integration around task-specific evaluation, a unified adapter layer, routing policies, retries, circuit breakers, and graceful degradation. This guide also covers quality regression testing, cost accounting, and data compliance controls for production deployments.
1. Identify Which Workflows Need Multiple Models
Integrating multiple models increases implementation, testing, and operational costs. Reserve this design for critical workflows. Evaluate each workflow against four factors:
- Request volume: At high daily volumes, per-request costs and latency add up.
- Impact of failure: Would model unavailability stop the workflow or require costly manual intervention?
- Quality requirements: Could incorrect results create financial, customer, or compliance risks?
- Compliance requirements: Is the data sensitive or restricted? Must it remain within a specific deployment region?
As a starting rule, treat a workflow as critical if at least two factors are rated high. Low-volume internal tools and batch jobs that can be rerun offline without affecting real-time users can usually rely on one model with a manual fallback.
Multi-model integration should make models replaceable, select models by task, and support failover. If weekly report generation and ticket classification depend on a single service, rate limits, regional outages, or service retirement can disrupt both. Model version updates can also change which model is the best fit.
2. Evaluate Models Across Six Dimensions
Public leaderboards are not enough. They measure performance on general-purpose benchmarks, while production workloads have their own input formats, terminology, and output constraints.
Use the following table as an evaluation template.
| Dimension | Metrics | Measurement method | Decision supported |
|---|---|---|---|
| Task quality | Accuracy, key-point coverage, valid JSON rate | Score against an internal evaluation set and manually review a sample | Determine whether the model can handle the task |
| Response latency | Time to first token and total completion time | Measure P50 and P95 by task type | Prioritize time to first token for interactive tasks and throughput for batch processing |
| Context length | Maximum input tokens and quality loss on long documents | Test long-document samples after truncation or chunking | Determine whether a chunking strategy is needed |
| Unit cost | Input and output token prices, average output token count | Use provider pricing and average output length from production logs | Estimate the actual cost of each task type |
| Reliability | Availability, rate limits, timeout rate, and error-code distribution | Measure peak-period timeout rates, not just averages | Set primary and fallback order and circuit-breaker parameters |
| Data compliance | Retention period, training-use terms, and deployment region | Obtain written confirmation from legal and security teams | Determine which data the model may receive |
Step 1: Apply Hard Eligibility Gates
Exclude any model that meets one or more of these conditions:
- Data compliance has not been confirmed in writing by legal and security teams.
- Task quality falls below the task’s baseline. The business owner defines this baseline—for example, ticket classification accuracy no more than 2 percentage points below the human-labeled benchmark.
- Peak-period timeout rates exceed the task’s limit.
Step 2: Apply Weighted Scoring
Compliance is a gate, not a weighted criterion. Normalize the other five dimensions to a 0–10 scale, then calculate a weighted total.
For ticket classification, an example weighting is:
- Task quality: 0.35
- Reliability: 0.20
- Response latency: 0.20
- Unit cost: 0.15
- Context length: 0.10
The following scores are hypothetical and should be replaced with measurements from your own workloads.
| Model | Quality | Latency | Cost | Reliability | Context | Weighted total |
|---|---|---|---|---|---|---|
| Model A | 8 | 9 | 6 | 7 | 8 | 7.7 |
| Model B | 9 | 6 | 5 | 9 | 7 | 7.6 |
| Model C | 7 | 8 | 9 | 8 | 6 | 7.6 |
Model A has the highest listed total and is the initial primary choice. Model C’s latency and cost profile make it a candidate for a fast fallback.
The displayed totals for Models B and C are equal, and a 0.1-point difference should not be treated as statistically meaningful on its own. Finalize the primary and fallback order only after offline evaluation confirms meaningful differences.
3. Build a Unified Integration Layer
A unified integration layer sits between the application and model services. Application code calls one interface, while adapters encapsulate provider-specific protocols.
The request includes these fields:
task_type: Task type, used to look up routing configuration.prompt: Input content, with sensitive information masked before it enters the integration layer.max_output_tokens: Output limit for cost control.timeout_ms: Timeout for a single call.idempotency_key: Caller-generated key. Retries of the same business action use the same key.trace_id: Distributed tracing identifier.tenant_id: Tenant identifier for quota enforcement and log isolation.data_level: Data classification:public,internal,confidential, orrestricted.
Response fields include text, model_used, input_tokens, output_tokens, latency_ms, fallback_used, and degraded. A degraded value of true indicates that the result came from a degradation path.
A minimal adapter interface looks like this:
from dataclasses import dataclassfrom typing import Protocol@dataclassclass LLMRequest:task_type: strprompt: strmax_output_tokens: inttimeout_ms: intidempotency_key: strtrace_id: strtenant_id: strdata_level: str # public / internal / confidential / restricted@dataclassclass LLMResponse:text: strmodel_used: strinput_tokens: intoutput_tokens: intlatency_ms: intclass AdapterError(Exception):def __init__(self, code: str):super().__init__(code)self.code = code # Standardized error codeclass ModelAdapter(Protocol):name: str # Logical name; application code does not use provider model namesdef call(self, req: LLMRequest) -> LLMResponse:"""Call the provider API and map provider errors to AdapterError."""...
Map provider errors to standardized codes:
| Provider behavior | Standardized code | Retry? | Handling |
|---|---|---|---|
| Request timeout | TIMEOUT |
Yes | Retry with backoff |
| HTTP 429 or a rate-limit error | RATE_LIMITED |
Yes | Retry with backoff and reduce the model’s routing weight |
| HTTP 5xx | UPSTREAM_ERROR |
Yes | Retry; repeated failures trigger the circuit breaker |
| Content filtering or input exceeding the length limit | REJECTED_INPUT |
No | Return the error to the application; do not switch models |
| HTTP 401 or 403 | AUTH_ERROR |
No | Raise an alert and switch to a fallback model |
Use the following as initial retry and circuit-breaker settings, then tune them using production data:
- Retries: Allow at most two retries, with backoff intervals of 500 milliseconds and 1 second, plus 0–200 milliseconds of random jitter. The total time spent on attempts and retries must remain within the task’s overall time budget.
- Circuit breaker: Open the circuit when a 60-second sliding window contains at least 20 requests and a failure rate above 50%. Send no requests for 30 seconds. Then enter the half-open state and allow one probe request. Close the circuit if the probe succeeds; reopen it if the probe fails.
An idempotency key helps prevent duplicate caller submissions. Model providers may not support idempotency, however. If generated results trigger database writes or messages, deduplication must happen at the write side.
4. Route by Task and Degrade on Failure
Define the primary model, fallback models, timeout, retry count, and degradation method for each task type:
routes:ticket_classify:primary: model-afallbacks: [model-c]timeout_ms: 3000max_retries: 2total_budget_ms: 4000degrade: rule_engineweekly_report:primary: model-bfallbacks: [model-a]timeout_ms: 15000max_retries: 1total_budget_ms: 20000degrade: template
The gateway switches to a fallback model when any of the following occurs:
- The primary model’s circuit breaker is open.
- The request still returns
TIMEOUT,RATE_LIMITED, orUPSTREAM_ERRORafter retries. - The output fails required structural validation, such as valid JSON validation, and still fails after one retry on the same model.
Degradation has four levels, each with a clear boundary:
- Switch to a fallback model. The fallback must pass the same evaluation set and meet the same quality requirements as the primary.
- Switch to a smaller model. Use this only for tasks with lower quality requirements. Set
degradedtotrueand log the event. - Use rules or templates. This works for fixed-format output, such as standard sections of a weekly report.
- Send the task to a human queue. Tasks involving financial, contractual, or legal conclusions should not automatically degrade to lower-quality results.
The following sketch illustrates the gateway’s core invocation logic:
RETRYABLE = {"TIMEOUT", "RATE_LIMITED", "UPSTREAM_ERROR"}def invoke(req: LLMRequest, route: Route) -> LLMResponse:for name in [route.primary, *route.fallbacks]:if not is_allowed(req.data_level, name):continue # Skip models not allowed for this data levelbreaker = breakers[name]if not breaker.allow_request():continue # Circuit is open; try the next modelfor attempt in range(route.max_retries + 1):try:resp = adapters[name].call(req)breaker.record_success()return respexcept AdapterError as e:if e.code == "REJECTED_INPUT":raise # An input problem does not justify model switchingif e.code not in RETRYABLE:break # For example, AUTH_ERROR: switch models and alertsleep(backoff(attempt))breaker.record_failure()return degrade(req, route.degrade) # Degrade when no model is available
Before restoring the primary model after degradation, its circuit breaker should enter the half-open state. Restore primary routing only after consecutive successful probes and sampled quality checks that meet or exceed the baseline.
5. Run Quality Regression Tests and Track Costs
Build the offline evaluation set from masked production samples. Stratify samples by task type and cover both common categories and edge cases.
Choose a sample size for each category that keeps metric variation within an acceptable range. Start with at least 200 samples per category. Use two annotators, cross-review 10% of the samples, and ask the business owner to resolve substantial disagreements.
Validate model changes in this order:
- Offline regression testing: Compare the candidate model against the current baseline on the evaluation set. Block release if the overall metric drops by more than 1 percentage point or any category drops by more than 3 percentage points. These are starting thresholds; adjust them to business tolerance.
- Shadow traffic: Send copies of production requests to the candidate model. Log its results without returning them to users. Compare latency, output length, and error distributions.
- Limited canary rollout: Split traffic by tenant or randomly by request. Start at 5% and gradually increase exposure once metrics are stable.
Calculate costs as follows:
Cost per call =input tokens × input price per token+ output tokens × output price per tokenDaily task cost = sum of all call costs for that task
Include retries and fallback calls. Some providers bill for timed-out requests, so reconcile estimates against invoices.
Use average output token counts from production logs and prices from the provider’s pricing schedule. State the measurement period and record peak and average values separately.
Log at least these fields for each call:
trace_idtenant_idtask_typemodel_usedfallback_useddegradedretry_countinput_tokensoutput_tokenslatency_mserror_code
Do not log raw source content. Record only a masked summary or a hash.
6. Enforce Data Compliance
- Mask sensitive information before requests enter the integration layer, including phone numbers, government-issued identification numbers, and payment card numbers.
- The application declares
data_levelin the request. The integration layer uses it to verify whether a model may receive the data; this decision must not depend on model output. - Set log retention periods according to compliance requirements, and never store unmasked source content in logs.
- Ensure the model’s deployment region meets data sovereignty requirements. Obtain written confirmation of training-use terms. Until confirmation is complete, do not send data classified as
confidentialor higher to the model. - Repeat the compliance review whenever you change models or providers.
Glossary
- Time to first token: The time between sending a request and receiving the first output token. It affects the responsiveness of interactive applications.
- P95: The latency value at or below which 95% of requests complete. It measures tail latency.
- Circuit breaker: A mechanism that temporarily stops calls to a failing model to prevent failures from spreading.
- Idempotency key: An identifier shared by retries of the same business action to help prevent duplicate execution.
- Shadow traffic: Copies of production requests sent to a candidate model for validation, with results logged but not exposed to users.
