Multi-Model Integration in Practice: Unified Adapters, Metering, and Failover
Office AI agents often need multiple models for document drafting, spreadsheet analysis, conversation summarization, and coding assistance. This article presents a four-layer architecture—access, metering, scheduling, and governance—for multi-model integration. It covers unified adapter interfaces, model registry metadata, error classification and failover, audit logging, quota freezing and settlement, and billing reconciliation with concrete code and formulas.
I. Problem and Layering
Office AI agents usually handle document drafting, spreadsheet analysis, conversation summarization, and coding assistance at the same time. Different tasks have different model requirements: long-document understanding depends on context length, simple rewriting depends on response speed, complex reasoning depends on logical capability, and batch processing is more sensitive to per-call cost. A single model can hardly excel in all dimensions, so platforms generally integrate multiple models.
When integrating a second model, teams often encounter four problems:
- How can multiple models be integrated without writing a separate set of business code for each model?
- How should models be selected to balance quality and cost?
- How should quota be deducted fairly and reconciled?
- How should failover work when a model fails without double charging?
Breaking these problems into four layers makes the design clearer:
- Access layer: abstracts differences in request parameters, authentication methods, and streaming output across models.
- Metering layer: converts usage from different models into unified quota units.
- Scheduling layer: selects a model for each request and decides how to fail over after a failure.
- Governance layer: provides model registration, safety review, and log retention for admission and audit.
Each layer has only its own responsibility. The access layer outputs a standard structure, the metering layer uses only unified units, the scheduling layer only decides which model a request is sent to, and the governance layer decides whether a model can go live. When adding or replacing a model, usually only the access layer and registration information need to change, while business code remains unchanged.
1.1 Task and Model Selection Principles
Before the scheduling layer selects a model, it first determines the primary requirement based on the task. The table below is a common prioritization approach. Specific model categories and thresholds should be based on your own test results.
| Task Type | Primary Requirement | Selection Principle | Fallback Strategy |
|---|---|---|---|
| Long-document understanding | Context length, information completeness | Context limit must exceed input plus expected output | Split long documents first, then send them to a long-context model |
| Text rewriting and polishing | Response speed, per-call cost | Prefer low latency and low multiplier | Among capable models, choose the one with the lowest multiplier |
| Complex reasoning and data analysis | Logical capability, result accuracy | Quality first, multiplier secondary | If result quality is insufficient, route to human review |
| Batch summarization | Per-call cost, throughput | Low multiplier, slightly longer latency acceptable | Schedule during off-peak hours |
II. Unified Adapters and Model Registry
2.1 Adapter Interface
The unified adaptation layer exposes one standard interface externally and implements one adapter per model internally. An adapter is responsible for three things: converting standard requests into the format required by the model, converting responses back into the standard structure, and mapping upstream exceptions to internal error codes. Business code calls only the standard interface and does not directly call any model’s raw SDK or HTTP API.
from abc import ABC, abstractmethodfrom dataclasses import dataclass@dataclassclass Usage:input_tokens: intoutput_tokens: int@dataclassclass ModelResponse:text: strusage: Usageclass AdapterError(Exception):def __init__(self, code: str, retryable: bool):super().__init__(code)self.code = codeself.retryable = retryableclass ModelAdapter(ABC):@abstractmethoddef send(self, req, timeout: float) -> ModelResponse:"""Return the result once. Raise AdapterError on failure."""@abstractmethoddef stream(self, req, timeout: float):"""Yield text chunks and return Usage at the end."""@abstractmethoddef classify_error(self, raw_error: Exception) -> AdapterError:"""Map upstream exceptions to internal error codes."""
2.2 Error Classification and Mapping
Errors fall into two categories. Temporary failures can switch to a fallback model. Problems with the request itself cannot be solved by switching and should be returned directly to the caller. The table below is a mapping example. Specific upstream status codes should follow each provider’s documentation.
| Upstream Behavior | Internal Error Code | Category | Switchable? | Handling |
|---|---|---|---|---|
| Request timeout | MODEL_TIMEOUT | Temporary | Yes | Release frozen quota and switch to a candidate model |
| Rate limit (e.g., 429) | MODEL_RATE_LIMITED | Temporary | Yes | Back off and switch; do not retry repeatedly on the same model |
| Server error (e.g., 5xx) | MODEL_UNAVAILABLE | Temporary | Yes | Switch to a candidate model and count it toward the model error rate |
| Parameter error (e.g., 400) | INVALID_REQUEST | Request | No | Return directly; do not switch |
| Authentication failure (e.g., 401, 403) | AUTH_FAILED | Configuration | No | Return directly and alert; usually a key or configuration issue |
| Content safety block | CONTENT_BLOCKED | Request | No | Return the block message; do not bypass review by switching models |
| Input exceeds context limit | CONTEXT_TOO_LONG | Request | No | Return directly; the caller decides whether to split or change models |
2.3 Model Registry
The registry records metadata for each model. The scheduler reads the registry to make decisions, and operators manage online/offline status through the registry without modifying code. Status and review results use fixed enums and are validated before writing, preventing dirty data from entering scheduling.
from dataclasses import dataclassfrom enum import Enumclass Status(str, Enum):AVAILABLE = "available"DEGRADED = "degraded"OFFLINE = "offline"class SafetyReview(str, Enum):PENDING = "pending"PASSED = "passed"REJECTED = "rejected"@dataclass(frozen=True)class ModelRecord:name: str # Model identifierversion: str # Integration versionowner: str # Ownercapabilities: frozenset # Capability tags, such as summary, writing, reasoningcontext_limit: int # Maximum context lengthmultiplier: float # Metering multiplierstatus: Statusfiling_no: str # Compliance filing IDsafety_review: SafetyReviewlog_retention_days: int # Log retention daysdef __post_init__(self):if self.multiplier <= 0:raise ValueError("multiplier must be greater than 0")if self.status is Status.AVAILABLE and (self.safety_review is not SafetyReview.PASSED or not self.filing_no):raise ValueError("Available status requires a filing ID and a passed safety review")
2.4 Audit Log
Audit logs must be persisted and append-only. An in-memory list is lost after a process restart and cannot truly prevent rewriting, so it cannot be used to meet audit requirements. Below is a PostgreSQL schema example.
CREATE TABLE model_audit_log (event_id UUID PRIMARY KEY,model_name VARCHAR(64) NOT NULL,from_status VARCHAR(16) NOT NULL,to_status VARCHAR(16) NOT NULL,operator VARCHAR(64) NOT NULL,reason TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now());CREATE INDEX idx_audit_model_time ON model_audit_log (model_name, created_at);-- The application role has insert and query permissions onlyREVOKE UPDATE, DELETE ON model_audit_log FROM app_role;
When status changes, the audit record and status update must be completed in the same transaction:
def change_status(db, model_name, new_status, operator, reason):if not operator or not reason:raise ValueError("operator and reason cannot be empty")with db.transaction():record = db.get_model(model_name, for_update=True)if record.status == new_status:returndb.insert_audit(model_name, record.status, new_status, operator, reason)db.update_status(model_name, new_status)
III. Quota Metering, Deduction, and Reconciliation
The cost differences between models are significant. If all models deduct at the same standard, high-cost models will cause platform losses, while users of low-cost models will feel treated unfairly.
3.1 Deduction Formula
The variables in the formula are defined as follows:
input_tokens,output_tokens: the number of input and output tokens for this call.W_IN,W_OUT: unit weights configured by the platform. Output tokens cost more; the example usesW_IN = 1.0andW_OUT = 3.0.multiplier: the metering multiplier in the model registry.
The calculation steps are:
usage_weight = input_tokens × W_IN + output_tokens × W_OUTraw_cost = usage_weight × multiplierdeducted = max(1, ceil(raw_cost))
The rounding rule is to round up to an integer number of quota points, with a minimum charge of 1 point.
Example: 1000 input tokens, 500 output tokens, multiplier 1.5.
- usage_weight = 1000 × 1.0 + 500 × 3.0 = 2500
- raw_cost = 2500 × 1.5 = 3750
- deducted = 3750
3.2 Pre-Freeze and Settlement
Before a call, freeze quota based on the estimated maximum usage. After the call, settle based on actual usage and release the excess. In the estimation formula, max_output is the maximum output length set in the request.
frozen = max(1, ceil((estimated_input × W_IN + max_output × W_OUT) × multiplier))
Example: model multiplier 1.5, estimated input 1000 tokens, maximum output 1000 tokens.
- Frozen quota: (1000 × 1.0 + 1000 × 3.0) × 1.5 = 6000
- Actual settlement is 3750, releasing 2250
If the call fails, the entire frozen quota is released and no charge is incurred.
Below is an example of a request that goes through two attempts. The first call to model-a times out, and the second attempt switches to model-b and succeeds.
- Attempt 1: model-a, multiplier 1.5, freeze 6000, timeout, release 6000.
- Attempt 2: model-b, multiplier 1.0, estimated input 1000 tokens, maximum output 1000 tokens, freeze 4000. Actual usage is 1000 input and 500 output, usage_weight is 2500, settlement charge is 2500, release 1500.
The request is ultimately charged only 2500 points.
3.3 Reconciliation Fields
Each attempt writes one billing record, and reconciliation is based on these records.
