Multi-Model Integration and Cost Governance: Practices for AI Agent Office Products

    This article explores the practices of integrating multiple large language models into AI agent office products, covering challenges in capability, cost, and compliance. It details the architecture design using a unified abstraction layer, quota calculation mechanisms, task routing strategies, reliability design, and evaluation methodologies to help developers balance performance, cost, and stability in enterprise AI applications.

    1. Background: From Single-Model to Multi-Model Collaboration

    Recent industry trends indicate that an AI agent product designed for office scenarios has integrated multiple third-party large language models alongside its proprietary model after a version update. Users can select the model based on task requirements, while the platform annotates the quota consumption multiplier for each invocation based on the usage cost of different models.

    This shift reflects a common trend in enterprise AI applications. A single model struggles to simultaneously balance reasoning depth, response speed, per-call cost, and language coverage. Therefore, a multi-model architecture is becoming a standard choice. For developers, the challenge is not invoking multiple APIs, but enabling the system to strike a balance between capability, cost, stability, and compliance.

    2. Four Key Challenges in Multi-Model Integration

    2.1 Capability Differences

    Different models perform differently in code generation, long-text comprehension, multilingual processing, and tool invocation. The output format and level of structuring for the same task may vary across models. The system must maintain a capability profile for each model rather than treating all models as interchangeable black boxes.

    2.2 Cost Differences

    Model pricing can vary significantly. If all requests default to the most capable model, costs can spiral out of control. A multiplier mechanism is a common approach: using a baseline model as 1x, other models are calculated based on their relative cost. This allows users to intuitively see the consumption of each operation, and enables the platform to unify metering and billing.

    2.3 Availability and Degradation

    External model services may experience timeouts, rate limiting, or brief outages. A multi-model structure provides inherent redundancy, provided the system can automatically switch models while ensuring the post-switch output still meets business requirements.

    2.4 Data and Compliance

    Request content may contain personal information, internal documents, or trade secrets. Different models may vary in their data processing terms, storage locations, and logging policies. These must be verified item by item before integration, and desensitization and auditing should be uniformly handled at the gateway layer.

    3. Architecture Design: Unified Abstraction Layer

    The core idea is to add an abstraction layer between the business code and specific models. The business code interacts only with a unified interface, and adapters are responsible for converting unified requests into the invocation formats of respective models.

    1. from dataclasses import dataclass
    2. from typing import Protocol
    3. @dataclass(frozen=True)
    4. class ChatRequest:
    5. messages: list[dict]
    6. max_output_tokens: int = 1024
    7. temperature: float = 0.2
    8. @dataclass(frozen=True)
    9. class ChatResponse:
    10. text: str
    11. model_id: str
    12. input_tokens: int
    13. output_tokens: int
    14. class ModelAdapter(Protocol):
    15. model_id: str
    16. def complete(self, request: ChatRequest) -> ChatResponse: ...

    The registry manages all available adapters:

    1. class ModelRegistry:
    2. def __init__(self) -> None:
    3. self._adapters: dict[str, ModelAdapter] = {}
    4. def register(self, adapter: ModelAdapter) -> None:
    5. if adapter.model_id in self._adapters:
    6. raise ValueError(f"duplicate model id: {adapter.model_id}")
    7. self._adapters[adapter.model_id] = adapter
    8. def get(self, model_id: str) -> ModelAdapter:
    9. try:
    10. return self._adapters[model_id]
    11. except KeyError:
    12. raise LookupError(f"model not registered: {model_id}") from None

    Two points to note during design. First, model metadata (multipliers, context length, capability tags) should be placed in configuration files, separated from the code, making it easy to adjust without code changes. Second, API keys should be read via environment variables or key management services, and must never be hardcoded in code or logs.

    4. Quota Metering: Applying Multipliers to Every Call

    Quota consumption can be expressed by the following formula:

    Consumption = (input tokens + output tokens) / 1000 × base rate × model multiplier

    1. BASE_RATE_PER_1K = 1.0 # Base rate, in quota points
    2. MODEL_MULTIPLIERS = {
    3. "economy-small": 0.5,
    4. "standard-medium": 1.0,
    5. "premium-large": 3.0,
    6. }
    7. def estimate_quota(model_id: str, input_tokens: int, output_tokens: int) -> float:
    8. multiplier = MODEL_MULTIPLIERS[model_id]
    9. total_tokens = input_tokens + output_tokens
    10. return total_tokens / 1000 * BASE_RATE_PER_1K * multiplier

    The values above are for illustrating the calculation logic; actual multipliers depend on business configurations. The metering process can be divided into two steps: reserve quota based on an estimated value before invocation to prevent overuse; after the call, settle based on the actual token count and release any excess reserved quota. For failed requests, it should be clear whether they are billed, and traceable records should be retained in the billing logs.

    5. Task Routing: Assigning the Right Model to the Right Task

    Routing strategies typically consider task type, complexity, and remaining budget. The following example demonstrates a simple rule-based routing:

    1. def choose_model(task_type: str, budget_left: float) -> str:
    2. if task_type in {"code_review", "long_analysis"}:
    3. return "premium-large"
    4. if budget_left < 5:
    5. return "economy-small"
    6. return "standard-medium"

    Rule-based routing is straightforward, but production environments require fallback chains. When degrading, the actual model used must be logged so that the caller can determine the reliability of the result:

    1. FALLBACK_CHAIN = ["standard-medium", "economy-small"]
    2. def call_with_fallback(registry: ModelRegistry, request: ChatRequest, preferred: str) -> ChatResponse:
    3. for model_id in [preferred, *FALLBACK_CHAIN]:
    4. try:
    5. return registry.get(model_id).complete(request)
    6. except TimeoutError:
    7. continue
    8. raise RuntimeError("all candidate models are unavailable")

    For compliance-sensitive tasks or those requiring high accuracy, silent degradation to a less capable model should be avoided. Such tasks are better off returning a failure directly or being routed to a manual processing queue.

    6. Reliability Design

    • Timeout control: Set independent timeout thresholds for each model. Long-text tasks and short Q&A tasks should not use the same parameters.
    • Retry strategy: Only retry idempotent requests, and use exponential backoff with random jitter to prevent avalanche effects caused by mass simultaneous retries.
    • Circuit breaking: If a model fails continuously within a time window beyond a threshold, temporarily remove it from the candidate list, and attempt recovery after the window ends.
    • Health checks: Periodically invoke each model with a fixed test set to verify both response status and output quality.
    • Observability: Log the model identifier, latency, token count, status code, and degradation flag for each invocation. User content in logs must be desensitized.

    7. Evaluation: Do Not Just Compare Unit Prices

    Model selection should be based on statistical results. It is recommended to build an evaluation set covering real business scenarios, run it on candidate models, and record data across the following dimensions:

    • Task accuracy: whether the output content meets factual and business requirements.
    • Format compliance rate: whether the output can be stably parsed by downstream programs.
    • End-to-end latency: including queuing and network overhead.
    • Cost per unit output: the quota consumed per accepted result.

    The last metric best reflects the true cost. A model with a low unit price that requires repeated retries may actually cost more than a higher-priced model that passes on the first try.

    8. Compliance and Filing Essentials

    • When providing generative AI services to the public, regulatory filing or security assessments should be completed according to local regulatory requirements.
    • Filing materials typically involve model usage descriptions, training data sources, and other relevant compliance documentation as required by local authorities.