Multi-Model Routing and Cost Control for AI Agents in Office Scenarios
This article explores the challenges of balancing task performance, response speed, and cost for AI Agents in office scenarios. It explains why integrating multiple models is necessary, provides a practical approach to quota metering and cost calculation, and presents routing pseudocode with retry and fallback mechanisms. Additionally, it covers off-peak discount strategies and a step-by-step implementation roadmap for robust multi-model routing.
Conclusion First
AI Agents in office scenarios must satisfy three constraints simultaneously: task performance, response speed, and per-request cost. A single model rarely meets all three, so platforms typically route different task types to different models and define fallback paths for insufficient balance, timeouts, and service failures. Below, we outline selection criteria, metering methods, routing pseudocode, and strategies for triggering and monitoring off-peak discounts.
I. Why Integrate Multiple Models
Office tasks vary greatly in complexity. Text polishing and email drafting require low reasoning capabilities, where users prioritize speed and cost. Conversely, multi-step data analysis and complex code generation rely on flagship models with stronger reasoning abilities. Relying on a single model means either overpaying for simple tasks or compromising the quality of complex tasks.
Before integrating multiple models, determine the selection criteria. The table below lists five common dimensions and their evaluation metrics.
| Dimension | Meaning | Evaluation Metric Example |
|---|---|---|
| Task Performance | Proportion of outputs passing acceptance | Sample 50 tasks from the same batch, judge pass rate manually or via rules |
| Response Latency | Time from request to full output | Record P95 latency, not average |
| Per-Request Cost | Quota consumption calculated by tokens and rates | Calculate average quota per 1,000 tasks |
| Stability | Ratio of errors and timeouts | Calculate failure rate over the last 7 days |
| Context Capability | Stable input length capacity | Test with actual document lengths, not just nominal limits |
A multi-model matrix also provides disaster recovery capabilities. If the primary model’s availability drops or latency exceeds the threshold, the routing layer can switch to a backup model. When a new model goes live, it can first take 5% of traffic in a canary release, comparing pass rates and latency before gradually scaling up.
To prevent upper-layer scheduling logic from depending on specific vendors, platforms typically add a model abstraction layer. This layer unifies request structures, error codes, and token metering. Vendors tokenize differently; without unifying this at the abstraction layer, the cost of the same task across different models cannot be directly compared.
II. Quota Rates and Metering: How to Avoid Miscalculation
The basic formula for quota consumption is as follows. Example values are for illustration only; actual values depend on platform disclosures.
Per-Request Quota = token_count / 1000 base_price model_rate
Note three things during metering. First, record input and output tokens separately, as their prices may differ. Second, pre-deduct quota based on maximum output length before sending the request to ensure sufficient balance; settle based on actual tokens upon completion and refund the difference. Third, unify balance and budget units (e.g., use quota points for both), avoiding mixed units like dollars and points.
The pseudocode below demonstrates the complete flow of routing, pre-deduction, settlement, timeout retries, and fallback. provider_call is the internal vendor adapter function, whose implementation is omitted here.
import loggingimport timefrom dataclasses import dataclasslogger = logging.getLogger("model_router")@dataclassclass ModelSpec:name: strrate: float # Quota rate (example value)price_per_1k: float # Base quota per 1000 tokens (example value)p95_latency_ms: int # Historical P95 latency, used for timeoutMODELS = {"lite": ModelSpec("lite", 1.0, 0.2, 1200),"pro": ModelSpec("pro", 5.0, 1.0, 3000),"expert": ModelSpec("expert", 8.0, 1.6, 8000),}FALLBACK_CHAIN = {"expert": ["pro", "lite"], "pro": ["lite"], "lite": []}MAX_RETRIES = 2def estimate_cost(model, input_tokens, max_output_tokens):# Pre-deduction: estimated by max output length to ensure sufficient balancereturn (input_tokens + max_output_tokens) / 1000 * model.price_per_1k * model.ratedef settle_cost(model, input_tokens, output_tokens):# Actual deduction: settled by actual tokensreturn (input_tokens + output_tokens) / 1000 * model.price_per_1k * model.ratedef select_primary(task_type, urgency):if task_type in ("summary", "polish"):return "lite"if task_type in ("code", "reasoning") and urgency == "high":return "expert"return "pro"def call_with_retry(model, task):timeout_s = model.p95_latency_ms * 2 / 1000 # Timeout set to 2x P95for attempt in range(MAX_RETRIES + 1):try:return provider_call(model.name, task.prompt,timeout=timeout_s,idempotency_key=task.request_id)except TimeoutError:logger.warning("timeout", extra={"request_id": task.request_id,"model": model.name, "attempt": attempt})except ProviderError as err:if not err.retryable:breaktime.sleep(0.5 * 2 ** attempt) # Exponential backoffreturn Nonedef run_task(task, balance):primary = select_primary(task.task_type, task.urgency)for name in [primary] + FALLBACK_CHAIN[primary]:model = MODELS[name]reserve = estimate_cost(model, task.input_tokens, task.max_output_tokens)if reserve > balance:logger.info("budget_insufficient", extra={"request_id": task.request_id, "model": name})continue # Insufficient balance, fallback to next modelresult = call_with_retry(model, task)if result is None:logger.error("model_failed", extra={"request_id": task.request_id, "model": name})continue # Current model failed, follow fallback chaincost = settle_cost(model, task.input_tokens, result.output_tokens)logger.info("settled", extra={"request_id": task.request_id, "model": name, "fallback_from": primary,"rate": model.rate, "input_tokens": task.input_tokens,"output_tokens": result.output_tokens, "reserved": reserve,"charged": cost, "status": "ok"})return result, costraise RuntimeError("All models failed or balance insufficient")
The retry logic in the code relies on the vendor supporting idempotency keys. If the vendor does not support this, you must verify whether the previous request was billed before retrying, otherwise the same task may be charged twice.
Common errors in practice include:
- Selecting models based solely on rates while ignoring task performance. A low-rate model with a low pass rate may result in higher total rework costs.
- Retrying timeouts without idempotency protection, leading to duplicate charges.
- Using different units for balance and pre-deducted amounts, distorting comparison results.
- Failing to record
fallback_fromafter degradation, making it impossible to determine later whether cost changes are due to routing strategies or traffic variations.
III. Off-Peak Discounts and Task Orchestration
Off-peak discounts require specific trigger conditions and monitoring metrics to validate their effectiveness. Common practices involve three parts.
First, off-peak windows. Determine off-peak periods based on historical load curves, such as weekday nights. During these periods, platforms lower the rate for non-urgent tasks, encouraging users to execute long-running tasks at this time.
Second, automated toggles. Discounts within the window should consider real-time load, not just time. For example, enable discounts if GPU utilization is below 40% for 15 consecutive minutes and queue backlog is below a set threshold; disable if utilization exceeds 80%. Keep an interval between the two thresholds to prevent frequent toggling.
Third, asynchronous queues and rate limiting. Non-urgent tasks enter a message queue, consumed by worker nodes during off-peak hours. Simultaneously, set QPS limits per user or tenant to prevent free quotas from being consumed in bulk, which would squeeze resources for regular users.
For monitoring, track GPU utilization, queue wait time, P95 latency, and cost per task at minimum. Settlement records during promotional periods should carry a discount tag to avoid mistaking temporary discounted costs for long-term costs.
Free quotas fall under the same mechanism. Platforms can provide a daily fixed quota for lightweight models, charging standard rates for overages. These quotas lower the barrier for new users, and their costs should be accounted for as customer acquisition costs, not as benefits of the model routing itself.
IV. Implementation Boundaries and Roadmap
Routing effectiveness depends on evaluation data, budgets, and SLAs. No single rule is optimal for all scenarios. A three-step approach is recommended.
Step 1: Manually categorize task types, route with fixed rules, and record pass rates, latency, and quota for each call.
Step 2: Use accumulated data to adjust rules. For instance, if the pass rate for a certain coding task on the pro model meets standards, default to using the expert model less frequently.
Step 3: Once sufficient sample sizes are available, attempt to predict optimal choices using models. Predictions should serve as suggestions, with manual rules retained as a fallback.
During implementation, watch for four risks. Evaluation sets may not match real task distributions, causing routing biases. Vendors may adjust prices or rates, invalidating previous cost predictions. Rate adjustments alter user behavior, requiring budget reassessment. Transferring data across vendors must also comply with enterprise data compliance requirements.
