Multi-Model Integration for Office Assistants: How to Switch Models by Task Type

    Office assistants handle a wide variety of tasks, from summarizing long documents to generating code, and no single LLM performs best at all of them. This article walks through the architecture and implementation of a multi-model office assistant: defining task types and model profiles, building a unified adapter interface, routing requests by task, handling failures with retries, backoff, and circuit breakers, protecting sensitive data, and evaluating models against real data. It includes working Python code for the adapter, router, and retry logic, and closes with a pre-launch checklist.

    1. Background: Why Office Scenarios Need Multiple Models

    Office tasks vary widely in their requirements. Long-document summarization depends on context window size and the ability to compress information; structured information extraction demands stable, parseable output; code assistance requires rigorous logic; multilingual polishing calls for strong language expression. A single model rarely excels at all of these simultaneously.

    User expectations also differ. Individual users often want to choose between “quick answers” and “deep reasoning” based on their own preferences. Enterprise users care more about cost, latency, data compliance, and reliability—and prefer that the system decide which model to call.

    As a result, the architectural focus of office assistants is shifting from “integrating one model” to “managing a group of models.” Three core questions emerge: how to unify the calling interface, how to assign tasks to the right model, and how to keep the service available when a model fails.

    2. Core Concepts and Key Metrics

    Before designing the system, clarify a few concepts:

    Task type: Classifying requests by user intent, such as summarization, extraction, generation, Q&A, or translation. Classification can be rule-based or handled by a lightweight classifier model.

    Model profile: A record of each model’s performance across dimensions—quality, latency, per-call cost, maximum context length, and data processing location.

    Routing policy: Given the task type and model profiles, decides which model receives a request and the fallback order after failures.

    Fallback: When the primary model is unavailable, times out, or is rate-limited, the system automatically switches to a backup model so the request still returns a result.

    Use the following dimensions when selecting models:

    Dimension Focus Typical Impact
    Output quality Accuracy, format adherence Determines whether manual review is needed
    Response latency P50 and P95 latency Affects user experience; tail latency needs separate monitoring
    Call cost Billed by input/output tokens Determines whether high-frequency tasks can scale
    Context length Maximum input per call Determines whether long documents must be split
    Data compliance Data storage and transmission location Determines whether sensitive data can enter that model

    3. Overall Architecture

    Split the system into five layers, each with a single responsibility, to make replacement and testing easier:

    1. Interaction layer: Receives user input, displays results, and provides a model-switching entry point.
    2. Task orchestration layer: Handles intent recognition, task decomposition, and context assembly.
    3. Model gateway layer: Centralizes authentication, rate limiting, routing, and logging.
    4. Model adapter layer: Encapsulates provider-specific API differences behind a unified interface.
    5. Observability layer: Collects latency, error rates, costs, and manual acceptance rates to inform policy tuning.

    The benefit of this layering: adding or retiring a model only requires changes in the adapter layer and routing configuration, leaving upstream business code largely untouched.

    4. Unified Interface Adapters

    Different model services differ in request formats, authentication schemes, and error codes. The adapter pattern isolates these differences in one place.

    1. from abc import ABC, abstractmethod
    2. from dataclasses import dataclass
    3. @dataclass
    4. class ChatRequest:
    5. task_type: str
    6. prompt: str
    7. max_tokens: int = 1024
    8. timeout_s: float = 30.0
    9. @dataclass
    10. class ChatResponse:
    11. text: str
    12. model_id: str
    13. latency_ms: int
    14. class ModelAdapter(ABC):
    15. """Unified interface that every model adapter must implement."""
    16. model_id: str
    17. @abstractmethod
    18. def generate(self, req: ChatRequest) -> ChatResponse:
    19. """Send the request and return a standardized result.
    20. Timeouts and server errors should raise exceptions."""
    21. ...

    Each concrete adapter does one thing: convert a ChatRequest into the target service’s request body, then convert the response back into a ChatResponse. Read authentication keys from environment variables or a secrets management service—never hardcode them or write them to logs.

    5. Task Routing Strategy

    A routing strategy typically combines three elements: static configuration, user preferences, and dynamic adjustment.

    Static configuration defines the primary and fallback models for each task type and serves as the default.

    1. TASK_PROFILES = {
    2. "summarize": {"primary": "model_a", "fallbacks": ["model_b"]},
    3. "extract_json": {"primary": "model_c", "fallbacks": ["model_a"]},
    4. "code_gen": {"primary": "model_b", "fallbacks": ["model_c"]},
    5. }

    User preferences let individual users designate a model for certain task types or switch models temporarily within a session. The system should persist these preferences in user settings, notify the user when the chosen model is unavailable, and then degrade according to the default policy.

    Dynamic adjustment modifies routing based on recent observations. For example, if a model’s timeout rate rises steadily over a period, the gateway can temporarily remove it from the primary candidate list.

    Here is a minimal routing implementation:

    1. class Router:
    2. def __init__(self, adapters: dict, profiles: dict):
    3. self.adapters = adapters
    4. self.profiles = profiles
    5. def dispatch(self, req: ChatRequest) -> ChatResponse:
    6. profile = self.profiles.get(req.task_type, self.profiles["summarize"])
    7. candidates = [profile["primary"], *profile["fallbacks"]]
    8. last_error = None
    9. for model_id in candidates:
    10. try:
    11. return self.adapters[model_id].generate(req)
    12. except (TimeoutError, RuntimeError) as exc:
    13. last_error = exc
    14. raise RuntimeError("All candidate models failed") from last_error

    Two key points in this code: candidates are ordered by priority, and exceptions are caught and handled only at the gateway layer—business code never needs to know which specific model failed.

    6. Failure Handling: Retries, Backoff, and Circuit Breaking

    Model services can fail due to rate limiting, network jitter, or server-side outages. Retrying immediately and repeatedly only worsens congestion, so pair retries with backoff.

    • Exponential backoff: Increase wait time multiplicatively with each retry, and add random jitter to prevent many requests from retrying simultaneously.
    • Retry limits: Cap retries against the same model at one or two, then switch to a fallback model.
    • Circuit breaker: When a model’s failure rate within a sliding window exceeds a threshold, stop sending it requests, then probe with a small amount of traffic after some time to check recovery.
    1. import random
    2. import time
    3. def call_with_backoff(fn, max_retries=2, base_delay=0.5):
    4. for attempt in range(max_retries + 1):
    5. try:
    6. return fn()
    7. except TimeoutError:
    8. if attempt == max_retries:
    9. raise
    10. delay = base_delay * (2 ** attempt) + random.uniform(0, 0.2)
    11. time.sleep(delay)

    For write operations or non-idempotent requests, confirm whether a retry could cause duplicate side effects—for example, resubmitting the same approval request twice.

    7. Data Security and Privacy

    Office data often contains contracts, financial records, and personal information. A multi-model architecture widens the scope of data movement, so tighter controls are required:

    1. Minimize context: Send only the task-relevant snippets to the model rather than entire documents.
    2. Mask sensitive fields: Before a request is sent, use rules or detection models to replace phone numbers, ID numbers, bank card numbers, and similar fields.
    3. Route by data classification: Data marked as sensitive may only reach models that have passed compliance review; the routing layer should directly block other options.
    4. Don’t log raw content: Logs should keep only the request ID, task type, model ID, duration, and status code; raw content should be encrypted per a retention policy or not stored at all.
    5. User consent: Before switching to an external model to process data, inform the user and obtain confirmation.

    8. Evaluation and Cost Control

    Whether model switching decisions are sound should be judged by data, not gut feeling.

    Build evaluation sets: Collect real samples for each task type and have domain experts label expected results. Update the sets regularly to cover newly emerging problem types.

    Offline comparison: Run multiple models against the same evaluation set and measure accuracy, format compliance, average latency, and per-call cost. Present results per task type, since a model’s strengths are often concentrated in specific tasks.

    Online monitoring: Track manual acceptance rate, user-initiated retry rate, and the extent of manual edits. These metrics reflect real-world effectiveness better than raw call success rates.

    Cost control: Reduce spend by caching results for identical requests, compressing prompt length, and using lighter models for simple tasks. Set a daily budget cap per task type and trigger an alert when it’s exceeded.

    9. Rollout Recommendations and Checklist

    Before going live, verify each of the following:

    • Every task type has a clear primary model and at least one fallback.
    • The adapter layer isolates all provider-specific request formats and error codes.
    • Sensitive data has routing restrictions, and the blocking logic is covered by tests.
    • Timeouts, rate limits, and service errors all have fallback paths, validated through fault-injection testing.
    • Logging and monitoring cover latency, error rates, costs, and user feedback.
    • The model-switching entry point is clear, and user preferences save and restore correctly.

    A multi-model architecture delivers flexibility and reliability, but at the cost of added complexity. Start with two or three high-frequency task types, accumulate evaluation data, and then expand gradually—avoid wiring every scenario in from day one.