Building a Unified Model Invocation Gateway: Architecture and Practices
This article explains how to build a unified gateway for calling multiple large language models. It covers the complexity of multi-model environments, a five-layer architecture, scoring-based routing, failover and fallback mechanisms, cost and caching strategies, adaptation to domestic compute hardware, a workflow for onboarding new models, and observability and governance recommendations.
1. Background: Invocation Complexity in the Multi-Model Era
When a business depends on multiple large models at the same time, teams quickly run into three types of problems: inconsistent interface shapes, differing provider availability and rate-limiting policies, and cost structures that are hard to predict. If each business team connects directly on its own, key management, retry strategies, and logging standards diverge rapidly, and the cost of locating failures rises sharply. The value of a unified model invocation gateway is precisely to consolidate these cross-cutting concerns in one place.
Typical pain points can be summarized as follows:
- Fragmented interfaces: request and response structures, streaming return methods, and error code semantics are inconsistent across sources.
- Single-point dependency: a fluctuation in a single source makes the business unavailable.
- Uncontrollable costs: there is no usage aggregation or budget constraint by tenant or by business line.
- Compliance and domestic technology stack requirements: the system needs to run on domestic chips and a localized software stack.
2. Target Architecture: A Five-Layer Design
A practical unified invocation platform is typically divided into five layers, decoupled from top to bottom:
- Access layer: exposes a stable protocol contract externally and hides backend differences.
- Routing layer: filters and scores candidates based on capability tags, cost, latency, and quota.
- Execution layer: handles retries, timeouts, circuit breaking, concurrency, and stream forwarding.
- Optimization layer: semantic caching, batching, prompt compression, and result reuse.
- Governance layer: authentication, quota, metering, auditing, and observability.
A sketch of the unified protocol contract (pseudocode that only expresses structure and does not point to any specific interface):
# Unified request model: business teams depend only on this layer@dataclassclass ModelRequest:task: str # capability tag: chat / embedding / rerank, etc.messages: list[dict]max_tokens: int = 1024temperature: float = 0.7stream: bool = Falsetenant_id: str = ""budget_hint: float | None = None # soft budget constraint@dataclassclass ModelResponse:text: strusage: dict # input/output token meteringprovider_tag: str # internal identifier, not exposed externally as a brandlatency_ms: intcache_hit: bool
The key point is that capability tags, rather than specific model names, are the stable basis for routing and disaster recovery. Model names iterate frequently, while capability tags are relatively stable.
3. Intelligent Routing: From Rules to Scoring
Routing should not be a simple if-else chain, but an explainable scoring function. The candidate set is first filtered by hard constraints (capability match, compliance region, remaining quota), then ranked by soft metrics:
score = w1 * capability_fit+ w2 * (1 - normalized_latency)+ w3 * cost_efficiency+ w4 * reliability- w5 * current_load
In engineering practice, it is recommended to make the weights configuration items and differentiate them by business line: online customer service favors latency and reliability, while offline batch processing favors cost efficiency. Routing decisions must be logged; otherwise, production behavior cannot be reviewed afterward.
4. Failover and Fallback: Availability Comes from Redundant Design
The availability ceiling of a single direct connection is the availability of the provider. A gateway should raise overall availability through multi-source redundancy. Core mechanisms include:
- Layered timeouts and retries: short connection timeout and long read timeout; retry only idempotent requests, using exponential backoff with jitter.
- Circuit breaking and half-open probing: enter the circuit-broken state after consecutive failures, and periodically let a small amount of traffic through to test recovery.
- Fallback chain: when the primary model is unavailable, switch to a backup model with an equivalent or approximate capability tag; if that is also unavailable, return a cached result or a templated fallback.
- Cell-based isolation: partition concurrency and quota by tenant to prevent a single large customer from dragging down the whole system.
async def call_with_fallback(req: ModelRequest):for candidate in router.rank(req): # already ranked candidatestry:return await executor.run(candidate, req, timeout=candidate.timeout)except RetryableError:continue # switch to the next candidateexcept NonRetryableError as e:metrics.incr("bad_request"); raise ereturn cache.get(req) or fallback_template(req)
It should be emphasized that availability targets such as 99.9% are design constraints. They should be validated through redundancy, failure drills, and monitoring alerts, rather than being considered achieved simply because they are written in a document.
5. Cost and Caching: Turning Utilization into a Cost Advantage
There are three practical paths to cost optimization. The first is to improve compute utilization by using virtualization partitioning and shared scheduling so that the same accelerator card can serve more concurrent inference tasks. The second is scheduling optimization, separating long and short requests into different pools to reduce fragmentation and queuing. The third is cache reuse, directly returning historical results for identical or highly similar requests.
Caching should distinguish two layers: exact caching uses a request fingerprint as the key; semantic caching matches by vector similarity and requires a similarity threshold and expiration policy to avoid conflating different intents. Hit rate, average similarity, and expiration reasons must be observable; otherwise, optimization cannot iterate.
def fingerprint(req: ModelRequest) -> str:payload = normalize(req.messages) + f"|{req.max_tokens}|{req.temperature}"return hashlib.sha256(payload.encode()).hexdigest()
6. Domestic Compute Adaptation: Abstracting the Device Interface
To run the same service across multiple types of domestic accelerator cards, the key is to introduce a device abstraction layer that encapsulates differences in operator implementations, memory management, and communication backends beneath the runtime, so that the upper layer programs only against unified tensor semantics. Adaptation work typically includes checking operator coverage and providing fallback implementations, precision alignment (threshold-based verification of numerical error), tuning memory and concurrency parameters, and managing a compatibility matrix of inference framework versions. On the model side, a unified weight conversion and quantization process forms a reusable adaptation pipeline, compressing the onboarding of a new model from “weeks” to “hours.”
7. Rapid Onboarding Workflow for New Models
Onboarding a new model after its release is essentially a standardized pipeline:
- Research: track architecture trends in advance and prepare weight conversion and operator mapping plans.
- Adaptation: complete precision alignment and performance baseline testing, and produce capability tags.
- Canary: validate with a small traffic share, comparing latency, error rate, and output quality.
- Ramp-up: gradually open access by tenant, keeping a one-click rollback available.
- Review: archive metrics and update routing weights and the cost model.
For business teams, the ideal experience is “changing only one parameter”: keeping the original invocation endpoint and credentials unchanged and switching only the capability tag or model identifier to complete the migration. This requires the gateway to strictly maintain backward compatibility during version evolution.
8. Observability and Governance
It is recommended to collect at least four categories of metrics: request volume, latency percentiles (P50/P95/P99), error classification, and token metering with cache hits. Logs need to include the routing decision path, and tracing should span from the gateway to the backend. On the governance side, implement key custody and rotation, per-tenant quota and budget alerts, data retention and masking policies, and audit trails.
9. Implementation Recommendations
Start with a pilot on a single business line, first fixing the protocol contract and metering standards, then gradually introducing multi-source redundancy, caching, and a domestic compute resource pool. Avoid pursuing full model coverage from the outset; first ensure that the capability tag system and rollback mechanism are reliable, then discuss scale and cost optimization.
