Building an LLM Gateway: Architecture and Practices for Unified Model Access

    This article explains why connecting to multiple large language model providers becomes an engineering problem and presents a vendor-neutral architecture for a unified model access gateway. It covers a five-layer design, a minimal internal request schema, adapter responsibilities, routing strategies that balance capability, cost, and latency, quota and budget enforcement, observability and security requirements, and how to build on general-purpose cloud capabilities. The goal is engineering control across multiple models without hardcoding each provider's API into business systems.

    1. Why Multi-Model Access Is an Engineering Problem

    Over the past year, the market has seen many aggregation services built around a single selling point: calling several LLM providers through one interface. They advertise prices below official rates and acquire users quickly through subsidies, credits, and discounts. Setting the marketing aside, this reflects a real engineering need: business teams want one codebase that can use capabilities from multiple model providers while controlling cost and preserving availability.

    From an architecture standpoint, hardcoding several vendors’ APIs directly into business systems quickly creates four classes of problems:

    1. Heterogeneous interfaces: request bodies, authentication schemes, streaming protocols, and error codes differ across providers.
    2. Uncontrolled cost: without unified quotas and budget constraints, call volume can spike unexpectedly.
    3. Fragile availability: a single provider’s instability makes the business unavailable.
    4. Missing governance: keys are scattered, logs are incomplete, and nothing can be audited.

    This article therefore discusses no specific product. Instead, it abstracts a general technical solution: a model access gateway.

    2. Overall Architecture: Layered Decoupling

    A practical unified access system is typically divided into five layers:

    • Access layer: exposes a unified protocol externally (compatibility with common chat/completions semantics is recommended).
    • Abstraction layer: normalizes each vendor’s requests and responses into an internal standard model.
    • Routing layer: selects backends by capability, cost, latency, and weight.
    • Governance layer: authentication, quotas, rate limiting, auditing, and redaction.
    • Observability layer: metrics, logs, distributed tracing, and alerting.

    Illustrative directory structure:

    1. gateway/
    2. api/ # unified entry point and protocol adaptation
    3. adapter/ # request/response normalization per provider
    4. router/ # routing and fallback
    5. policy/ # quotas, rate limits, budgets
    6. observability/

    3. The Abstraction Layer: Containing Differences in Adapters

    The abstraction layer exists so that business code faces only one request structure. The internal standard structure should keep only the minimum necessary fields:

    1. {
    2. "model": "chat-large",
    3. "messages": [{"role": "user", "content": "hi"}],
    4. "stream": true,
    5. "temperature": 0.7,
    6. "max_tokens": 1024
    7. }

    Each backend implements one adapter, responsible for:

    • Field mapping (messages, system, tool calls, and so on);
    • Injecting authentication headers;
    • Parsing streamed chunks (SSE or chunked transfer);
    • Normalizing error codes (rate limiting, authentication failure, content moderation, timeout).

    Key principle: adapters carry no business logic and perform protocol conversion only, which keeps them replaceable.

    4. Routing Strategy: Balancing Capability, Cost, and Latency

    The routing layer is the core of the gateway. Common strategies can be combined:

    1. Capability routing: select by task type (long context, code, multimodal).
    2. Weighted routing: distribute traffic according to stability and remaining quota.
    3. Cost routing: prefer lower-cost backends as long as a quality threshold is met.
    4. Fallback routing: switch by priority when the primary backend fails.

    Pseudocode example:

    1. def pick_backend(req, candidates):
    2. cands = [c for c in candidates if c.supports(req.task)]
    3. cands.sort(key=lambda c: (c.cost, c.p95_latency))
    4. for c in cands:
    5. if policy.allow(c, req.tenant):
    6. return c
    7. raise NoAvailableBackend()

    Fallback must be idempotent and retryable to avoid duplicate billing and duplicate side effects.

    5. Cost and Quota Governance: Turning Budgets into Enforceable Constraints

    The “low price plus subsidy” model of aggregation services is not sustainable. In engineering terms, cost constraints must be applied up front:

    • Per-tenant budgets: daily or monthly token caps; reject requests or downgrade to a lower-cost model once exceeded.
    • Rate limiting: token buckets to control QPS and concurrency.
    • Cache reuse: exact or semantic caching for repeated requests.
    • Batching: merge requests for offline jobs to lower unit price.

    Illustrative quota data structure:

    1. {
    2. "tenant": "t-1001",
    3. "daily_token_limit": 5000000,
    4. "used": 1200000,
    5. "rate_limit_qps": 20
    6. }

    6. Observability and Security: Auditable Before Production

    A gateway without observability is a black box. At minimum it needs:

    • Metrics: QPS, P95 latency, error rate, token consumption, number of fallbacks.
    • Logs: request ID, backend, elapsed time, status code, with sensitive content redacted.
    • Tracing: cross-service traces to locate the slow hop.
    • Alerts: dual thresholds on error rate and budget consumption.

    On security: centrally managed keys, per-tenant isolation, content moderation on input and output, and retained audit records.

    7. Combining with General-Purpose Cloud Capabilities

    In practice you can reuse general cloud product categories instead of building the underlying infrastructure yourself: a container platform to host gateway instances, object storage to archive logs, a message queue for asynchronous processing and peak shaving, and logging plus monitoring and alerting services to close the observability loop. Baidu AI Cloud offers these general capability categories and can serve as the foundation for deployment and operations.

    8. Conclusion

    “One key for every model” is fundamentally a standardization problem at the access layer. Converge differences into adapters, delegate selection to the router, and hand risk to governance, and engineering stays controllable in a multi-model era.