Multi-Model AI Agent Platforms for Office Work: Model Gateway, Task Routing, and Cost Governance

    This article explains how to build an AI agent platform for office productivity scenarios that supports multiple large language models without losing control of cost. It covers why a single model cannot serve heterogeneous office tasks, a reference architecture built around a model gateway with a capability registry, scheduling layer, and metering layer, how to implement a unified adapter and routing strategy, how to convert per-model pricing into a single quota multiplier, how off-peak discounts should be wired into scheduling, and how to design fallback chains, caching, rate limiting, observability, and compliance guardrails. It closes with a three-phase rollout plan and a pre-launch checklist. The goal is a platform where model choice is accurate, cost accounting is transparent, and degradation is stable.

    1. Why Office Agents Need Multiple Models

    A productivity-oriented AI agent differs fundamentally from a chat-style Q&A assistant: it does not just emit text, it accepts a goal, runs a workflow, and delivers an artifact. Typical tasks include parsing and summarizing long documents, extracting and structuring table data, drafting and rewriting proposals, generating and refactoring code, understanding images and screenshots, and turning meeting recordings into structured notes. These tasks vary enormously in input length, reasoning depth, structural constraints, and latency tolerance — which is why “one model for everything” fails both technically and economically.

    Three dimensions of heterogeneity explain the problem:

    • Capability heterogeneity: Long-context handling, tool calling, multimodal understanding, and strict structured output mature at very different rates across models.
    • Cost heterogeneity: Per-token prices can differ by an order of magnitude, and for long tasks that absolute gap is amplified further by input length.
    • Latency heterogeneity: Lightweight models typically have a much lower time-to-first-token than heavy reasoning models, and interactive scenarios are highly sensitive to first-response latency.

    The architectural conclusion is clear: an office agent platform should not treat models as a “kernel.” Models should be treated as pluggable, measurable, and degradable infrastructure. The common industry evolution path is: unified abstraction layer → model registry → task routing → quota metering → closed-loop cost operations.

    2. Reference Architecture: A Model Gateway with Four Horizontal and Two Vertical Layers

    Use a model gateway as the single ingress and egress point, so all model differences converge in one place:

    • Adapter layer: Protocol conversion for message formats, system prompts, tool calls, streamed chunks, and multimodal inputs.
    • Capability registry layer: Capability tags and specification metadata for every available model, serving as the single source of truth for routing and UI display.
    • Scheduling and decision layer: Task profiling, routing policy, concurrency limits, circuit breaking and fallback, result caching.
    • Metering and billing layer: Normalized token accounting, multiplier conversion, time-window discounts, budget guardrails, and itemized bills.
    • Two vertical concerns: Observability (logs, metrics, distributed tracing, cost dashboards) and security/compliance (data classification, key and quota isolation, content safety, audit trails).

    Model metadata should be registered centrally rather than scattered across business code, where capability judgments inevitably drift:

    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class ModelSpec:
    4. model_id: str # internal identifier; shown to users as a generic name
    5. version: str
    6. ctx_window: int # maximum context length (tokens)
    7. supports_tools: bool # tool / function calling support
    8. supports_vision: bool # image input support
    9. structured_output: str # "none" | "json_mode" | "schema"
    10. latency_tier: str # "fast" | "standard" | "deep"
    11. quality_tier: str # derived from offline benchmark scores
    12. quota_factor: float # quota consumption multiplier, 1.0 = baseline
    13. input_price: float # input price per 1K tokens (internal accounting basis)
    14. output_price: float
    15. compliance_scope: str # "public" | "private" | "restricted"

    Two rules matter here. quality_tier and latency_tier must come from repeatable offline evaluation (a fixed benchmark set + manual spot checks + automated scoring), never from subjective labeling. And quota_factor must be derived from the pricing basis rather than filled in by hand — otherwise every later billing dispute becomes unexplainable.

    3. Unified Abstraction and Adapter Implementation Details

    An office agent’s call patterns are far more complex than a single completion request: multi-turn context, tool-calling loops, structured result write-back, chunked batch processing of long documents, and streamed rendering. The adapter layer has to smooth over differences on each of these points:

    1. Message and role normalization: Models differ in how they support the system role and multimodal message blocks, so adapters must perform equivalent conversions (for example, merging the system prompt into the first user message).
    2. Usage normalization: Collect prompt_tokens / completion_tokens / total_tokens uniformly. For models that do not expose that granularity, apply an auditable estimation method and mark the resulting bill entries as “estimated.”
    3. Tool-call protocol normalization: Use one internal tool description and call structure, then parse outputs into uniform structured events for the agent orchestrator to consume.
    4. Streaming and timeout normalization: Standardize time-to-first-token timeouts, overall timeouts, and chunk aggregation strategy. If a stream breaks, already-generated content must still be persisted so a whole run is not wasted (and quota is not burned for nothing).
    5. Failure semantics normalization: Distinguish retryable errors (rate limiting, timeouts, 5xx) from non-retryable ones (invalid parameters, content policy blocks, context overflow). These two classes must follow completely different handling paths.

    The value of adapters is that they reduce N×M integration complexity to N+M: business code sees only one unified interface, and onboarding a new model requires one new adapter plus one registry entry.

    4. Task-Profile-Driven Model Routing

    The goal of routing is not “always pick the best model,” but “pick the cheapest and fastest model that still meets the quality constraint.” A two-stage design — rules first, policy as fallback — works well.

    Stage one: build the task profile. A lightweight classifier or rule set extracts routing signals from the goal description, attachment characteristics, and position in the call chain:

    • Input size: estimated_tokens, including a post-parsing estimate for attachments
    • Task type: generation / extraction / summarization / reasoning / code / multimodal
    • Quality requirement: whether the output is a customer-facing deliverable, whether a second validation pass is needed
    • Latency requirement: interactive (low first-response latency required) or batch (queueing acceptable)
    • Data classification: a hard constraint that determines the eligible model set

    Stage two: score and select. Among candidates that satisfy all hard constraints (long enough context, required capabilities, matching compliance scope), rank by a cost function:

    1. def route(task, candidates: list[ModelSpec]) -> ModelSpec:
    2. usable = [m for m in candidates
    3. if m.ctx_window >= task.estimated_tokens * 1.2 # keep a 20% margin
    4. and (not task.need_tools or m.supports_tools)
    5. and (not task.need_vision or m.supports_vision)
    6. and m.compliance_scope == task.data_scope]
    7. if not usable:
    8. raise NoCapableModel(task) # fail explicitly, never degrade silently
    9. def cost(m: ModelSpec) -> float:
    10. # cost-efficiency = quality gain / total cost; coefficients must be calibrated with online A/B tests
    11. est = m.input_price * task.estimated_tokens / 1000 \
    12. + m.output_price * task.estimated_output_tokens / 1000
    13. price_term = est * m.quota_factor * task.discount_factor
    14. latency_term = 0 if task.deadline_ms is None else \
    15. max(0, m.expected_latency_ms - task.deadline_ms) * 0.01
    16. return (price_term + latency_term) / max(m.quality_score, 1e-6)
    17. return min(usable, key=cost)

    One hard-won engineering lesson: never expose raw technical parameters to users. Office users cannot judge “which model is right for writing a weekly report,” but they can judge task presets such as “quick first draft,” “deep reasoning,” and “batch processing.” The model selection page should therefore offer a task-based preset entry point, keep an advanced model-based entry point alongside it, and display the quota consumption multiplier next to each option. A lower multiplier means the same task deducts less, which is the cheapest possible way to build a user’s cost intuition.

    5. Quota Billing: Multipliers and a Single Metering Basis

    With several models coexisting, the billing challenge is that each model has a different unit price while user quota is a single currency. The standard industry solution is to introduce a unified standard quota unit and convert every model into it through a multiplier:

    1. quota consumed = (input tokens / 1000 × input multiplier + output tokens / 1000 × output multiplier)
    2. × time-window discount factor

    The multiplier definition must be explainable and auditable:

    • Pick one baseline model and set quota_factor = 1.0.
    • For every other model, multiplier = its per-token cost ÷ the baseline model’s per-token cost, computed separately for input and output.
    • When displayed to users, round the multiplier to one decimal place and add a note such as “approximately X times the baseline model.”
    1. def estimate_quota(model: ModelSpec, usage, discount: float) -> dict:
    2. base = (usage.prompt_tokens / 1000 * model.quota_factor_in
    3. + usage.completion_tokens / 1000 * model.quota_factor_out)
    4. return {
    5. "base_quota": round(base, 2),
    6. "discount": discount,
    7. "charged_quota": round(base * discount, 2),
    8. "estimated": usage.is_estimated, # distinguish measured from estimated; bills must flag it
    9. }

    Several guardrails have to ship alongside this:

    • Free allowance for small tasks: Keep a zero-cost channel for new-user onboarding and debugging, but pair it with per-user rate limits, a per-task token ceiling, duplicate-request deduplication, and content-fingerprint risk controls. Without them, free quota will be abused by scripts.
    • Budget guardrails: Support both individual and team budgets with alert thresholds at 80% and 100%. When a budget approaches its limit, automatically switch to a lower-multiplier model rather than aborting the task.
    • Pre-authorization and settlement: Long tasks should pre-deduct an estimate and then reconcile against measured usage (refund or charge the difference) so concurrent tasks cannot blow through a quota.
    • Explainable bills: Every deduction must be traceable to six elements — model + version + input/output tokens + multiplier + discount + actual quota charged. This single design choice does more to reduce support tickets than any other.

    6. Off-Peak Discounts and Peak-Shifting Scheduling

    Time-limited discounts are fundamentally a price signal used to smooth compute peaks and troughs. To generate real scheduling benefit, the billing side and the scheduling side must be linked:

    1. Configuration-driven discount tables: Configure by “time window × model × discount factor,” support separate calendars for workdays and holidays, and support canary rollout plus one-click rollback.
    2. Task classification: Tag tasks explicitly as interactive (a user is waiting; delays forbidden) or deferrable (batch exports, scheduled summaries, bulk translation; queueing allowed). Only the latter enter the discount-window schedule.
    3. Discount transparency: Discounts must appear in the itemized bill and in the quota-consumption prompt, and the estimated actual charge must be stated before the task starts. If users never see the discount take effect, the discount policy delivers zero value.
    4. Lower multipliers for lightweight models: Reducing the multiplier on lightweight models is equivalent to lowering the marginal cost of simple tasks. It naturally steers a large volume of low-risk requests toward lightweight models and preserves heavy reasoning capacity for high-value work.
    1. def discount_at(model_id: str, ts: datetime, calendar) -> float:
    2. if not calendar.is_holiday(ts) and calendar.in_window(ts, "workday_offpeak"):
    3. return calendar.factor(model_id, default=0.6)
    4. if calendar.is_holiday(ts) and calendar.in_window(ts, "holiday_offpeak"):
    5. return calendar.factor(model_id, default=0.7)
    6. return 1.0

    7. Stability: Fallback Chains, Caching, and Rate Limiting

    The biggest payoff of a multi-model architecture is actually redundancy. Build an explicit fallback chain and annotate each hop with its cost and quality loss:

    1. def invoke_with_fallback(task, chain: list[str]):
    2. last_err = None
    3. for i, mid in enumerate(chain):
    4. try:
    5. return call(mid, task), {"model": mid, "degraded": i > 0}
    6. except RetryableError as e:
    7. last_err = e
    8. sleep(backoff(e, attempt=i)) # exponential backoff with jitter
    9. continue
    10. except FatalError as e:
    11. last_err = e
    12. continue # switch models instead of retrying the same one
    13. raise AllModelsFailed(last_err)

    Supporting requirements:

    • Result caching: Cache keys should include normalized prompt + model identifier + version + key parameters (temperature, structure constraints), and the prompt should state that cache hits are not billed again. Retrieval-style tasks must also include the data source version, or they will return stale conclusions.
    • Concurrency and rate limiting: Maintain a token bucket per model so that saturating a single model does not trigger a global cascade. Internal agent tool calls need rate limiting too.
    • Idempotency: Any tool call with side effects (writing files, sending messages, editing tables) must carry an idempotency key, and retries must never produce duplicate side effects.
    • Quality gating: Structured output must pass schema validation with automatic retry; citation-based tasks must produce verifiable references; everything must pass the content safety policy before external delivery. When a fallback switches models, tell the user “this result was generated by the backup model” to avoid an expectation gap.

    8. Observability and Cost Operations

    Cost governance starts with visibility. A minimum viable metric set:

    • Quality: task success rate, schema validation pass rate, human adoption rate, rework rate
    • Performance: time-to-first-token P50/P95, end-to-end latency, timeout rate
    • Cost: average tokens per task, average quota per task, difference before and after multiplier conversion, savings from discounts, cache hit rate
    • Scheduling: routing distribution, fallback trigger rate, rate-limit rejection rate, share of peak-shifted tasks

    All metrics should support drill-down across four dimensions: model / task type / tenant / time window. In addition, routing decisions must record the reason for the decision (which candidates were filtered out by hard constraints, and which cost terms drove the final choice). Without that log, a quality regression cannot be attributed to the model rather than to the router.

    9. Security and Compliance Constraints

    Connecting multiple models naturally widens the data egress surface, so compliance has to be a hard routing constraint rather than a post-hoc audit:

    • Data classification bound to routing: Restricted data may only enter models whose compliance scope allows it, and may require a privately deployed form. The classification result travels with the task and must not be overridable by model-selection logic.
    • Key and quota isolation: Manage credentials per environment and per service, and isolate quotas and budgets between tenants so one tenant cannot exhaust a shared pool.
    • Prompt injection protection: Agents hold tool-calling permissions, so instruction-like content inside external documents must be treated as untrusted data. On the tool side, follow least privilege and require secondary confirmation.
    • Audit trails: Retain the full request, model, version, usage, discount, and result summary so every run remains traceable.

    10. Rollout Plan and Launch Checklist

    Roll out in three phases instead of attempting a single big-bang rewrite:

    • Phase 1 — Abstraction: Extract a unified invocation interface and adapters, then connect a self-developed model plus one external model to validate protocol normalization and usage-accounting accuracy.
    • Phase 2 — Operability: Complete the model registry, routing policy, quota multipliers, and itemized bills; ship task-preset selection and multiplier display.
    • Phase 3 — Cost closed loop: Add the discount calendar, budget guardrails, fallback chains, caching, and cost dashboards, then calibrate the routing cost-function weights against real traffic data.

    Most of the underlying capabilities map to general-purpose cloud product categories: a container platform to host the gateway and adapter services, a message queue to absorb deferrable tasks, object storage for artifacts and cache snapshots, and logging plus monitoring/alerting services to support metric drill-down and anomaly detection. Cloud platforms such as Baidu AI Cloud typically expose many model capabilities through a unified model service catalog, which makes it possible to connect and meter everything under a single abstraction layer — a key prerequisite for multi-model governance. Confirm current model availability and regional support in the official documentation.

    Pre-launch checklist:

    • Are multipliers derived from the pricing basis and explainable to users?
    • Does hard-constraint filtering cover context length, capability support, and compliance scope?
    • Does the free allowance have rate limits, a per-task ceiling, and deduplication risk controls?
    • Does a budget breach trigger degradation rather than a hard stop?
    • Does every model have a defined fallback target with a stated quality loss?
    • Can each bill entry be traced back to a single call by the six elements?
    • Do discounts show up in scheduling, in the pre-task estimate, and in the actual charge?
    • Do structured outputs and side-effecting tool calls both have validation and idempotency guarantees?

    Bottom line: The hard part of multi-model integration is not connecting the models — it is choosing accurately, accounting transparently, and degrading gracefully. Converge model abstraction into a gateway, delegate selection to cost-based routing, convert cost into a unified quota multiplier, and turn discounts into an observable scheduling signal. Only then can an AI agent product make a continuously explainable trade-off between quality, latency, and cost.