Multi-Model AI Platform Architecture: Engineering Practices for Routing, Metering, and Governance

    This article breaks down the technical architecture and engineering practices behind a multi-model AI platform that unifies heterogeneous large language models. It explains a four-layer decoupled design (provider adapters, unified gateway, routing and policy, governance), how to standardize messages, tools, images, and streaming events behind one request schema, how to enable in-conversation model switching through context normalization and artifact inheritance, how consumption ratios normalize cost and quota deduction, and how to operationalize vision and general coding capabilities with closed-loop verification. It also covers observability, common anti-patterns, and the core takeaway: converge heterogeneity with unified abstraction, match tasks with policy routing, normalize cost with a ratio model, guarantee quality with closed-loop validation, and support governance with observability.

    1. Technical Background: Why Platforms Move Toward Multi-Model Coexistence

    A clear signal has recently emerged in the industry: an intelligent workspace-style platform shipped a new version of its large model, adding enhanced visual understanding and general coding capabilities. More notably, its selectable model list includes both a self-developed model and multiple third-party models, each labeled with a different consumption ratio. Once you abstract away the branding, the real technical problem is a single one: how a developer-facing platform can onboard, schedule, meter, and govern multiple heterogeneous large models in a unified way.

    This is not as simple as adding one more dropdown option. Multi-model coexistence introduces four categories of engineering problems:

    1. Interface heterogeneity: Different models have different request/response structures, streaming protocols, function calling formats, and multimodal input encodings.
    2. Capability heterogeneity: Some models excel at long-context reasoning, some at code generation and refactoring, some can understand images or screenshots, and some offer better cost efficiency at lower ratio tiers.
    3. Metering heterogeneity: Different models have different compute costs, so the platform needs a relative coefficient such as a “consumption ratio” to normalize costs before deducting from a user’s quota in a unified way.
    4. Experience consistency: Users expect to switch models at any point within the same conversation to continue a task, which requires context, artifacts, and tool state to remain usable after a model switch.

    The sections below cover six layers: architecture, interfaces, routing, metering, capability implementation, and observability.

    2. Overall Architecture: Four-Layer Decoupling

    A multi-model platform built for long-term evolution should be decoupled into four layers:

    • Access layer (Provider Adapter): One adapter per model vendor or model family, responsible for protocol conversion, authentication, rate limiting, and retries.
    • Abstraction layer (Unified Model Gateway): Exposes a unified request model externally and hides the differences.
    • Scheduling layer (Router & Policy): Selects and switches models based on task type, context length, budget ratio, and availability.
    • Governance layer (Metering / Observability / Guardrail): Handles quota deduction, log tracing, content safety, and quality evaluation.

    An illustrative directory structure:

    1. model-platform/
    2. adapters/
    3. base.py # Unified adapter abstraction
    4. vendor_a.py # Adapter for a general-purpose large model
    5. vendor_b.py # Adapter for a vision-capable model
    6. gateway/
    7. schema.py # Unified request/response models
    8. stream.py # Unified streaming protocol
    9. router/
    10. policy.py # Routing and switching policy
    11. budget.py # Ratios and quota
    12. observability/
    13. tracer.py
    14. evaluator.py

    3. Unified Abstraction Interface: Confining Differences to Adapters

    The goal of the abstraction layer is to let upper-layer business code recognize only one request structure. The core is to standardize four elements: messages, tools, images, and streaming events.

    1. from dataclasses import dataclass, field
    2. from typing import Any, Literal, Optional
    3. @dataclass
    4. class ContentPart:
    5. type: Literal["text", "image", "tool_result"]
    6. text: Optional[str] = None
    7. image_ref: Optional[str] = None # Reference to a resource in object storage
    8. payload: Optional[dict] = None
    9. @dataclass
    10. class ModelRequest:
    11. messages: list[dict[str, Any]]
    12. tools: list[dict] = field(default_factory=list)
    13. temperature: float = 0.2
    14. max_tokens: int = 4096
    15. stream: bool = True
    16. extra: dict = field(default_factory=dict) # Vendor-specific parameters go here only

    Key design principles:

    • Capability manifest: Each adapter declares the capabilities it supports, such as supports_vision, supports_tool_call, and max_context. The scheduling layer filters based on these declarations rather than hard-coded if-else branches.
    • Degradation field isolation: Vendor-private parameters always go into extra to avoid polluting the unified semantics.
    • Externalized multimodal resources: Large objects such as images, screenshots, and log bundles are stored in object storage, and only a reference identifier is passed in the request. This reduces request body size and makes auditing and reuse easier.

    4. Routing and Switching: How In-Conversation Relaying Works

    The user requirement is to switch models on demand within the same conversation based on task needs. Engineering must solve three things: context portability, artifact inheritance, and state recovery.

    4.1 Context Normalization

    Different models accept historical messages differently (for example, whether system messages are allowed and how tool results are fed back). The approach is to maintain a platform-internal canonical conversation tree and, on each switch, have the adapter “project” the canonical conversation into a form the target model accepts:

    1. def project_messages(canonical: list[dict], adapter) -> list[dict]:
    2. msgs = []
    3. for m in canonical:
    4. if m["role"] == "system" and not adapter.manifest.supports_system:
    5. msgs.append({"role": "user", "content": "[Constraint] " + m["content"]})
    6. else:
    7. msgs.append(m)
    8. return adapter.normalize(msgs)

    4.2 Three Common Forms of Routing Policy

    • Based on task type: Data analysis and visualization, interactive reports, and web/app building each bind to a set of candidate models.
    • Based on budget ratio: Low-ratio models handle drafts and batch tasks, while high-ratio models are reserved for critical reasoning and final validation.
    • Based on quality feedback: Automatically validate the previous output (for example, whether code passes the build or whether chart data matches the source), and switch models to retry on failure.
    1. def choose(task: str, budget_ratio: float, manifest_list) -> str:
    2. cands = [m for m in manifest_list if task in m.capabilities]
    3. cands.sort(key=lambda m: (m.quality_hint / m.ratio, -m.ratio))
    4. for m in cands:
    5. if m.ratio <= budget_ratio:
    6. return m.name
    7. return cands[0].name

    4.3 Artifact Inheritance During Switching

    Code, chart configurations, and report structures should be persisted as first-class artifacts rather than living only in the conversation context. This way, when switching to a new model, you only need to inject an artifact summary and key snippets into the prompt, saving tokens while preserving continuity.

    5. Metering Model: The Correct Engineering Meaning of Consumption Ratios

    The original text mentions that different models are labeled with different ratios and that quota is deducted uniformly from a subscription. Abstracted into a general model:

    • Let the baseline model’s unit consumption be 1 quota unit;
    • For a model with ratio r, one call deducts tokens_used × r (using the platform’s defined billing token convention, usually distinguishing input/output);
    • A limited-time discount tier is equivalent to a temporary reduction of r, which requires ratio configuration with effective times rather than hard-coding it in code.
    1. @dataclass
    2. class RatioRule:
    3. model: str
    4. ratio: float
    5. effective_from: str
    6. effective_to: str | None = None
    7. def resolve_ratio(model: str, rules: list[RatioRule], now: str) -> float:
    8. for r in rules:
    9. if r.model == model and r.effective_from <= now and (r.effective_to is None or now < r.effective_to):
    10. return r.ratio
    11. return 1.0

    Engineering essentials:

    1. Configurable and auditable ratios: All ratio changes are logged and traceable, supporting the ability to review the basis for a given charge.
    2. Separation of pre-deduction and settlement: Long tasks are pre-deducted based on an estimate and then settled against actual usage afterward, preventing quota leakage.
    3. Budget guardrails: Set ratio and quota caps per session or per task, automatically degrading to a lower-ratio model or prompting the user for confirmation when exceeded.

    6. Implementation Notes for Vision and General Coding Capabilities

    6.1 Vision Capability

    Vision-capable models are typically used for: understanding UI screenshots, locating errors from screenshots, converting design mockups to code, and validating chart readings. Engineering notes:

    • Images should first undergo preprocessing and redaction (removing personal information, keys, and internal addresses);
    • Resolution and tiling strategy directly affect recognition quality and cost, so it is recommended to tier by task (thumbnail-based locating / local high-definition);
    • Vision output must go through structured validation, for example converting a recognized table into JSON and comparing it against the source data, rather than directly trusting a natural-language description.

    6.2 General Coding Capability

    “General coding” covers code generation, completion, refactoring, unit test generation, script writing, and configuration debugging. The key to reliable implementation is closed-loop verification:

    1. def coding_loop(task, model_router):
    2. draft = model_router.call(task, stage="draft")
    3. checks = run_lint_and_tests(draft) # Static checks + unit tests
    4. if checks.passed:
    5. return draft
    6. fix = model_router.call(task + checks.summary, stage="fix", prefer="high_quality")
    7. return fix if run_lint_and_tests(fix).passed else escalate_to_human(fix, checks)

    Making “generate—verify—fix—escalate to human” a closed loop improves delivery quality more than simply switching to a stronger model.

    7. Observability and Governance

    The biggest fear in a multi-model environment is a “black box”: not knowing which model a given call used, how much quota it consumed, or why output quality fluctuates. A minimal viable observability set:

    • Call chain tracing: One user task → multiple model calls → artifact versions, fully replayable end to end.
    • Quality evaluation: Build/test pass rates for code tasks, numerical consistency checks for data tasks, and structural integrity checks for report tasks.
    • Cost and ratio dashboard: Aggregate quota consumption by model, task type, and user.
    • Safety guardrails: Bidirectional content moderation on input and output, sensitive information externalized to object storage with access control, and a prohibition on writing plaintext keys to log services.

    8. Common Anti-Patterns

    1. Writing vendor differences into the business layer: This forces business code changes every time a model is added.
    2. Hard-coding ratios: Discount promotions cannot take effect in time, and billing disputes are hard to trace.
    3. Switching models without validation: Quality becomes unstable, and users perceive it as “sometimes good, sometimes bad.”
    4. Injecting the full context without restraint: Token costs spike and key information gets diluted; summarization and retrieval-based injection should be used instead.
    5. Missing fallback paths: When a high-ratio model is unavailable, there is no degradation plan and the task fails outright.

    9. Conclusion

    From the phenomenon of “a platform launching a new model and opening access to multiple third-party models,” what is truly worth learning for developers is not any specific model but the engineering paradigm behind it: converge heterogeneity with unified abstraction, match tasks with policy routing, normalize cost with a ratio model, guarantee quality with closed-loop verification, and support governance with an observability system. Mastering this method lets you obtain an extensible, meterable, and fallback-capable foundation with low modification cost, whether for self-developed models or externally integrated ones. When needed, you can also quickly build the corresponding hosting and operations system based on general cloud product categories offered by Baidu AI Cloud (such as object storage, container platforms, log services, and monitoring/alerting).