Unified Access Architecture and Cost Governance for Multi-Model LLM Integration
This article explains how to connect several large language models through a single access layer, also called a model gateway. It covers an adapter pattern that isolates differences between providers, three strategies for routing requests to models by task, and a metering approach that converts usage from different models into shared quota units for cost control.
1. Background: Why Unified Model Management Is Needed
Enterprises that adopt large language model capabilities often connect to several model providers at the same time. There are three main reasons. First, different models have different strengths in tasks such as code generation, long-document understanding, and Chinese-language writing. Second, relying on a single provider carries availability risk, and multiple providers offer backup. Third, unit prices vary widely across models, so choosing the right model for each task can reduce costs substantially.
Running multiple models also creates new engineering problems. When business code binds directly to each provider’s API, the following issues usually appear:
- Each new model requires changes to the calling code, so the migration cost grows linearly with the number of models.
- Authentication, timeout, and retry logic is scattered across services, which makes troubleshooting difficult.
- Usage and fees are spread across different bills, so teams find it hard to tell which business unit consumes how much quota.
- After a model version update, prompts and output formats must be validated again, but there is no unified regression entry point.
This article therefore focuses on a central question: how to connect, schedule, and govern multiple models in a unified way without slowing down business iteration.
2. Overall Architecture: A Unified Access Layer
The recommended approach is to add a unified access layer between business services and models. This layer is often called a model gateway. It handles five responsibilities:
- Protocol adaptation: Expose a consistent calling interface to callers, and convert request and response formats for each provider internally.
- Routing decisions: Select the target model based on task type, cost budget, and current availability.
- Authentication and key isolation: Business services hold only internal tokens. Real provider keys are stored in a key management service.
- Quota and billing: Record the input and output size of each call and convert it into internal metering units according to defined rules.
- Observability: Output metrics such as latency, error rate, and cost to support capacity planning.
The architecture is shown below:
Business service ──> Unified access layer ──┬──> Provider adapter A├──> Provider adapter B└──> Provider adapter C│├── Routing policy├── Quota and billing├── Logs and metrics└── Key management
The key design of the access layer is the adapter pattern. Each provider implements the same abstract interface. When a new model is added, only one adapter needs to be written, and business code does not change.
An example of the interface abstraction is shown below:
from abc import ABC, abstractmethodfrom dataclasses import dataclass@dataclassclass ChatRequest:task_type: strmessages: list[dict]max_output_tokens: int = 1024timeout_seconds: float = 30.0@dataclassclass ChatResponse:text: strmodel_id: strinput_tokens: intoutput_tokens: intlatency_ms: floatclass ModelAdapter(ABC):"""Unified interface that all provider adapters must implement."""provider: str@abstractmethoddef chat(self, request: ChatRequest) -> ChatResponse:...
The business layer depends only on ChatRequest and ChatResponse. This limits the impact of provider interface changes to the adapter layer, which keeps the scope of any change under control.
3. Model Routing: Selecting Models by Task
Routing aims to balance quality, latency, and cost. There are three common strategies.
Static rule routing: Map each task type to a fixed model. For example, summarization tasks use a low-cost model, and code generation tasks use a more capable model. This approach is simple to implement and its behavior is predictable, so it works well as a starting point.
Budget- and priority-based routing: Select a tier based on the remaining project quota or task priority. When quota is tight, requests automatically fall back to a cheaper model.
Health-based failover: Continuously monitor each provider’s error rate and latency. When a provider exceeds a threshold, traffic switches automatically to a backup model.
An example of static rule routing is shown below:
ROUTING_TABLE = {"summary": ["tier_low_cost", "tier_standard"],"code_generate": ["tier_standard", "tier_high_capability"],"translate": ["tier_low_cost", "tier_standard"],}def pick_model(task_type: str, health: dict[str, bool]) -> str:candidates = ROUTING_TABLE.get(task_type, ["tier_standard"])for model_id in candidates:if health.get(model_id, True):return model_idraise RuntimeError(f"No available model for task type: {task_type}")
In the candidate list, the order defines priority. Placing backup models later in the list lets the business keep running when the primary model is unavailable.
Routing strategies should be used together with evaluation. Choosing a model by unit price alone may lower output quality. Build a fixed set of evaluation samples for each task type, compare output quality before switching models, and keep a one-click rollback switch.
4. Quota and Cost Governance
In a multi-model environment, cost governance is the part most often overlooked. The core idea of unified metering is to convert the raw usage of different models into internal quota units using one set of rules.
Common billing design elements include the following.
- Token-based metering: Count input and output tokens separately. Output tokens usually cost more, so they should be handled separately in metering.
- Multiplier coefficients: The same usage consumes different amounts of quota on different models. Multipliers reflect these cost differences.
- Time-of-day policies: Set lower multipliers during off-peak hours to encourage deferrable tasks to run at those times.
- Task-type rules: Apply different metering rules to batch offline tasks and real-time interactive tasks.
These rules should be managed through internal configuration rather than hard-coded in business logic. Below is an illustrative configuration for quota calculation. The values only show the structure. Teams should set actual values based on their own costs and budgets.
from datetime import datetime# Sample configuration. Set the values based on your actual costs and budget.RATE_CONFIG = {"tier_low_cost": {"base_rate": 0.01, "off_peak_rate": 0.005},"tier_standard": {"base_rate": 0.10, "off_peak_rate": 0.08},}OFF_PEAK_HOURS = set(range(0, 6)) # Example: 00:00 to 05:59 is off-peakOUTPUT_WEIGHT = 2 # Example: output tokens count at 2x weight
