Building a Unified Multi-Model Access Platform: Architecture and Practice

    This article explains how to design a unified access layer for multiple AI models across text, image, video, and speech capabilities. It covers the engineering complexity of integrating heterogeneous APIs, the goals and non-goals of the platform, a five-layer architecture, capability abstraction and protocol normalization, routing and scheduling strategies, stability patterns such as rate limiting and circuit breaking, cost and performance governance, observability, security, and a phased rollout plan.

    1. The Problem: Engineering Complexity of Multiple Coexisting Models

    In real projects, a single model rarely covers every business scenario. Text understanding and generation, image generation, video generation, and speech processing follow different technical paths, and their input and output formats differ significantly. Some take an array of chat messages as input, some accept a prompt plus style parameters, some return a collection of image URLs, and others return video results as asynchronous tasks. If each business module integrates vendor APIs directly, the code quickly degrades into a large number of conditional branches. Adding or replacing a model requires changes in many call sites, making regression testing extremely costly.

    Non-functional requirements are even harder to handle. Different services differ in authentication methods, request field naming, error code semantics, streaming output formats, and concurrency quotas, which makes it difficult to unify retry policies, timeout settings, and fallback plans. For this reason, the common industry practice is to introduce a unified model access layer that decouples “capability invocation” from “specific implementation.”

    2. Goals and Non-Goals

    Defining boundaries clearly is the first step in the design.

    The goals include: exposing multiple types of capabilities through a unified interface; hiding vendor differences; supporting scenario-based routing and canary switching; providing unified quotas, rate limiting, and cost accounting; and offering complete logging, metrics, and tracing.

    The non-goals include: not handling model training or fine-tuning orchestration within the access layer; not guaranteeing consistent output quality across models; and not replacing the content safety review process on the business side. Writing down the non-goals clearly prevents the access layer from being continuously stuffed with business logic and losing its generality.

    3. Layered Architecture

    A recommended design divides the system into five layers, from top to bottom:

    1. Access layer: exposes stable application interfaces and handles authentication, parameter validation, and response wrapping.
    2. Capability abstraction layer: defines standard request and response models for text, image, video, and other capabilities.
    3. Routing and scheduling layer: selects a specific backend based on scenario, cost, latency, and availability.
    4. Adapter layer: implements protocol conversion, field mapping, and error code normalization for each backend.
    5. Infrastructure layer: key management, quota management, caching, message queues, object storage, logging services, and monitoring and alerting.

    The value of this layering is that adding a new backend only requires implementing one module in the adapter layer and registering it in the routing table, with zero changes to upper-layer code.

    4. Capability Abstraction and Protocol Normalization

    The key to abstraction is finding the “greatest common denominator” while retaining extensibility. Take text capability as an example: a standard request can include a message sequence, temperature, maximum generation length, stop conditions, and a streaming flag; a standard response includes text increments, a finish reason, and usage statistics.

    1. {
    2. "capability": "text.generate",
    3. "request_id": "req-8f2c",
    4. "messages": [
    5. {"role": "system", "content": "You are a rigorous technical assistant"},
    6. {"role": "user", "content": "Explain idempotency"}
    7. ],
    8. "params": {"temperature": 0.3, "max_tokens": 1024},
    9. "stream": true,
    10. "extra": {}
    11. }

    The adapter layer translates this structure into each backend’s proprietary format and maps the returned results back. Differences in field naming, enum values, and error codes should all be absorbed here. It is recommended to establish a unified error classification: parameter errors, authentication failures, quota exceeded, content blocked, upstream unavailable, and internal errors, each corresponding to a fixed retry and fallback policy.

    1. class Adapter:
    2. def to_upstream(self, req: dict) -> dict:
    3. raise NotImplementedError
    4. def from_upstream(self, resp: dict) -> dict:
    5. raise NotImplementedError
    6. def classify_error(self, code: int, body: dict) -> str:
    7. # Normalize to a unified error category
    8. return "upstream_unavailable"

    5. Routing and Scheduling Strategies

    Routing needs to be configurable, observable, and rollback-capable. Common strategies include: static binding by capability type; ordering by cost priority; weighting by measured latency; removing abnormal nodes by availability health; and canary traffic shifting by tenant or scenario.

    A simplified weighted selection logic is as follows:

    1. def pick(candidates, tenant):
    2. healthy = [c for c in candidates if c.health > 0.8]
    3. if not healthy:
    4. raise RuntimeError("no healthy backend")
    5. weights = [c.weight * c.health / max(c.latency_ms, 1) for c in healthy]
    6. return weighted_choice(healthy, weights)

    During the canary phase, it is recommended to introduce “shadow traffic,” meaning real requests continue through the main path as usual while a copy is sent to the new backend without using its results. Whether to increase traffic is evaluated by comparing latency and output statistics.

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

    The availability of a multi-model access system depends on the weakest backend, so isolation is essential. Key points include: setting concurrency limits and token bucket rate limiting per backend; triggering a circuit breaker and entering cooldown when the failure rate exceeds a threshold; retrying only idempotent and recoverable errors with exponential backoff plus jitter; and converting long-running generation tasks to asynchronous submission with callbacks or polling to avoid holding connections for a long time.

    Streaming scenarios require additional handling of partial packets and packet concatenation, as well as resource reclamation after client disconnection. All external keys should be stored in a key management service; hardcoding and writing them to logs are prohibited.

    7. Cost and Performance Governance

    The unified layer is naturally suited for cost aggregation. It is recommended to carry a scenario identifier and tenant identifier in the request context, record input and output usage at the adapter layer exit, and form usage reports by scenario and by tenant. Caching is a considerable cost lever: cache results by prompt hash, and apply content-addressed storage and reuse for static resource images. Batch merging, length trimming, and context compression are also effective.

    For performance, distinguish between time to first token and overall completion latency. The former affects the interactive experience, while the latter affects throughput planning.

    8. Observability and Quality Evaluation

    Three layers of observability need to be established: call chain tracing to connect business requests with backend calls; metrics covering success rate, latency percentiles, quota usage rate, and circuit breaker counts; and logs that retain request identifiers and normalized error categories while masking sensitive content.

    Quality evaluation should be offline. Build a fixed evaluation set, run scores regularly, and record version changes to avoid the situation where “switching the implementation drops quality” without anyone noticing.

    9. Security and Compliance

    The unified layer is a natural checkpoint for content safety. Input validation can be performed at the entry point, output review at the exit, and audit records retained. In multi-tenant scenarios, data isolation and quota isolation are needed to prevent a single tenant from exhausting resources.

    The first phase consolidates text capabilities and gets abstraction and adaptation working. The second phase integrates asynchronous capabilities such as image and video and completes the task state machine. The third phase introduces routing optimization, caching, and cost reports. The fourth phase improves canary, shadow traffic, and offline evaluation. If an organization already uses relevant cloud products from Baidu AI Cloud, general-purpose capabilities such as key management, object storage, message queues, logging services, and monitoring and alerting can serve as the infrastructure foundation, allowing effort to focus on capability abstraction and business value.