Multi-Model Office Agents: Model Routing and Fallback Strategies
Learn how to select models for office agent tasks using a unified adapter layer, intent-based routing, cost and latency trade-offs, and failure recovery. This article includes illustrative Python code, routing rules, and circuit breaker thresholds that should be calibrated against real workloads.
Why Office Agents Need Multiple Models
Office tasks vary widely. “Turn this week’s meeting notes into three action items” and “Analyze the risk clauses in this 200-page procurement contract and generate a comparison table” require very different levels of model capability and response time.
Using a single model can waste compute and money on simple tasks while leaving complex tasks underserved. Multi-model integration aims to assign each task to an appropriate model.
Some AI office agent platforms combine in-house models with several third-party large language models, an increasingly common approach. This article focuses on reusable design principles rather than any product’s internal implementation. All thresholds, weights, and formulas below are illustrative and should be calibrated using your own business data.
1. A Unified Model Adapter Layer
Model providers differ in request formats, streaming responses, tool-call fields, and error codes. If the orchestration layer calls each provider’s SDK directly, adding a model requires changes to business logic.
An adapter layer encapsulates these differences and exposes a single calling interface to the orchestration layer.
The following illustrative code demonstrates the registry component of this approach. It is not production-ready.
from dataclasses import dataclassfrom typing import Callable, Dict@dataclassclass ModelResponse:text: strmodel_id: strclass ModelRegistry:"""Register models without modifying routing code when adding a model."""def __init__(self):self._handlers: Dict[str, Callable] = {}def register(self, model_id: str, handler: Callable) -> None:self._handlers[model_id] = handlerdef get(self, model_id: str) -> Callable:if model_id not in self._handlers:raise KeyError(f"Unregistered model: {model_id}")return self._handlers[model_id]
The key points are:
ModelRegistrymaps model IDs to callable handlers. Registration replaces model-specificif/elsebranches, so adding a model only requires another registration entry.ModelResponsestandardizes the response structure, keeping provider-specific response formats out of the orchestration layer.- Each
handlermanages authentication, protocol conversion, and error mapping internally. Credentials should come from environment variables or a secrets management service, not be embedded in code.
2. Selecting Models Through Intent-Based Routing
Routing is central to a multi-model system. A lightweight classifier first identifies the instruction’s intent, then a rule table selects the model. The classifier can be a small model or a combination of keyword rules and a small model.
LIGHT_INTENTS = {"schedule", "lookup", "draft_email"}HEAVY_INTENTS = {"long_doc_summary", "data_cleaning", "code_design"}CONFIDENCE_THRESHOLD = 0.7def pick_model(label: str, confidence: float) -> str:if confidence < CONFIDENCE_THRESHOLD:return "pro" # Use the more capable model when classification is uncertainif label in LIGHT_INTENTS:return "lite"return "pro" # Route heavy tasks and unknown labels to the more capable modelclass AgentRouter:def __init__(self, registry, classifier, fallback_chain):self.registry = registryself.classifier = classifier # Returns (label, confidence)self.fallback_chain = fallback_chain # For example, ["lite", "pro"]def execute_task(self, user_input: str, context: dict) -> ModelResponse:label, confidence = self.classifier(user_input)primary = pick_model(label, confidence)# Deduplicate with dict.fromkeys to avoid calling the same model twicefor model_id in dict.fromkeys([primary] + self.fallback_chain):try:handler = self.registry.get(model_id)text = handler(user_input, context, timeout=10)return ModelResponse(text=text, model_id=model_id)except (TimeoutError, ConnectionError):continueraise RuntimeError("All model calls failed; hand off the task to a human")
How the routing code works:
classifieris an injected intent classification function. Passing it as a dependency makes it easier to test and replace independently.pick_modelimplements the routing policy. A confidence score below0.7routes the task to the more capable model to reduce quality loss from misclassification.timeout=10is an example value. Set timeouts based on each model’s P95 latency.- The fallback chain is tried in order. If the preferred model fails, the router tries subsequent models. If all calls fail, the task is handed off for human handling.
The following routing table is a starting point, not a fixed policy. Adjust it to match your actual task distribution.
| Intent label | Example instruction | Preferred model | Rationale |
|---|---|---|---|
schedule |
Schedule a review meeting for next Tuesday | lite |
Prioritize low latency |
lookup |
Look up the last quote sent to a customer | lite |
Results can be checked directly |
draft_email |
Draft a payment reminder email | lite |
Requires human review before sending |
long_doc_summary |
Summarize an 80-page tender document | pro |
Depends on long-context capability |
data_cleaning |
Remove duplicate rows from a sales spreadsheet and explain the rules | pro |
Requires careful reasoning |
code_design |
Design the structure of a report export module | pro |
Requires understanding across files |
| Unknown or low confidence | Any instruction | pro |
Log these cases to support further labeling |
Evaluate routing with two metrics:
- Misrouting rate: The proportion of tasks assigned to the lightweight model that should have gone to the more capable model and consequently require rework.
- Share of calls to the more capable model: This directly affects cost.
Track both together. Reducing the share of higher-capability calls alone often increases misrouting.
Common mistakes include:
- Sending every task to the more capable model. This prioritizes quality but can quickly exceed the budget.
- Looking only at overall classifier accuracy while ignoring the rework caused by misrouting.
- Defaulting low-confidence tasks to the lightweight model, reducing quality on complex tasks.
3. Balancing Cost and Performance
Models differ in pricing, context windows, and response speed. Routing decisions should account for all three.
Estimate task cost by separating the initial attempt from retries:
Initial attempt cost = input tokens × input unit price + output tokens × output unit price
Estimated total task cost = initial attempt cost + retry count × cost per retry
Input and output unit prices should follow the provider’s current pricing schedule. Prices can change, so they should not be hard-coded.
A weighted score can help compare routing options:
Overall score = 0.5 × quality score + 0.3 × (1 − normalized cost) + 0.2 × (1 − normalized latency)
These weights are hypothetical. For accuracy-sensitive tasks such as contract review, increase the quality weight. For batch processing such as archiving meeting summaries, increase the cost weight.
Long-context tasks require an additional check: confirm whether the input exceeds the target model’s effective context window. If it does, there are two options:
- Split the document, process each section, and consolidate the results.
- Route the task to a model that supports a longer context.
In either approach, assess the information loss associated with document splitting.
Measure latency using percentiles rather than averages. During load testing, record P95 and P99 latency along with concurrency levels and network conditions. Do not promise specific response times without load-test data.
4. Failure Recovery and Circuit Breakers
Third-party models can encounter network instability, rate limiting, or service outages. Without circuit breakers and fallback paths, a single model failure can interrupt an entire office workflow.
A circuit breaker typically has three states: closed, open, and half-open. The following rules are illustrative:
- Closed: Requests proceed normally.
- Open trigger: Open the circuit if the error rate exceeds 20% over the past minute or if five consecutive requests time out.
- Open: Skip requests to the affected model rather than sending them.
- Half-open: After 30 seconds, allow a small number of probe requests. If the probes succeed, close the circuit and resume normal operation. If they fail, keep the circuit open.
