Multi-Model Access for LLM Agents: Model Gateway Architecture and Practices

    This article explains how LLM agent applications can move from a single-model setup to a governed multi-model architecture using a model gateway. It covers a five-layer architecture, unified interface design, capability negotiation, routing strategies, stability controls, cost and capacity planning, security and compliance, evaluation, common pitfalls, and a phased rollout path. The focus is on building a model invocation layer that is replaceable, measurable, and controllable as models, vendors, and business scenarios change.

    I. Introduction: From Switching Models to Building a Model Gateway

    Recently, an office-productivity agent product added several third-party models alongside its in-house model. If this is understood only as a simple “model switch,” it overlooks the engineering implications behind it. For developers, the more valuable work is investing in the infrastructure of the model invocation layer: the model gateway. The gateway turns models from hard-coded dependencies inside business code into capability resources that can be centrally managed, routed on demand, and replaced at any time.

    A single-model architecture can be efficient during early validation, but once the product moves into production, it is continuously constrained by four factors:

    • Capability boundaries: Generation quality, reasoning depth, long-context handling, and multimodal capabilities are not evenly distributed across models. A single model rarely performs best in every scenario.
    • Cost structure: Using a flagship model for simple tasks increases average invocation costs. Differences in pricing models, context lengths, and output limits across providers further complicate model selection and cost accounting.
    • Stability and supply-chain risk: Rate limiting, outages, or version retirement from any provider can directly translate into unavailability for users. With only one model, fluctuation in one external dependency is enough to interrupt the entire business flow.
    • Compliance and data boundaries: Multiple providers mean data must move across more boundaries, which also makes compliance requirements more complex.

    Therefore, “adding more models” is the result; “having the capability to integrate and govern multiple models” is the goal. The following sections discuss architecture layering, interface abstraction, routing decisions, stability governance, cost optimization, security and compliance, the evaluation system, and a rollout path. Together, they form a model invocation system that is not locked to a single model.

    Terminology note: In this article, “Agent” refers to an application form driven by components such as planning, tool invocation, and memory, rather than a specific product. “Model” refers broadly to language model services that provide dialogue, reasoning, or generation capabilities.

    II. Architecture Layers: Decoupling Model Invocation from Business Logic

    A sustainable model invocation system is usually divided into five layers:

    • Access layer: Exposes unified interfaces to business systems for dialogue, completion, embedding, and other operations, while hiding differences among underlying models.
    • Orchestration layer: Handles prompt assembly, tool definitions, memory retrieval, and multi-turn loop control for agents. It does not directly perceive specific models.
    • Routing layer: Selects models based on task characteristics, capability constraints, cost and quality preferences, and tenant policies. It also maintains fallback chains.
    • Adaptation layer: Translates the unified internal protocol into the request format of each model and normalizes responses back into a unified structure.
    • Governance layer: Covers authentication and authorization, key management, quotas and rate limiting, content safety, logging and auditing, and monitoring and alerting.

    The overall structure is as follows:

    1. ┌───────────────────────────────────────────────┐
    2. │ Business applications (office assistant / coding assistant / customer support / knowledge Q&A) │
    3. └───────────────────┬───────────────────────────┘
    4. │ Unified protocol (messages / tools / streaming)
    5. ┌───────────────────▼───────────────────────────┐
    6. │ Orchestration layer: prompt assembly · tool definitions · memory retrieval · loop control │
    7. └───────────────────┬───────────────────────────┘
    8. ┌───────────────────▼───────────────────────────┐
    9. │ Routing layer: rule routing · quality routing · cost routing · fallback chains │
    10. └───────────────────┬───────────────────────────┘
    11. ┌───────────────────▼───────────────────────────┐
    12. │ Adaptation layer: request/response normalization · tool-call transformation · error mapping │
    13. └───────────────────┬───────────────────────────┘
    14. ┌───────────────────▼───────────────────────────┐
    15. │ Governance layer: auth · key management · rate limiting/quota · content safety · logging/audit │
    16. └───────────────────┬───────────────────────────┘
    17. │
    18. ┌────────────────┼────────────────┬──────────────┐
    19. ▼ ▼ ▼ ▼
    20. In-house model Third-party model A Third-party model B Third-party model C

    The core value of this layering is dependency inversion: the orchestration layer depends only on the unified protocol, not on any specific model. Adding a model requires adding an adapter and registering its metadata; business code does not need to change. Expressed in interface terms:

    1. # adapters/base.py — internal unified model interface
    2. from typing import Protocol, AsyncIterator, Any
    3. class ModelAdapter(Protocol):
    4. """Unified interface implemented by all model adapters; business and orchestration layers depend only on it."""
    5. name: str # Model identifier, e.g. "vendorA-chat-pro"
    6. version: str # Pinned version; changes require regression review
    7. capabilities: frozenset # Set of capability flags
    8. async def chat(self, req: "ChatRequest") -> "ChatResponse":
    9. """Non-streaming invocation."""
    10. async def stream(self, req: "ChatRequest") -> AsyncIterator["StreamEvent"]:
    11. """Streaming invocation with standardized incremental events."""

    III. Unified Interface Abstraction: Capability Negotiation Above the Lowest Common Denominator

    One of the most underestimated challenges in multi-model integration is that requests and responses that look the same are often inconsistent in detail.

    3.1 Key Differences

    • Roles and prompts: The naming of system prompts (system / developer, etc.), whether multiple system messages are allowed, and the order in which they are concatenated with other messages.
    • Tool calls: How tool definitions are referenced, whether parameters require strict JSON Schema, the structure of multi-turn tool calls, parallel calls, and return formats.
    • Context and output limits: Differences in context window length, single-output limits, and tokenization methods affect truncation strategies and budget calculations.
    • Multimodal input: Images may be passed via URL or data encoding, placed inside message content blocks or in separate fields.
    • Streaming semantics: Whether the first packet carries role information, end markers, how reasoning content is returned, and whether there are reserved fields (fields that may be enabled later and must be passed through unchanged for now).
    • Error semantics: Local errors such as request limits, authentication failures, and content-moderation blocks, and remote errors such as quota exhaustion and service overload, need unified error classification.
    • Usage statistics: Token counting conventions, and whether details such as cache hits are returned.

    3.2 Minimal Common Subset and Capability Negotiation

    A unified protocol should first cover the minimal common subset, then express differences through capability declarations. Simplified request and response definitions are as follows:

    1. # adapters/schema.py — unified request / response structures (simplified illustration)
    2. from dataclasses import dataclass, field
    3. from typing import Any
    4. @dataclass
    5. class ToolSpec:
    6. name: str
    7. description: str
    8. parameters: dict # JSON Schema
    9. @dataclass
    10. class Message:
    11. role: str # system / user / assistant / tool
    12. content: Any # str or list of content blocks (text / image, etc.)
    13. tool_call_id: str | None = None # required when role=tool
    14. tool_calls: list[dict] | None = None # assistant-initiated tool calls
    15. @dataclass
    16. class ChatRequest:
    17. model: str # filled by routing layer; nullable
    18. messages: list[Message]
    19. tools: list[ToolSpec] = field(default_factory=list)
    20. tool_choice: str = "auto" # auto / required / none
    21. temperature: float | None = None
    22. max_tokens: int = 4096
    23. stream: bool = False
    24. @dataclass
    25. class ChatResponse:
    26. model: str
    27. finish_reason: str # stop / tool_calls / length / content_filter / error
    28. content: str | None = None
    29. tool_calls: list[dict] = field(default_factory=list)
    30. usage: dict = field(default_factory=dict)
    31. raw: Any = None # Raw response retained for debugging and auditing
    32. class CapabilityError(Exception):
    33. """The selected model does not support one of the capabilities in the request."""

    The core capabilities required by a request can be declared task by task: dialogue, tool calls, structured output, long context, visual understanding, and so on. During routing, candidates are first filtered by capability, then policies are applied. Example:

    1. # router.py — capability-based candidate filtering
    2. CAPABILITY = frozenset({"chat", "tools", "json_mode", "long_context", "vision"})
    3. def filter_candidates(req: ChatRequest, catalog: dict) -> list:
    4. """Filter available models by required request capabilities, preserving registration order for stable ranking."""
    5. needed = {"chat"}
    6. if req.tools:
    7. needed.add("tools")
    8. if req.tool_choice == "required":
    9. needed.add("json_mode")
    10. return [m for m in catalog.values()
    11. if needed <= m.capabilities and not m.is_disabled()]

    For capabilities that a provider does not yet support, there are two handling approaches:

    • Explicit degradation: The routing layer switches to a supported model and returns a degradation explanation to the caller.
    • Adapter-level emulation: If conditions allow, prompt constraints can be used to implement equivalent behavior such as “must call a tool” or “output JSON only.” However, this kind of emulation does not provide engine-level constraint guarantees and is less reliable. It is generally used only as a fallback.

    Whether to degrade should be an explicit decision made by the business side; it should not be silently swallowed.

    IV. Routing Decisions: Making Model Selection Explainable and Replayable

    The essence of routing is multi-objective trade-off among quality, latency, cost, and data boundaries. Common strategies can be combined:

    1. Rule routing: Select models by task type (summarization, classification, code review, complex reasoning) or input size (use a long-context model above a threshold). It is simple to implement and deterministic, making it suitable as the first strategy.
    2. Quality routing: Dynamically adjust weights based on offline evaluation scores and online feedback (human annotation, user retry rate, task completion rate). Mechanisms such as multi-armed bandits can balance exploration and exploitation.
    3. Cost routing: Set budgets and confidence thresholds for each task. A lightweight model answers first; if confidence is insufficient or the result fails validation, escalate to a stronger model. This is the cascade idea.
    4. Constraint routing: Filter candidates according to tenant allowlists, region and data-residency requirements, and compliance policies. Constraints take priority over other preferences.
    5. Availability routing: Combine health probes and error rates to remove weight from abnormal instances.

    Routing decisions must be traceable. Decision results should be retained together with model invocation logs to support review and replay.

    1. # router.py — routing decisions and fallback chains (illustrative)
    2. import random
    3. from dataclasses import dataclass
    4. @dataclass
    5. class RouteDecision:
    6. primary: str # primary model identifier
    7. chain: list # full fallback chain
    8. reason: str # routing reason for auditing
    9. def decide(task: dict, ctx: dict, catalog: dict) -> RouteDecision:
    10. """Apply, in order: hard constraints -> rules -> availability -> preferences -> budget."""
    11. # 1. Hard constraints: tenant allowlist + capability requirements + data residency
    12. candidates = filter_candidates(task["req"], catalog)
    13. allowed = ctx["tenant"].allowed_models
    14. region = ctx["tenant"].data_region
    15. candidates = [m for m in candidates
    16. if m.name in allowed and m.region == region]
    17. if not candidates:
    18. raise CapabilityError(f"No model satisfies the constraints for tenant {ctx['tenant'].id}")
    19. # 2. Rules: define preferred order by task type
    20. by_type = task.get("preferred", [])
    21. primary = next((name for name in by_type if name in {m.name for m in candidates}),
    22. candidates[0].name)
    23. # 3. Availability: healthy models first, failed models at the end of the chain
    24. healthy = [m for m in candidates if m.is_healthy()]
    25. unhealthy = [m for m in candidates if not m.is_healthy()]
    26. ordered = healthy + unhealthy
    27. # 4. Preferences: choose by weight under equal conditions (soft affinity)
    28. primary = weighted_pick(ordered, key=lambda m: m.affinity_weight())
    29. # 5. Budget: switch to a lower-cost tier when remaining session budget is insufficient
    30. if ctx["session"].remaining_budget <= 0:
    31. primary = ctx["tenant"].low_cost_model or primary
    32. chain = [primary] + [m.name for m in ordered if m.name != primary]
    33. return RouteDecision(primary=primary, chain=chain, reason=task.get("reason", "default"))

    Availability feedback is also needed: when error rates or latency percentiles exceed thresholds, the corresponding model is marked unhealthy; after recovery, traffic is gradually restored using exponential backoff.

    V. Stability Governance: Circuit Breaking, Retrying, Degradation, and Timeout Budgets

    After introducing multiple models, availability no longer depends only on “whether a single model is reliable,” but on “whether the entire invocation chain can degrade gracefully.” This requires treating models as standard external dependencies:

    • Timeout budget breakdown: Starting from the total user-side budget, allocate time in sequence for gateway processing, the first model invocation, tool execution, and fallback handling. For example, with a total budget of 8 seconds: 0.5 seconds for gateway processing, 4 seconds for the primary model, 2.5 seconds for the fallback model, and 1 second for tool execution. This prevents “layered retries stacking up and causing total latency to exceed user expectations.”
    • Bounded retries: Retry only idempotent requests (completion requests without side effects), limit retry counts, and use exponential backoff with jitter. In multi-turn loops that involve tool side effects, retries must return to a safe point to avoid repeated tool execution.
    • Circuit breaking and isolation: Track error rates by model or provider. Once triggered, fail fast and switch to the fallback chain, preventing failures from accumulating into an avalanche within the gateway.
    • Graceful degradation: Define degradation order according to business importance. For example: flagship model → mainstream model → lightweight model → cached result or preset copy. When degradation occurs, inform users honestly rather than pretending the result is normal.
    • Structured-output fallback: When JSON-mode or tool-call result parsing fails, trigger a repair retry that includes the error explanation. If it still fails, switch models or fall back to rule-based parsing.
    • Streaming response management: Include connection interruption, missing heartbeats, and first-packet timeouts in monitoring. The frontend should be able to seamlessly continue when switching models midstream.

    The execution path is as follows:

    1. # gateway.py — execution path with circuit breaking, validation, and degradation (illustrative)
    2. import asyncio
    3. import time
    4. class UpstreamUnavailable(Exception):
    5. """Model is unavailable or the call failed; continue to the next fallback option."""
    6. async def generate(req: ChatRequest, session: dict) -> ChatResponse:
    7. decision = route(session["task"], session["ctx"], session["catalog"])
    8. budget = session["deadline"] - time.monotonic() # remaining time budget
    9. last_error = None
    10. for depth, model_name in enumerate(decision.chain):
    11. if budget <= 0:
    12. break
    13. adapter = session["catalog"][model_name]
    14. timeout = min(session["ctx"].timeouts.get(model_name, 4.0), budget)
    15. try:
    16. async with adapter.breaker: # Circuit breaker: fail fast when open
    17. resp = await asyncio.wait_for(adapter.chat(req), timeout=timeout)
    18. if resp.finish_reason == "length":
    19. raise UpstreamUnavailable(f"{model_name} output was truncated")
    20. if req.tools and validate_tool_calls(resp, req): # tool-call structure validation
    21. raise UpstreamUnavailable(f"{model_name} tool calls are invalid")
    22. session["log"].record(model_name, resp.usage, depth) # cost and degradation audit
    23. return resp
    24. except (asyncio.TimeoutError, UpstreamUnavailable) as err:
    25. last_error = err
    26. budget = session["deadline"] - time.monotonic()
    27. continue # Try the next model in the fallback chain
    28. return fallback(session) # cached result / preset reply / explicit failure message

    It must be emphasized that the stability benefits of multi-model systems hold only when the fallback chain is truly available. If all alternatives share the same network egress or the same key pool, a single failure domain still exists, and the so-called redundancy is only theoretical.

    VI. Cost and Capacity: From Per-Call Accounting to Per-Task Accounting

    In a multi-model system, the focus of cost governance shifts from “which model was chosen” to “how much each task actually cost and whether it was worth it”:

    • Unified metering: Record the model, input/output tokens, cache-hit volume, retry count, and whether degradation occurred for every invocation. Tag records with tenant, scenario, and session labels to support attribution by business line.
    • Budget controls: Set token budgets and invocation limits for tenants, scenarios, or sessions. When thresholds are approached, automatically switch to a lower-cost model or degrade to non-streaming or non-multimodal modes.
    • Capacity planning: Providers differ in concurrency quotas, QPS, and context lengths. Capacity evaluation should be based on load testing using peak invocation volume, average token length, and output-length distribution, rather than rough estimates.

    Common cloud capabilities that support model invocation can be divided as follows: a relational database stores model registry information and tenant configurations; a cache stores prompt prefixes and hot Q&A results; a message queue smooths traffic peaks and handles asynchronous tasks; object storage saves multimodal assets; logging services aggregate invocation details; and monitoring and alerting systems track latency, error rates, and costs. This combination is not exclusive to any one cloud provider and can be implemented with any technology stack.

    VII. Security and Compliance: A New Risk Surface from Multiple Vendors

    As the number of models increases, the security boundary also expands. The following risks deserve particular attention:

    • Data-flow control: Perform field-level masking before forwarding each request. Combine tenant-configured data-residency requirements to restrict the range of available models, ensuring sensitive data is not sent to unauthorized providers.
    • Prompt injection and tool safety: When third-party models process untrusted input such as external documents, web pages, or attachments, isolate system prompts from user content and apply allowlist validation to tool calls. Otherwise, the model may be induced to perform unauthorized operations.
    • Key and credential management: Store each provider’s keys separately in a key management service, grant least-privilege access, and rotate them regularly. Prohibit keys and full prompts from appearing in logs.
    • Content safety: Perform sensitive-content detection on the input side and compliance review on the output side. Only after passing review should output be returned to users or passed to downstream tools.
    • Version and behavior drift: Model version updates may change output style and tool-calling behavior. Version numbers should be pinned and recorded. Regression evaluation must be run before upgrades, and canary rollout and rollback should be supported.
    • Auditability: Call-chain logs should retain the model, version, request summary, latency, token usage, and degradation reasons to meet internal and external audit requirements.

    VIII. Evaluation System: Using Data to Decide Which Model to Use

    Without evaluation, routing strategies can rely only on intuition. A three-layer evaluation capability is recommended:

    • Offline evaluation sets: Construct cases by sampling from real business traffic, covering typical scenarios and long-tail boundaries. Also include adversarial samples such as prompt injection, unauthorized tool calls, and format inducement.
    • Core metrics: Task success rate, tool-call accuracy, JSON validity, average rounds to completion, P95 first-token latency, and average cost per task.
    • Online evaluation: Validate strategy effects through small-traffic canary releases, A/B testing, and manual spot checks. Continuously collect bad cases from production and feed them back into the evaluation set.
    1. # eval.py — offline evaluation illustration
    2. import json
    3. def evaluate(case: dict, resp: ChatResponse) -> dict:
    4. """Return a structured score for one case; aggregated scores can adjust routing weights."""
    5. score = {"case_id": case["id"], "model": resp.model, "passed": True, "issues": []}
    6. if resp.finish_reason == "length":
    7. score["passed"] = False
    8. score["issues"].append("truncated")
    9. if case["expect_schema"] is not None:
    10. try:
    11. parsed = json.loads(resp.content or "")
    12. if not case["expect_schema"](parsed):
    13. score["passed"] = False
    14. score["issues"].append("schema_mismatch")
    15. except json.JSONDecodeError:
    16. score["passed"] = False
    17. score["issues"].append("invalid_json")
    18. return score

    Evaluation results can drive the system in two directions: on one hand, they provide weight inputs for quality routing; on the other hand, they accumulate into model capability profiles, clarifying which types of tasks should be handled by which types of models.

    IX. Common Pitfalls

    1. Treating multi-model integration as “connecting more APIs”: Without a unified protocol and adaptation layer, business code becomes tightly coupled to each model, making later replacement extremely costly.
    2. Silent degradation: If degradation is not recorded or communicated, problems are difficult to locate, and users may also lose trust in output quality.
    3. Treating retries as a cure-all: Indiscriminate retries inside agent loops with side effects may cause tools to be executed multiple times, resulting in data-level errors.
    4. Ignoring version pinning: Model versions may change silently with provider upgrades, making production behavior drift difficult to reproduce.
    5. Selecting models only by subjective feel: Without evaluation and cost accounting, teams may pay a premium for more expensive models while gaining little clear benefit.
    6. Ignoring token-counting differences: Different models count context and output differently. Direct horizontal comparison can lead to incorrect capacity and cost conclusions.

    X. Rollout Path and Summary

    The rollout can proceed in four stages:

    • Stage 1: Abstraction: Define the unified protocol and adapter interface. First integrate the in-house model and one third-party model, and get the end-to-end path and logging in place.
    • Stage 2: Governance: Add circuit breaking, fallback chains, timeout budgets, and quota controls. Build a minimal usable evaluation set.
    • Stage 3: Intelligence: Launch routing based on rules and quality, route traffic by scenario, and validate benefits with A/B testing.
    • Stage 4: Optimization: Introduce cascade invocation and caching. Bring cost and latency into routine monitoring and form a closed loop of “evaluation → weight adjustment → canary release → review.”

    Updates such as adding multiple third-party models beyond an in-house model are not just about the model list. What developers should really care about is the infrastructure that supports multi-model coexistence. With a unified protocol as the foundation, routing and degradation as the backbone, and evaluation and observability as the feedback loop, models can truly become capability resources that are replaceable, measurable, and governable. This way, whether models iterate, vendors change, or business scenarios expand, the agent platform can remain stable and controllable.