How to Build a Model Gateway: One API Entry Point for Multiple LLMs

    This article explains how to build a unified Model Gateway that lets applications call multiple large language models through a single entry point. It covers the engineering problems caused by heterogeneous model APIs, a five-layer architecture, unified request and response schemas, routing strategies, quota and cost governance, stability patterns such as circuit breaking and fallback, observability, and security practices, along with a phased rollout plan.

    1. The Problem: Why You Need One Entry Point for Multiple LLMs

    Recent industry trends show that some AI coding and office platforms have started integrating multiple third-party models through aggregation, while lowering the adoption barrier with limited-time offers. Setting specific products aside, this points to a clear engineering problem: when model supply shifts from a single source to multiple sources with different specifications and billing models, the application layer needs a unified entry point to contain the complexity.

    The benefits of using multiple models are clear:

    • Complementary capabilities: Different models have different strengths in long-context understanding, code generation, structured output, and reasoning depth.
    • Cost flexibility: Lightweight models handle high-frequency simple requests, while heavier models handle complex ones, making overall cost easier to control.
    • Availability redundancy: When a single service becomes unstable, traffic can switch to a backup model, reducing the overall failure rate.

    However, these benefits come with four types of engineering debt:

    1. Heterogeneous APIs: Providers differ in request and response structures, authentication methods, streaming protocols, and error code semantics.
    2. Difficult quota and limit governance: Each source has different limits, concurrency caps, and billing units, with no unified view.
    3. Incomparable quality: Without a shared evaluation set, you cannot tell whether a routing strategy is actually better.
    4. Fragmented observability: Logs, metrics, and traces are scattered, making fault localization costly.

    A unified entry point (a Model Gateway) is the architectural layer that addresses these problems.

    2. Target Architecture: A Layered, Decoupled Model Entry Point

    A robust design is typically divided into five layers, each with a single responsibility and the ability to evolve independently:

    1. API Layer: Exposes a unified protocol externally and hides backend differences.
    2. Router: Selects the target model based on policy.
    3. Adapter: Handles protocol conversion, parameter mapping, and streaming normalization.
    4. Governance: Manages quotas, rate limiting, degradation, and auditing.
    5. Observability: Provides metrics, logs, tracing, and evaluation feedback.

    A sample structure looks like this:

    1. Client
    2. -> Unified API (OpenAI-like / custom schema)
    3. -> Router (policies: cost/latency/capability/weight)
    4. -> Adapter A / Adapter B / Adapter C
    5. -> Upstream model services (multiple providers)
    6. <- Normalized response (including usage, finish_reason, trace_id)
    7. <- Governance (quota deduction, rate limiting, circuit breaking)
    8. <- Observability (metrics/logs/traces/evaluation samples stored)

    The key point is: the unified protocol exists only in internal and external contracts; all upstream differences are absorbed by the adapter layer.

    3. Unified Protocol Design: Turning Heterogeneity into Homogeneity

    Define an internal standard request and response structure with a minimal but complete set of fields:

    1. {
    2. "model_alias": "general-chat",
    3. "messages": [
    4. {"role": "system", "content": "..."},
    5. {"role": "user", "content": "..."}
    6. ],
    7. "temperature": 0.7,
    8. "max_tokens": 1024,
    9. "stream": true,
    10. "tools": [],
    11. "metadata": {"tenant": "t-1", "trace_id": "abc123"}
    12. }

    The unified response is:

    1. {
    2. "id": "chatcmpl-xxx",
    3. "choices": [{"index": 0, "message": {"role": "assistant", "content": "..."}, "finish_reason": "stop"}],
    4. "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
    5. "model_resolved": "vendorA-large",
    6. "trace_id": "abc123"
    7. }

    Design highlights:

    • Decouple model_alias from the real model: Applications only know aliases, and the router decides which real model to map to, making canary releases and switching easier.
    • Always populate usage: Whether or not the upstream returns usage, the adapter should make its best effort to estimate it and mark the source; otherwise quota governance is impossible.
    • Normalize error semantics: Map upstream errors to unified error codes (such as RATE_LIMITED, CONTEXT_TOO_LONG, CONTENT_FILTERED, UPSTREAM_UNAVAILABLE), while retaining the original information in logs.
    • Normalize streaming: Output uniformly as incremental events (deltas), hiding whether the upstream returns the whole response at once or token by token.

    4. Routing Strategies: From “Workable” to “Optimal”

    Routing is the core of a unified entry point. Common strategies can be combined:

    1. Capability routing: Select a model alias by task type (code, long-form text, structured extraction, conversation).
    2. Cost routing: Prefer lower-cost models as long as quality thresholds are met.
    3. Latency routing: Select based on real-time P95 latency to avoid slow nodes hurting the experience.
    4. Weighted/canary routing: Roll out a new model by percentage to control risk.
    5. Fallback routing: Degrade by priority when the primary model fails.

    A simplified runnable router example:

    1. class Router:
    2. def __init__(self, registry):
    3. self.registry = registry # alias -> [ {model, cost, p95, weight, quota} ]
    4. def pick(self, alias, task_type, tenant):
    5. candidates = [c for c in self.registry[alias] if c["quota"].available(tenant)]
    6. if not candidates:
    7. raise NoCapacityError(alias)
    8. # First filter by capability tags, then score by cost/latency weighting
    9. candidates = [c for c in candidates if task_type in c["tags"]] or candidates
    10. candidates.sort(key=lambda c: (c["cost"], c["p95"]))
    11. return candidates[0]["model"]
    12. def fallback(self, alias, failed_model):
    13. rest = [c["model"] for c in self.registry[alias] if c["model"] != failed_model]
    14. return rest[0] if rest else None

    Practical recommendations:

    • Do not rely only on static weights: Static weights cannot handle upstream fluctuations; incorporate real-time health signals.
    • Set quality gates: Use an offline evaluation set for regular regression checks, and automatically reduce the weight of models that fail quality standards.
    • Version aliases: Aliases like general-chat@2026-06 make changes traceable.

    5. Quota and Cost Governance: Making “Saving Quota” a Measurable Capability

    “Saving quota” is not just marketing language; it is a set of engineering controls:

    1. Unified quota ledger: Record remaining quota by tenant, application, and model alias; all requests are reserved first and settled afterward.
    2. Tiered model orchestration: Send simple requests to lightweight models and only escalate complex ones; a two-stage “light first, then heavy, escalate on failure” approach works well.
    3. Caching and deduplication: Apply semantic caching for identical prompts (pay attention to tenant isolation and expiration policies).
    4. Context compression: Trim history and summarize long contexts to directly reduce token consumption.
    5. Batching and off-peak scheduling: Combine offline tasks and avoid peak periods when quota is tight.
    6. Budget alerts: Automatically degrade or reject requests near the threshold to avoid unexpected bills.

    Simplified reserve-and-settle logic:

    1. def call_with_quota(alias, req, tenant):
    2. q = quota_ledger.reserve(tenant, alias, estimate_tokens(req))
    3. try:
    4. resp = upstream.invoke(alias, req)
    5. quota_ledger.settle(q, actual=resp.usage.total_tokens)
    6. return resp
    7. except UpstreamError:
    8. quota_ledger.release(q)
    9. raise

    Note: All billing and limit rules should follow the actual terms of service; keep them configurable in the architecture and avoid hard-coding the rules.

    6. Stability: Rate Limiting, Circuit Breaking, Degradation, and Retries

    Stability in a multi-model architecture comes from “redundancy plus isolation”:

    • Bulkhead isolation: Give each upstream its own connection pool and concurrency cap so one upstream cannot bring down the whole system.
    • Circuit breaking: Trigger a circuit break after consecutive failures, then use half-open probing after a cooldown.
    • Retry policy: Retry only idempotent errors, using exponential backoff with jitter and a total timeout budget.
    • Degradation chain: Primary model → backup model → cached result → explicit error, with fallback at each level.
    • Timeout budget allocation: Distribute the end-to-end timeout across routing, adaptation, and upstream calls to prevent layered waiting.
    1. def invoke_with_breaker(model, req):
    2. if breaker.is_open(model):
    3. nxt = router.fallback(req.alias, model)
    4. return invoke_with_breaker(nxt, req) if nxt else raise_friendly_error()
    5. try:
    6. return upstream.invoke(model, req)
    7. except UpstreamError as e:
    8. breaker.record_failure(model)
    9. if e.retryable and budget.left():
    10. sleep(backoff())
    11. return invoke_with_breaker(model, req)
    12. raise

    7. Observability and the Evaluation Loop

    Without measurement, there is no optimization. Build at least four capabilities:

    1. Metrics: QPS, P50/P95/P99 latency, error rate, token consumption, cache hit rate, and fallback rate, segmented by model alias and tenant.
    2. Logs: Structured records of request_id, alias, resolved_model, usage, and error codes, with sensitive content masked.
    3. Tracing: End-to-end traces to pinpoint whether time is spent in routing, adaptation, or upstream calls.
    4. Evaluation feedback: Sample real requests to build an evaluation set, regularly regress model quality, and drive routing weight adjustments.

    A minimal metrics list example:

    1. gateway_requests_total{alias,tenant,status}
    2. gateway_latency_seconds{alias,quantile}
    3. gateway_tokens_total{alias,type=prompt|completion}
    4. gateway_fallback_total{from,to}
    5. gateway_cache_hit_ratio{alias}

    8. Security and Compliance Essentials

    • Tenant isolation: Isolate caches, logs, and quotas by tenant to prevent unauthorized access and data mixing.
    • Data minimization: Transmit only necessary context, and mask or process sensitive fields locally.
    • Key management: Centrally manage and regularly rotate upstream credentials; never distribute them to the application side.
    • Auditing: Retain call audit records to meet traceability requirements.
    • Content safety: Apply unified pre- and post-filtering with normalized error codes to avoid policy gaps caused by upstream differences.
    1. Phase 1: Unified protocol plus single-model adaptation; get the contract and observability working.
    2. Phase 2: Integrate the second and third upstreams; enable routing and fallback.
    3. Phase 3: Quota ledger, caching, and context compression for cost optimization.
    4. Phase 4: Evaluation loop driving automatic weight adjustments, forming a continuous optimization mechanism.

    10. Conclusion

    The essence of “one entry point for multiple LLMs” is turning multi-source, heterogeneous model capabilities into governable, measurable, and evolvable internal infrastructure. The unified protocol contains differences, routing strategies unlock complementary capabilities and cost flexibility, quota governance turns “saving quota” into verifiable engineering metrics, and stability plus observability ensure long-term sustainability. For teams building intelligent applications, if you already use general-purpose capabilities such as object storage, message queues, container platforms, log services, and monitoring alerts from Baidu AI Cloud, you can deploy the gateway layer above as an independent service, integrate it with existing infrastructure in a decoupled way, and gradually evolve it into a mature model integration platform.