Multi-Model AI Gateway Architecture for Cost-Controlled Office AI

    This article explains how to build a model gateway that decouples office AI applications from specific LLM backends, enabling multi-model routing, normalized cost estimation, tiered task classification, and evaluation gates. It covers the gateway's core responsibilities, a minimal backend abstraction, configurable rate multipliers and budget guardrails, routing and fallback strategies, offline and online evaluation loops, and a pre-launch checklist for balancing quality, latency, and cost.

    1. Why Office AI Needs Multiple Models

    A recurring pattern in office AI adoption over the past two years is that no single model excels at writing well, reasoning accurately, running fast, and staying cheap at the same time. Tasks such as document drafting, meeting notes, spreadsheet processing, coding assistance, long-document summarization, and knowledge base Q&A differ dramatically in input length, reasoning depth, and output format constraints. Forcing one model to handle all of them often underperforms on some tasks while wasting resources on others.

    The industry has gradually converged on a principle: treat models as replaceable compute backends instead of hard-coding business logic to a specific model. This mirrors traditional layered service design, where upper layers depend only on abstract interfaces and lower layers remain pluggable, gradually releasable, and rollback-capable. Running multiple models together delivers three direct benefits: matching capability to each task, improving reliability through competition and gradual rollout, and enabling fine-grained cost governance based on rate differences.

    2. Defining the Capability Layer: Model Gateway Responsibilities

    The first step toward clean multi-model integration is a Model Gateway that decouples business code from concrete model implementations. The gateway typically handles six responsibilities:

    1. Protocol adaptation: normalize requests and responses from different backends into internal standard structures, hiding field differences.
    2. Routing decisions: select a backend based on task type, context length, latency budget, and cost ceiling.
    3. Rate limiting and quotas: apply token bucket and concurrency control per tenant, application, and user.
    4. Observability: record call traces, token usage, failure reasons, and cost per task.
    5. Fallback and retry: switch by priority when the primary model is unavailable to prevent single-point failures from spreading.
    6. Audit and compliance: retain call metadata to satisfy internal review and traceability requirements.

    A minimal internal abstraction can be written as follows. Note that it defines only a generic contract without any vendor-specific parameters:

    1. from dataclasses import dataclass
    2. from typing import Protocol, Optional
    3. @dataclass
    4. class ChatRequest:
    5. messages: list[dict] # [{"role": "user", "content": "..."}]
    6. max_output_tokens: int = 1024
    7. temperature: float = 0.3
    8. task_type: str = "general" # summary / code / table / qa ...
    9. deadline_ms: int = 8000 # latency budget
    10. cost_ceiling: float = 1.0 # cost ceiling for this task (relative unit)
    11. @dataclass
    12. class ChatResponse:
    13. text: str
    14. backend: str
    15. prompt_tokens: int
    16. completion_tokens: int
    17. latency_ms: int
    18. cost_units: float # normalized quota consumption
    19. class Backend(Protocol):
    20. def chat(self, req: ChatRequest) -> ChatResponse: ...

    Above the gateway, business code only declares what it wants to accomplish and no longer cares which model does the computation.

    3. Making Rate Multipliers a First-Class, Computable Concept

    The most valuable engineering idea in the original discussion is making quota consumption differences across models explicit, so users can anticipate cost before choosing. Generalized into common practice, this means introducing a normalized cost model:

    1. cost_units = (prompt_tokens + completion_tokens) * rate(backend, task_type) * time_factor

    Here, rate is the consumption multiplier for a model under a given task category, and time_factor is a time-based discount coefficient (for example, lower during off-peak hours). Moving cost from an after-the-fact bill to an upfront estimate is a key leap in user experience. Implementation points include:

    • Configurable multiplier tables: manage them through a configuration center with hot updates and gradual rollout support, rather than hard-coding them.
    • Upfront estimation interface: return an estimated consumption range before the user clicks “run” to set expectations.
    • Budget guardrails: enforce three-level budgets per task, per user, and per day; when exceeded, automatically fall back to a lower-cost backend or queue the request.
    • Cost attribution: attach cost_units to the call trace so costs can be allocated and reviewed by project or department.

    4. Task Tiering and Routing: Let Cheaper Models Handle Simple Work

    The most effective cost governance measure is not cutting prices but assigning the right task to the right model. Office tasks can be divided into three tiers by complexity:

    Tier Typical Tasks Selection Preference Key Constraint
    L1 Lightweight Classification, extraction, short rewriting, format conversion Low-multiplier, high-throughput backends Latency first
    L2 Standard Meeting notes, email polishing, summarization Medium-multiplier, stable output Balance quality and latency
    L3 Complex Long-document reasoning, code generation, multi-sheet analysis High-capability backends, multiple samples when needed Quality first, controlled cost

    For routing, a practical approach is “rules first, models later”: use interpretable rules to capture most traffic, then run small-scale evaluations to decide on adjustments:

    1. def route(req: ChatRequest, backends: dict[str, Backend]) -> Backend:
    2. if req.task_type in ("classify", "extract", "format"):
    3. return backends["cheapest"]
    4. if req.task_type in ("code", "reason_long"):
    5. return backends["strongest"]
    6. # Standard tasks: pick the lowest latency within budget
    7. candidates = [b for b in backends.values() if b.estimate(req) <= req.cost_ceiling]
    8. return min(candidates, key=lambda b: b.estimate_latency(req))

    Combined with a circuit breaker and fallback chain (strongest → balanced → cheapest), this keeps the system available during peak hours instead of letting all requests fail.

    5. Evaluation: Comparing Multiple Models Without an Eval Set Is Just Subjective Feeling

    The biggest risk of running multiple models is switching based on gut feeling. Two closed loops are required: an offline evaluation set and online gradual rollout.

    • Offline evaluation set: sample from real office corpora covering long documents, spreadsheets, code, and multi-turn conversations, with reference answers and scoring dimensions (correctness, completeness, format compliance, conciseness).
    • Automated metrics plus human spot checks: automated metrics assess format compliance and key point coverage, while human spot checks assess usability and tone.
    • Online A/B testing and gradual rollout: use task success rate as the core metric, supplemented by average latency, cost per task, and user retry rate.
    • Regression gate: before onboarding a new backend or changing multipliers, the baseline evaluation must pass; rollout is allowed only if metrics do not regress.

    A schematic evaluation loop:

    1. for case in eval_set:
    2. resp = gateway.chat(case.request)
    3. score = rubric(case.expected, resp.text) # 0~1
    4. report.append((case.id, resp.backend, score, resp.cost_units, resp.latency_ms))
    5. summary = aggregate(report) # output quality/cost/latency comparison by backend

    6. Pre-Launch Checklist

    1. Is the abstraction layer stable enough to swap backends with zero business code changes?
    2. Are multipliers and time coefficients configurable, with an estimation interface and budget guardrails?
    3. Are fallback chains, circuit breakers, retries, and idempotency in place?
    4. Does the call trace fully record tokens, latency, cost, and failure reasons?
    5. Is there an offline evaluation set and a gradual rollout gate that blocks rollout on metric regression?
    6. Is data compliance closed-loop: redaction, retention period, and access auditing?

    7. Conclusion

    The engineering dividing line for office AI is shifting from “which model to integrate” to “how to govern a group of models.” Making cost an estimable multiplier, making tasks a tiered routing decision, and making model selection a regression-tested evaluation—combined, these three practices achieve a stable balance among quality, latency, and cost. This methodology is vendor-agnostic and reusable by any platform capable of multi-backend integration; in related practices at Baidu AI Cloud, the same recommendation applies: use gateway abstraction, cost observability, and evaluation gates as the foundation for implementation.