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:

    1. Access layer: abstracts differences in request parameters, authentication methods, and streaming output across models.
    2. Metering layer: converts usage from different models into unified quota units.
    3. Scheduling layer: selects a model for each request and decides how to fail over after a failure.
    4. 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.

    1. from abc import ABC, abstractmethod
    2. from dataclasses import dataclass
    3. @dataclass
    4. class Usage:
    5. input_tokens: int
    6. output_tokens: int
    7. @dataclass
    8. class ModelResponse:
    9. text: str
    10. usage: Usage
    11. class AdapterError(Exception):
    12. def __init__(self, code: str, retryable: bool):
    13. super().__init__(code)
    14. self.code = code
    15. self.retryable = retryable
    16. class ModelAdapter(ABC):
    17. @abstractmethod
    18. def send(self, req, timeout: float) -> ModelResponse:
    19. """Return the result once. Raise AdapterError on failure."""
    20. @abstractmethod
    21. def stream(self, req, timeout: float):
    22. """Yield text chunks and return Usage at the end."""
    23. @abstractmethod
    24. def classify_error(self, raw_error: Exception) -> AdapterError:
    25. """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.

    1. from dataclasses import dataclass
    2. from enum import Enum
    3. class Status(str, Enum):
    4. AVAILABLE = "available"
    5. DEGRADED = "degraded"
    6. OFFLINE = "offline"
    7. class SafetyReview(str, Enum):
    8. PENDING = "pending"
    9. PASSED = "passed"
    10. REJECTED = "rejected"
    11. @dataclass(frozen=True)
    12. class ModelRecord:
    13. name: str # Model identifier
    14. version: str # Integration version
    15. owner: str # Owner
    16. capabilities: frozenset # Capability tags, such as summary, writing, reasoning
    17. context_limit: int # Maximum context length
    18. multiplier: float # Metering multiplier
    19. status: Status
    20. filing_no: str # Compliance filing ID
    21. safety_review: SafetyReview
    22. log_retention_days: int # Log retention days
    23. def __post_init__(self):
    24. if self.multiplier <= 0:
    25. raise ValueError("multiplier must be greater than 0")
    26. if self.status is Status.AVAILABLE and (
    27. self.safety_review is not SafetyReview.PASSED or not self.filing_no
    28. ):
    29. 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.

    1. CREATE TABLE model_audit_log (
    2. event_id UUID PRIMARY KEY,
    3. model_name VARCHAR(64) NOT NULL,
    4. from_status VARCHAR(16) NOT NULL,
    5. to_status VARCHAR(16) NOT NULL,
    6. operator VARCHAR(64) NOT NULL,
    7. reason TEXT NOT NULL,
    8. created_at TIMESTAMPTZ NOT NULL DEFAULT now()
    9. );
    10. CREATE INDEX idx_audit_model_time ON model_audit_log (model_name, created_at);
    11. -- The application role has insert and query permissions only
    12. REVOKE 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:

    1. def change_status(db, model_name, new_status, operator, reason):
    2. if not operator or not reason:
    3. raise ValueError("operator and reason cannot be empty")
    4. with db.transaction():
    5. record = db.get_model(model_name, for_update=True)
    6. if record.status == new_status:
    7. return
    8. db.insert_audit(model_name, record.status, new_status, operator, reason)
    9. 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 uses W_IN = 1.0 and W_OUT = 3.0.
    • multiplier: the metering multiplier in the model registry.

    The calculation steps are:

    1. usage_weight = input_tokens × W_IN + output_tokens × W_OUT
    2. raw_cost = usage_weight × multiplier
    3. deducted = 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.

    1. 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.