Multi-Model Routing and Cost Governance for AI Agents in Office Scenarios

    This article breaks down how to build a multi-model architecture for AI agents in office and productivity settings. It covers why office workloads are inherently heterogeneous, the four engineering problems that multi-model setups must solve, and how to address them with a unified model access layer, a comparable quota-cost unit, tiered routing with cascade escalation, off-peak scheduling, and end-to-end observability. Readers will learn how to route the right task to the right model at the right time, make cost measurable and enforceable, and turn a multi-model architecture from a maintenance burden into a competitive advantage.

    1. The Starting Point: Office Agent Workloads Are Inherently Heterogeneous

    An AI agent built for productivity scenarios never receives homogeneous requests. If you break down real traffic, it falls into roughly four categories:

    • Short-instruction tasks: Rewriting a sentence, generating an email subject line, format conversion. Short context and short output, low demand on model capability, but extremely sensitive to perceived latency — users typically expect the first token within 1–2 seconds.
    • Long-document tasks: Contract comparison, meeting-notes summarization, cross-document information extraction. Inputs easily reach tens of thousands of tokens, testing long-context stability and retrieval/localization ability.
    • Tool-calling tasks: Multi-turn function calls, cross-system queries, form filling. High demand on structured output (JSON Schema compliance) and call-orchestration ability.
    • Long-chain reasoning tasks: Solution design, data analysis, code generation and debugging. A single task may require dozens of reasoning turns, and cumulative token consumption is hundreds of times that of a short-instruction task.

    These four workload types have completely different optimal operating points across four dimensions: latency sensitivity, context length, reasoning depth, and unit cost. Expecting a single model to win on all dimensions simultaneously is engineeringly unsustainable: either you cover all traffic with the strongest model and lose control of cost, or you compress all cost with a lightweight model and see quality collapse on long tasks. So coexisting multiple models is not an optional optimization — it is an architectural necessity.

    This also means that once an agent product connects to multiple in-house and external models, its core competitiveness shifts from “which model to call” to “how to hand the right task to the right model at the right time, while keeping cost measurable, enforceable, and explainable.”

    2. Four Engineering Problems a Multi-Model Architecture Must Solve

    2.1 Missing capability abstraction layer

    Different model services differ greatly in protocol details: context window limits vary, streaming-event granularity varies (some push per token, others per sentence or paragraph), function-calling (Function Calling / Tool Use) schema styles differ, error-code systems differ, and retry semantics differ. If business code programs directly against one vendor’s SDK, switching models means rewriting a whole layer of invocation logic.

    2.2 Inconsistent cost accounting

    Vendors use different tokenizers, so the same Chinese text can produce noticeably different token counts across models. Billing dimensions are also inconsistent: some distinguish input and output unit prices, some price cache-hit prefixes separately, and some count intermediate tokens produced during reasoning as well. This means directly adding “1000 tokens of model A” to “1000 tokens of model B” produces a meaningless total.

    2.3 Variance in quality

    The difference in output quality between models on the same prompt is often not uniform — it depends heavily on the task type. And failures amplify cost: a retry triggered by a failed structured-output parse can double the token consumption of a single task. If a routing strategy considers only unit price, you get the counterintuitive result of “pennies saved per bit, more spent in total.”

    2.4 Operational elasticity needs

    Models get gradually rolled out, offered time-limited discounts, temporarily downgraded under capacity pressure, and eventually retired. If model IDs are scattered everywhere as string literals, any adjustment requires a full regression. Models must be treated as configurable resources, not hard-coded constants.

    3. A Unified Model Access Layer: Collapsing the Differences in One Place

    The engineeringly sound approach is to insert an adapter layer (Adapter / Gateway) between the business and the models. This layer exposes a single unified request semantics to the outside and adapts to each model on the inside. The core is a capability descriptor that declaratively expresses each model’s observable attributes:

    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class ModelDescriptor:
    4. model_key: str # Logical identifier; the business only recognizes this key
    5. context_window: int # Context window limit (tokens)
    6. max_output: int # Maximum output per single call
    7. supports_tools: bool # Whether tool calling is supported
    8. supports_stream: bool # Whether streaming is supported
    9. supports_vision: bool # Whether multimodal input is supported
    10. p95_latency_ms: int # Empirical latency percentile, used for routing scoring
    11. cost_rate: float # Quota multiplier relative to a standard workload
    12. capability_tags: tuple # Capability tags, e.g. ("long_ctx", "reasoning")
    13. deprecated: bool = False

    At minimum, the adapter layer must perform four kinds of normalization: message-structure normalization (a unified representation for system/user/assistant roles and multimodal segments), streaming-event normalization (unified into three event types: “incremental text + finish reason + usage statistics”), error-code normalization (distinguishing retryable rate-limiting errors from non-retryable parameter errors), and usage-statistic normalization (mapping each vendor’s input/output/cache/reasoning tokens into unified fields).

    1. @dataclass
    2. class NormalizedUsage:
    3. input_tokens: int
    4. output_tokens: int
    5. cached_tokens: int # Portion served by prefix cache hits
    6. reasoning_tokens: int # Explicit reasoning / thinking-process consumption

    Only with a unified usage structure can cost be computed uniformly. This layer is also the natural home for gradual rollout, circuit breaking, degradation, and rate limiting — business code does not need to know whether a model is being temporarily switched.

    4. Quota Consumption Multipliers: Compressing Heterogeneous Costs onto a Single Ruler

    To let users “choose a model based on actual need,” the product side must provide a cross-model comparable cost scale. A common industry approach is to introduce an internal standard quota unit and then convert each model’s real cost into a multiplier coefficient:

    1. rate multiplier = f(input tokens, output tokens, cache hits, reasoning tokens)
    2. quota consumed per task = rate multiplier × normalized workload
    3. normalized workload = w_in × normalized input + w_out × normalized output

    The “normalization” step is the key: to make results from different tokenizers comparable, each model’s raw token counts must be converted into a unified reference basis (for example, uniformly converted to character counts or token counts under a reference tokenizer), then multiplied by a coefficient weighted by output/reasoning — because the actual compute cost of output tokens and reasoning tokens is significantly higher than that of input tokens.

    For users, this mechanism should be presented as estimate + settlement, a dual value:

    • On the model-selection page, show the model’s multiplier tier (lower means cheaper) and give an estimated consumption range for the current task.
    • After the task finishes, write back the actual consumption; when the deviation from the estimate exceeds a threshold, use it to continuously calibrate routing strategy and display copy.

    For developers, the direct benefit is that cost can be written into the objective function. Routing is no longer a binary choice (expensive/cheap) but a budget-constrained optimization problem:

    1. def estimate_quota(model: ModelDescriptor, norm_workload: float) -> float:
    2. """Illustrative implementation: demonstrates the modeling idea only,
    3. not the interface of any real service."""
    4. base = (0.6 * norm_workload.input + 2.0 * norm_workload.output)
    5. discount_cache = 0.25 * norm_workload.cached
    6. overhead_reasoning = 1.5 * norm_workload.reasoning
    7. return max(0.0, (base - discount_cache + overhead_reasoning) * model.cost_rate)

    It is worth stressing that multipliers must be configurable and able to vary by time period. A time-limited promotion is essentially a temporary adjustment of the multiplier curve. If multipliers are compile-time constants, any campaign would require a release — an unacceptable organizational friction. The reasonable approach is to externalize the multiplier table as configuration and bring it under version control and auditing.

    5. Routing Strategy: From Rule Matching to Cascade Escalation

    5.1 A three-tier progressive routing decision

    • Rule layer: Hard filtering based on explicit constraints. For example, drop any model whose context window is smaller than the required length; exclude models without tool-calling support from agent-orchestration tasks. The rule layer guarantees correctness at the lowest cost.
    • Heuristic scoring layer: Within the candidate set, apply weighted scoring over task-feature-to-model-capability-tag match, latency, and cost. Task features can be produced by a lightweight classifier (or rule-based keyword + length + turn-count features).
    • Cascade escalation layer: This is the tier with the most significant cost-reduction effect. Try a low-cost model first, then decide whether to escalate to a stronger model based on objectively verifiable criteria.

    The key to cascading is not the naive idea of “cheap first, expensive later,” but the design of the escalation criteria. Usable criteria include: whether structured output passes schema validation, whether tool calls are successfully executed by downstream systems, whether the answer passes self-consistency sampling, whether key fields align with knowledge-base retrieval results, and whether code compiles and passes unit tests. Only when the criteria are automatically decidable is cascading reliable; otherwise escalation degenerates into random retries that waste budget for nothing.

    1. def cascade_solve(task, budget_quota, models_asc):
    2. spent = 0.0
    3. for model in models_asc:
    4. if spent >= budget_quota:
    5. break
    6. resp = invoke(model, task) # Unified invocation via the adapter layer
    7. spent += resp.quota_used
    8. if verifier(task, resp): # Automatically decidable acceptance criteria
    9. return resp, spent, model.model_key
    10. return fallback(task), spent, models_asc[-1].model_key

    5.2 Priority of explicit user selection

    Automated routing must not override a user’s clear intent. A reasonable product layering is: explicit user selection > user-set preference tier (economy / balanced / high-quality) > system auto-recommendation. The result of auto-recommendation is a suggestion, not a mandate; provide one-click switching and re-run, and keep a before/after cost comparison, so that the user’s choice is built on perceivable information.

    5.3 Online decisions under budget constraints

    In scenarios with an overall budget (such as billing against a per-user quota pool), routing must balance “current task quality gain” against “remaining budget longevity.” Engineeringly, this problem does not pursue global optimality but instead combines tiered quotas (allocating quota pools by user level) + budget-watermark control (automatically tightening routing when the watermark falls below a threshold, prioritizing low-multiplier models) + elastic refill (granting over-budget requests separately for high-value tasks).

    6. Off-Peak Scheduling: Taking Deferrable Load off the Critical Path

    A substantial share of load in office scenarios is deferrable: daily and weekly report generation, batch document summarization, scheduled data organization, and non-real-time archiving. These tasks are insensitive to the exact completion moment but contribute greatly to total throughput pressure. Taking them off the interactive critical path and placing them into an asynchronous task queue yields benefits on two dimensions at once:

    1. Cost dimension: Resource unit prices during off-peak/discount windows are usually lower. Concentrating deferrable load into these windows trades time for cost.
    2. Experience dimension: Interactive requests no longer compete with batch jobs for concurrency and quota, so first-token latency stability improves noticeably.

    There are four implementation essentials:

    • Tag every task with an elasticity flag (elastic=True) and a deadline (deadline); the scheduler uses these to decide whether deferral is allowed.
    • Tasks must be idempotent (deduplicated by an idempotency key) and support resume-from-checkpoint, to avoid a long task failing and requiring a full recompute.
    • Long tasks should use segmented submission (e.g., summarize by chapter in batches, then merge), which both lowers the cost of a single failure and makes progress viewable mid-way.
    • Clearly expose “estimated completion time” and “current execution tier” to users, avoiding the black-box feeling that async introduces.

    The queue and orchestration layer can reuse general cloud capabilities: a message queue carries asynchronous task distribution and delayed delivery, a task-orchestration/workflow service carries multi-step dependencies and state machines, object storage carries large intermediate artifacts, and logging and monitoring/alerting services carry execution traces and failure alerts. These belong to general cloud infrastructure categories. When selecting them, focus on delivery semantics (at-least-once vs. exactly-once), delayed-message support, backlog observability, and how they cooperate with the idempotency implementation.

    7. Observability: Closing the Loop on Cost Governance

    Optimization without measurement is guesswork. A multi-model architecture needs at least the following metrics, attributed across multiple dimensions of “user / scenario / task type / model / prompt template”:

    Category Key metrics
    Cost Quota consumed per task, escalation rate, retry rate, prefix-cache hit rate
    Latency First-token latency P50/P95, end-to-end P95, queue wait time
    Quality Structured-validation pass rate, tool-execution success rate, human-adoption rate, rework rate
    Stability Per-model error rate, rate-limit trigger rate, degradation-switch count, model availability

    The pair “escalation rate × post-escalation success rate” is the most worth watching. If the escalation rate is high but post-escalation success does not improve noticeably, the cascade’s acceptance criteria are too loose and budget is being wasted ineffectively; conversely, if the escalation rate is very low while human-adoption rate is also low, then the upstream model’s criteria are too strict or the routing threshold is set wrong.

    Two supporting pieces must be established: a regression benchmark set (fixed samples covering each task type, used to compare quality before and after a model switch or multiplier change) and a gradual-rollout mechanism (validate a new model on small traffic first, then ramp up gradually once metrics meet targets). Cost reduction must not come at the price of silent quality degradation, and the regression set is the only means of automatically detecting such silent degradation.

    8. Implementation Checklist and Risk Warnings

    When implementing, the following items are the easiest to overlook yet directly determine whether the architecture can evolve over the long term:

    • Models as configurable resources: Model IDs, multipliers, and weights are all externalized as configuration, supporting adjustment without a release and fast rollback; periodically drill the “a model becomes unavailable” degradation path.
    • Cost guardrails: Three levels of limits — per-user, per-tenant, and per-task; require a second confirmation when estimated consumption exceeds a threshold, to avoid an accidentally triggered long-chain task draining the quota.
    • Idempotency and retry discipline: Retry only rate-limiting and connection errors, and always use exponential backoff + jitter; fail fast on parameter errors, do not retry.
    • Explainable failures: On task failure, return a readable reason to the user (insufficient budget / input too long / model temporarily unavailable) rather than a vague “generation failed.”
    • Data compliance: Multi-model means data may flow to different processors. Sensitive fields must be masked or classification-tagged before entering the adapter layer, and the range of routable models should be decided by data classification; log-retention policies and the audit trail must be designed in advance.
    • Avoid single points of dependency: Keep at least one switchable fallback model on the critical path, and ensure at the architectural level that switching does not require code changes.

    In a hybrid architecture combining self-hosted model services and external models, general capabilities such as the underlying container platform, message queue, logging, and monitoring/alerting can be carried by the infrastructure tooling of cloud platforms such as Baidu AI Cloud, letting the team focus its attention on the two areas that truly determine product competitiveness: routing strategy and quality validation.

    9. Conclusion

    Connecting multiple models looks on the surface like an “onboarding” action, but in essence it is a process of engineering cost: first eliminate protocol differences with a unified access layer, then compress heterogeneous costs onto a comparable ruler with a unified quota multiplier, then write cost into the decision objective function with tiered routing and cascade escalation, and finally use off-peak scheduling and an observability loop to ensure the mechanism can be tuned continuously rather than configured once. When cost shifts from “something you only learn about when the monthly bill arrives” to “something every call can estimate, attribute, and constrain,” a multi-model architecture truly transforms from an architectural burden into a product advantage.