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.

    1. from dataclasses import dataclass
    2. from typing import Callable, Dict
    3. @dataclass
    4. class ModelResponse:
    5. text: str
    6. model_id: str
    7. class ModelRegistry:
    8. """Register models without modifying routing code when adding a model."""
    9. def __init__(self):
    10. self._handlers: Dict[str, Callable] = {}
    11. def register(self, model_id: str, handler: Callable) -> None:
    12. self._handlers[model_id] = handler
    13. def get(self, model_id: str) -> Callable:
    14. if model_id not in self._handlers:
    15. raise KeyError(f"Unregistered model: {model_id}")
    16. return self._handlers[model_id]

    The key points are:

    • ModelRegistry maps model IDs to callable handlers. Registration replaces model-specific if/else branches, so adding a model only requires another registration entry.
    • ModelResponse standardizes the response structure, keeping provider-specific response formats out of the orchestration layer.
    • Each handler manages 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.

    1. LIGHT_INTENTS = {"schedule", "lookup", "draft_email"}
    2. HEAVY_INTENTS = {"long_doc_summary", "data_cleaning", "code_design"}
    3. CONFIDENCE_THRESHOLD = 0.7
    4. def pick_model(label: str, confidence: float) -> str:
    5. if confidence < CONFIDENCE_THRESHOLD:
    6. return "pro" # Use the more capable model when classification is uncertain
    7. if label in LIGHT_INTENTS:
    8. return "lite"
    9. return "pro" # Route heavy tasks and unknown labels to the more capable model
    10. class AgentRouter:
    11. def __init__(self, registry, classifier, fallback_chain):
    12. self.registry = registry
    13. self.classifier = classifier # Returns (label, confidence)
    14. self.fallback_chain = fallback_chain # For example, ["lite", "pro"]
    15. def execute_task(self, user_input: str, context: dict) -> ModelResponse:
    16. label, confidence = self.classifier(user_input)
    17. primary = pick_model(label, confidence)
    18. # Deduplicate with dict.fromkeys to avoid calling the same model twice
    19. for model_id in dict.fromkeys([primary] + self.fallback_chain):
    20. try:
    21. handler = self.registry.get(model_id)
    22. text = handler(user_input, context, timeout=10)
    23. return ModelResponse(text=text, model_id=model_id)
    24. except (TimeoutError, ConnectionError):
    25. continue
    26. raise RuntimeError("All model calls failed; hand off the task to a human")

    How the routing code works:

    • classifier is an injected intent classification function. Passing it as a dependency makes it easier to test and replace independently.
    • pick_model implements the routing policy. A confidence score below 0.7 routes the task to the more capable model to reduce quality loss from misclassification.
    • timeout=10 is 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:

    1. Misrouting rate: The proportion of tasks assigned to the lightweight model that should have gone to the more capable model and consequently require rework.
    2. 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.