Multi-Model Routing and Cost Control for Office Agents

    This article presents a practical approach to routing office-agent tasks across multiple LLMs. It defines quality, latency, and cost constraints, assigns models by task and context size, adds off-peak routing and timeout fallback, and provides routing/fallback code plus guidelines for validating whether a task fits a lightweight model.

    Introduction

    In office scenarios, an Agent must complete a goal, not just answer a question. A goal usually requires multiple rounds of reasoning, document reading, and tool calls, and each step has different requirements for model capability and cost. Using only one model wastes compute on simple steps and may under-reason on complex steps.

    This article presents a routing method: first define a quality floor and latency ceiling, then assign models by task, and finally add timeout fallback, quota accounting, and monitoring. Thresholds, multipliers, and time windows in this article are examples; teams need to recalibrate them with their own task data.

    This article provides four directly usable assets: a model assignment table, routing and fallback code, a per-task quota formula, and a monitoring checklist with a troubleshooting table.

    1. Define Three Constraints First

    Quality floor: Measured by rule-validation pass rate or manual sampling pass rate. The baseline can be the pass rate of the existing manual process or the pass rate of the previous process version. For example, “sampling pass rate no lower than baseline minus 2 percentage points” is an operational definition. Without a quantifiable baseline, routing results cannot be accepted.

    Latency ceiling: The wait time users can accept, defined by P95 latency. For example, if P95 must not exceed 40 seconds, then the single-call timeout of each model must be checked against this ceiling. Timeouts must be enforced on the client side, such as with asyncio.wait_for or an HTTP client timeout parameter, not only by relying on the server to return.

    Cost budget: Two layers. One is the per-task quota limit, and the other is the daily quota limit. Both are needed; otherwise, a small number of abnormal tasks can consume the entire daily budget.

    The routing goal is to choose the model with the lowest quota consumption while meeting the quality floor and latency ceiling.

    2. Model Assignment and Off-Peak Strategy

    Model Suitable tasks Context limit Quota multiplier (relative to standard_pro) Single-call timeout Fallback target
    light_flash Information extraction, format conversion, short-text polishing 8k tokens 0.3 15 s None
    discounted_flash Same as light_flash, off-peak only 8k tokens 0.15 15 s light_flash
    standard_pro Email drafting, medium-complexity analysis 32k tokens 1.0 45 s light_flash
    premium_pro Cross-document reasoning, complex cross-document analysis, long-report generation 128k tokens 2.0 90 s standard_pro

    The quota multiplier indicates relative quota consumption for the same token consumption, not an absolute price. Use your team’s billing data for actual multipliers.

    The following definitions are used in this article; confirm them before applying them:

    • Context limit refers to the total input plus output tokens for a single call. When estimating input length, reserve space for output.
    • Single-call timeout is the client-side wait limit for one call, excluding wait time between retries. Each attempt for the same task is timed separately.
    • Fallback trigger is a single-call timeout. After a timeout, switch to the fallback target. Network errors and 5xx errors do not trigger fallback; instead, retry on the same model, and retries count toward the total number of attempts.
    • Upgrade trigger is quality validation failure. Upgrade only one tier, and each task can upgrade at most once.

    Off-Peak Strategy

    discounted_flash calls the same interface as light_flash; the difference is the billing multiplier during off-peak hours. This way, the team does not need to maintain a separate inference service for the discount. The routing rule is simple: lightweight tasks use discounted_flash during off-peak hours and light_flash during peak hours. The specific off-peak window depends on the platform’s billing rules. The example in this article uses 00:00 to 08:00 in the business timezone.

    Confirm the timezone separately. Server default timezones are often UTC; using server time directly to determine off-peak hours shifts the entire window.

    How to Determine Whether a Task Fits a Lightweight Model

    Do not judge by character count alone. A short text may still require multi-step reasoning. The correct approach is to run labeled samples through light_flash and standard_pro and compare their quality pass rates.

    Keep the same batch of inputs for comparison, and record the prompt version and sampling parameters so both groups use consistent criteria.

    Sample size is determined by the allowable error. For a single proportion, if the pass rate is about 90%, the margin is ±3 percentage points, and the confidence level is 95%, about 385 samples are needed per group:

    n = 1.96² × 0.9 × 0.1 ÷ 0.03² ≈ 385

    Samples should cover long documents, tables, multilingual text, and other edge cases. Each edge category needs enough samples; otherwise, mainstream samples can mask edge-case issues.

    The decision rule is as follows. Calculate the 95% confidence interval for the difference d between the lightweight model and standard_pro pass rates. If the lower bound of the interval is not below -T, the task type can use the lightweight model. T is the business-defined tolerance, for example, 2 percentage points. If both pass rates are below the baseline, the problem is usually in labeling or validation rules; fix those first, then compare models.

    3. Routing and Fallback Code

    The following code requires Python 3.10 or later. call_model is a placeholder; replace it with your team’s SDK call. Timeouts in the code are enforced by asyncio.wait_for, and the SDK must support cancellation.

    1. import asyncio
    2. from dataclasses import dataclass
    3. from datetime import datetime, timezone, timedelta
    4. @dataclass(frozen=True)
    5. class ModelSpec:
    6. ctx_limit: int # Total input + output token limit
    7. quota_ratio: float # Quota multiplier relative to standard_pro
    8. timeout_s: float # Single-call timeout in seconds
    9. fallback: str | None # Fallback target after timeout
    10. MODELS = {
    11. "light_flash": ModelSpec(8_000, 0.3, 15, None),
    12. "discounted_flash": ModelSpec(8_000, 0.15, 15, "light_flash"),
    13. "standard_pro": ModelSpec(32_000, 1.0, 45, "light_flash"),
    14. "premium_pro": ModelSpec(128_000, 2.0, 90, "standard_pro"),
    15. }
    16. UPGRADE = {
    17. "light_flash": "standard_pro",
    18. "discounted_flash": "standard_pro",
    19. "standard_pro": "premium_pro",
    20. }
    21. MAX_ATTEMPTS = 4 # Maximum total attempts per task
    22. OFF_PEAK_HOURS = range(0, 8) # Example: 00:00 to 08:00 business time is off-peak
    23. BIZ_TZ = timezone(timedelta(hours=8)) # Example: business timezone
    24. class TransientError(Exception):
    25. """Network errors, 5xx, and other retryable errors"""
    26. def pick_model(task_type: str, complexity: int, est_tokens: int, now: datetime) -> str:
    27. if est_tokens > MODELS["premium_pro"].ctx_limit:
    28. raise ValueError("Task exceeds maximum context; split it first")
    29. # 1. Choose a base model by task type and complexity
    30. if task_type == "cross_doc" or complexity >= 3:
    31. model = "premium_pro"
    32. elif task_type == "email" or complexity == 2:
    33. model = "standard_pro"
    34. else:
    35. model = "light_flash"
    36. # 2. Raise the model tier based on context length
    37. if est_tokens > MODELS["standard_pro"].ctx_limit:
    38. model = "premium_pro"
    39. elif est_tokens > MODELS["light_flash"].ctx_limit and model == "light_flash":
    40. model = "standard_pro"
    41. # 3. Switch lightweight tasks to discounted_flash during off-peak hours
    42. local_hour = now.astimezone(BIZ_TZ).hour
    43. if model == "light_flash" and local_hour in OFF_PEAK_HOURS:
    44. model = "discounted_flash"
    45. return model
    46. async def call_model(model: str, prompt: str) -> str:
    47. raise NotImplementedError("Replace with your team's SDK call")
    48. async def run_task(prompt, task_type, complexity, est_tokens, validate, now=None):
    49. now = now or datetime.now(timezone.utc)
    50. model = pick_model(task_type, complexity, est_tokens, now)
    51. log, attempts, upgraded = [], 0, False
    52. while attempts < MAX_ATTEMPTS:
    53. attempts += 1
    54. spec = MODELS[model]
    55. try:
    56. out = await asyncio.wait_for(call_model(model, prompt), timeout=spec.timeout_s)
    57. except asyncio.TimeoutError:
    58. log.append((model, "timeout"))
    59. if spec.fallback is None:
    60. raise
    61. model = spec.fallback # Fall back immediately on timeout; do not retry on the same model
    62. continue
    63. except TransientError:
    64. log.append((model, "error"))
    65. continue # Retry on the same model; counts toward total attempts
    66. if validate(out):
    67. return {"output": out, "model": model, "attempts": attempts, "log": log}
    68. log.append((model, "quality_fail"))
    69. if upgraded or model not in UPGRADE:
    70. raise RuntimeError("Quality validation failed and no upgrade model is available")
    71. model = UPGRADE[model] # Upgrade only one tier on quality failure
    72. upgraded = True
    73. raise RuntimeError("Exceeded maximum attempts")
    74. if __name__ == "__main__":
    75. async def demo_call(model: str, prompt: str) -> str:
    76. await asyncio.sleep(0.01)
    77. return f"{model} output: {prompt[:10]}"
    78. call_model = demo_call # Replace the placeholder function for the demo
    79. result = asyncio.run(run_task(
    80. prompt="Summarize the payment terms in this contract",
    81. task_type="email",
    82. complexity=2,
    83. est_tokens=1_200,
    84. validate=lambda s: len(s) > 0,
    85. now=datetime(2026, 11, 24, 20, 0, tzinfo=timezone.utc),
    86. ))
    87. print(result["model"], result["attempts"]) # Expected output: standard_pro 1