Multi-Model Routing: Balancing Cost and Performance for AI Office Agents

    When building AI office agents, relying on a single model often leads to a trade-off between high costs and suboptimal performance for complex tasks. This article explores a multi-model routing strategy that categorizes tasks by difficulty, estimates comprehensive costs including retries, leverages off-peak scheduling, and implements robust model selection and fallback mechanisms. It also provides Python code examples and a deployment checklist to help engineering teams optimize both cost and quality.

    I. Why Office Agents Need Multiple Models

    Tasks in office scenarios vary significantly. Organizing meeting minutes, extracting key contract terms, verifying report figures, and generating weekly reports with charts each require different levels of model capability, response times, and costs. Routing all tasks to a single high-end model ensures stability but results in higher costs and latency. Conversely, delegating everything to a lightweight model increases the failure rate for complex reasoning tasks.

    The core problem multi-model integration aims to solve is determining which model should handle each task category to achieve a reasonable balance between performance, speed, and cost. This requires evaluating tasks, models, and costs within a unified framework.

    II. Task Classification: Assessing Difficulty First

    Classification is the prerequisite for model selection. You can determine task attributes across three dimensions:

    • Cognitive complexity: Is it a single-step extraction or field conversion, or does it require multi-step reasoning and cross-document synthesis?
    • Fault tolerance: Is the output merely a draft, or will it be sent externally or used for decision-making?
    • Latency sensitivity: Does the user expect real-time feedback, or can the task be completed asynchronously in the background?

    Based on these dimensions, tasks can be broadly categorized into three tiers:

    Tier Typical Tasks Model Selection Preference
    Basic Format conversion, short text summarization, keyword extraction Lightweight model; prioritize low cost and latency
    Standard Document rewriting, data organization, routine email drafting General-purpose model; balance performance and cost
    Advanced Multi-document synthesis, complex planning, calculations requiring strict validation Advanced reasoning model; higher cost acceptable

    Classification should be determined by both rules and historical data. For instance, if the input length exceeds a certain threshold, or the manual modification rate for similar tasks is high, the task should be elevated a tier even if it appears basic on the surface.

    III. Converting Quota Consumption into Comparable Metrics

    Many platforms use a “multiplier” to represent the quota consumption of different models. The multiplier indicates the consumption ratio of a specific model relative to a baseline model for the same task. A lower multiplier means lower single-task consumption. However, multipliers only reflect consumption, not output quality; both must be considered during model selection.

    The cost of a single task can be estimated using the following formula:

    Single Cost = Base Quota × Model Multiplier × Number of Call Steps × (1 + Retry Rate)

    Here, “Number of Call Steps” refers to how many times the agent calls the model to complete a task, and “Retry Rate” is the proportion of outputs regenerated due to validation failure. The value of this formula lies in evaluating low-unit-price models within the complete workflow. A model with a low multiplier but a high retry rate may ultimately cost more than a model with a higher multiplier that succeeds on the first try.

    IV. Off-Peak Scheduling for Platform Discounts

    Some platforms offer quota discounts during specific time windows. For engineering teams, these rules can be translated into scheduling strategies, but two points must be noted.

    First, event rules are subject to official platform announcements. Hardcoding unconfirmed time windows and prices in the code should be avoided; instead, store them in a configuration center for easy adjustment.

    Second, off-peak scheduling only applies to tasks that can be completed asynchronously. Real-time interactive requests should not be delayed to wait for discount periods.

    1. from datetime import datetime
    2. # Time window configuration is read from a configuration center; shown here for illustration
    3. DISCOUNT_WINDOWS = [
    4. {"start": 0, "end": 6},
    5. ]
    6. def in_discount_window(now: datetime, windows: list[dict]) -> bool:
    7. return any(w["start"] <= now.hour < w["end"] for w in windows)
    8. def should_defer(task_is_async: bool, now: datetime, windows: list[dict]) -> bool:
    9. # Only consider deferring if it is an async task and currently outside the discount window
    10. return task_is_async and not in_discount_window(now, windows)

    In production systems, you also need to distinguish between weekdays and holidays in the configuration, and allow operations staff to disable off-peak logic at any time.

    V. Code Implementation for Model Selection and Fallback

    The selection logic should simultaneously consider the quality floor, cost, and availability. The quality floor should be determined by an offline evaluation set, not subjective impressions.

    1. from dataclasses import dataclass
    2. QUALITY_FLOOR = {"basic": 0.70, "standard": 0.80, "advanced": 0.90}
    3. @dataclass
    4. class ModelProfile:
    5. name: str
    6. cost_multiplier: float # Quota consumption multiplier; lower is better
    7. p95_latency_s: float # Historical P95 latency in seconds
    8. quality_score: float # Offline evaluation score, ranging from 0 to 1
    9. def pick_model(task_level: str, budget_ok: bool,
    10. profiles: list[ModelProfile]) -> ModelProfile:
    11. candidates = [p for p in profiles
    12. if p.quality_score >= QUALITY_FLOOR[task_level]]
    13. if not candidates:
    14. raise RuntimeError("no model meets the quality floor")
    15. if budget_ok:
    16. return min(candidates, key=lambda p: p.cost_multiplier)
    17. return max(candidates, key=lambda p: p.quality_score)

    The fallback chain must cover three types of exceptions: timeouts, rate limiting, and output structural validation failures. When falling back, record the failure reason to prevent repeatedly triggering the same fault.

    1. import time
    2. class ModelError(Exception):
    3. pass
    4. def call_with_fallback(prompt, chain, call_fn, validate,
    5. timeout_s=30, max_retry=1):
    6. # chain is a list of models ordered by priority
    7. # validate is an output structure validation function implemented by the business logic
    8. last_error = None
    9. for model in chain:
    10. for attempt in range(max_retry + 1):
    11. try:
    12. result = call_fn(model, prompt, timeout=timeout_s)
    13. if validate(result):
    14. return model, result
    15. last_error = "validation_failed"
    16. except (TimeoutError, ModelError) as e:
    17. last_error = str(e)
    18. time.sleep(0.5 * (attempt + 1))
    19. raise RuntimeError(f"all models failed, last error: {last_error}")

    VI. Quality Evaluation: Data-Driven Model Selection

    Model selection conclusions require data support. It is recommended to proceed with the following steps:

    • Build an evaluation set: Collect real samples categorized by task tier, covering both common and edge case inputs. Prepare at least dozens of samples for each tier.
    • Offline evaluation: Run the evaluation set against candidate models in batches, recording completion rate, accuracy, and average latency.
    • Online monitoring: Continuously collect manual modification rates, user undo rates, and task failure rates.
    • Periodic re-evaluation: After model version updates or billing rule changes, re-run the evaluation set and update the model selection table.

    Evaluation results should be summarized in a unified table for easy team comparison:

    Metric Meaning Focus
    Task Completion Rate Proportion completed without manual intervention Higher is better
    Manual Modification Rate Proportion of outputs substantially modified by users Lower is better
    P95 Latency Upper limit of response time for 95% of requests Lower is better
    Cost-Effectiveness Task completion rate divided by single-task cost Aids decision-making

    VII. Deployment Checklist

    1. Have tasks been classified, and are the classification rules supported by historical data?
    2. Are model multipliers read from configurations and regularly reconciled with actual bills?
    3. Does the cost estimation include retries and multi-step calls?
    4. Does the fallback chain cover timeouts, rate limiting, and validation failures?
    5. Is the logic related to limited-time discounts configurable and disableable?
    6. Are there online feedback metrics like manual modification rates, and are they included in periodic re-evaluations?