Building a Multi-Model Gateway, Routing, and Observability Stack for Office AI Agents

    This article explains how to integrate multiple large language models (LLMs) into an office AI agent system without rewriting business code. It proposes a three-layer architecture: a gateway for unified API access and authentication, a routing layer for model selection based on task type, quota, and cost, and an observability layer for tracking token usage, spend, and failure reasons. The article defines key metrics, a total cost of ownership (TCO) formula, and a selection matrix that considers capabilities, latency, data compliance, and cost sensitivity. Designed for technical teams evaluating or building multi-model AI backends, the content focuses on practical design decisions while avoiding vendor-specific recommendations.

    Introduction

    Most office AI products historically bound to a single model provider. Switching models required changing business code. Now, the same entry point can connect to multiple providers, and the system can switch models per task. Three drivers push this change:

    1. Model capabilities differ by task. Long-document summarization depends on long context windows, data analysis relies on reasoning and code execution, and image/table multimodal tasks need strong visual understanding. No single model is optimal for all tasks.
    2. Price and availability fluctuate. Models with similar capabilities can differ in unit price by several times. Providers also adjust pricing, rate limits, or service status. Binding to one vendor leaves you passively waiting when prices rise or service degrades.
    3. Compliance requirements vary. Different data sensitivity levels may only allow certain models or deployment modes. Some data must be processed through private on-premise deployments or region-specific endpoints.

    The architecture discussed here assumes the following prerequisites:

    • Access method: Prefer standard HTTP APIs or compatible protocols from each provider, avoiding a separate SDK integration for each vendor.
    • Credentials: The gateway stores provider API keys. Business systems only receive internal tokens. Keys are kept in a secret management service, not in code or logs.
    • Network: Outbound requests go through a unified egress for auditing and access restriction. If data is internal, verify that the chosen model’s network path complies with internal policy.
    • Data classification: Before routing, evaluate the data sensitivity level to determine the allowed model list.
    • Failure fallback: If the primary model times out or returns an error, switch to backup models in a predefined order, with a maximum retry count.
    • Switch cost: Prompts, output formats, and evaluation results differ across models. Validate with the same evaluation set before switching.

    If some prerequisites are not met, the three-layer structure remains useful but delivers less value. For example, with only one model available, the gateway and observability layers still help, but the routing layer becomes trivial.

    Three-Layer Design

    1. Gateway Layer

    The gateway is the single entry point. It translates each provider’s request format into a unified internal format, handling authentication, timeouts, retries, and request body validation. Business systems call one API only; all provider differences are hidden behind the gateway.

    2. Routing Layer

    The routing layer decides which model to use for each call. It reads task type, data sensitivity, tenant, quota remaining, and unit price, then outputs a model selection result along with a fallback list. Quotas are used for rate limiting and budget control—for example, a monthly spending cap for a department. Quotas only gate whether a call can be sent; they do not choose which model. Keep quota checks and model selection separate to avoid ambiguity when debugging why a call used a particular model.

    3. Observability Layer

    The observability layer records key data for every call. It answers three questions: how much was spent, how many tokens were used, and at which step a failure occurred.

    The table below maps responsibilities across the three layers.

    Layer Primary Responsibility Input Output Key Metrics Failure Handling
    Gateway Unified API, auth, timeout & retry Business request Standardized request/response Success rate, P95 latency Retry by error code; return degraded result after max attempts
    Routing Model selection, quota check Task type, data sensitivity, quota, unit price Model name & fallback list Routing hit rate, quota rejection rate Switch to fallback if primary unavailable
    Observability Usage, cost, failure logging Per-call logs Reports & alerts Token counts, per-call cost, failure category Logging failure does not block main flow, but must alert

    Metrics Definitions

    Define metrics precisely before collecting data; otherwise, numbers from different teams are not comparable.

    • Token counting scope: Input tokens include system prompts, conversation history, and text extracted from attachments. Output tokens include all content returned by the model; if the provider charges for reasoning tokens, include those too. Record both categories separately.
    • Cost unit price source: Use the official price list of each provider as the source of truth. Record the price version and effective date. When prices change, historical costs are calculated at the prices in effect at that time—never use current prices retroactively.
    • Failure cause classification: At minimum, classify into: authentication failure, quota rejection, timeout, content filtering, invalid response format, and other. Do this classification at the gateway layer uniformly; do not rely on provider-specific error messages.
    • Sampling approach: Record full metadata for every call: model, latency, token counts, status code. Sample request and response bodies only partially, with the sampling ratio determined by compliance; always redact sensitive data before storage.

    Total Cost of Ownership (TCO) Formula

    Cost accounting for a single model is straightforward. With multiple models, hidden costs must be included. The formula below is calculated monthly:

    TCO = Σ(i=1 to n) [ (T_in,i × P_in,i + T_out,i × P_out,i) × (1 + r_i) ] + C_dev + C_ops + C_switch + C_comp

    Where:

    • T_in,i, T_out,i = total input and output tokens consumed from model i in the month.
    • P_in,i, P_out,i = input and output unit prices for model i, with units consistent with token counts.
    • r_i = additional retry ratio for model i, defined as the proportion of tokens resent in failed requests relative to the total token usage of that model. The more failures, the higher this factor.
    • C_dev = one-time development cost amortized per month, including effort for gateway, routing, and evaluation tooling.
    • C_ops = operational cost, including key rotation, monitoring/alerts, and on-call support.
    • C_switch = switching cost, including prompt rewriting, regression evaluation, and user training, amortized over planned switch frequencies.
    • C_comp = compliance cost, including data audits, redaction tools, and third-party compliance assessments.

    Two points to note:

    1. Use the same time period for unit prices and token counts.
    2. The variable n only counts models actually invoked during the month; inactive models are excluded.

    To compare two architecture or vendor options, run the same task sample through both, compute each TCO, then divide by the number of completed tasks to get a per-task cost. Comparing only unit prices can miss retry, switching, and compliance expenses.

    Model Selection Matrix

    When choosing models, first review the task requirements, then check constraints, and finally compare total costs. The table below offers a general decision framework—actual models must be validated with your own evaluation results.

    Task Type Key Capability to Check Data Sensitivity Requirements Latency Requirements Cost Sensitivity
    Long-document summarization Long context window length May require private deployment Moderate Medium
    Data analysis & code execution Reasoning, code generation, tool use Possibly high for sensitive data Low to medium High
    Multimodal (images, tables) Visual understanding, layout parsing Depends on source data Medium Medium to high
    Customer-facing chat Response quality, instruction following Often low or anonymized Low High
    Internal knowledge QA Retrieval quality, citation ability Often high Medium Medium

    Choose models after running your own benchmarks on the exact prompt and task templates you plan to use. Do not rely solely on vendor marketing claims. Also consider rate limits and regional availability, especially if your data must remain within certain jurisdictions. When multiple models meet the technical and compliance thresholds, use the TCO formula to compare per-task costs across a realistic workload sample.

    Conclusion

    Integrating multiple models into office AI agents can be cleanly separated into three layers. The gateway unifies interfaces and hides provider differences. The routing layer selects models based on task, quota, and cost policy. The observability layer records token usage, spend, and failure causes. Each layer manages one concern, so you can replace any layer without significant changes to the others—provided you keep the interfaces between them stable. Define metrics precisely, include hidden costs in your TCO, and validate model choices with your own test set before switching.