Technical Architecture and Cost Governance for Multi-Model Integration in AI Office Agents

    This article explores the technical architecture and cost governance strategies for integrating multiple large language models into AI office agents. It addresses challenges such as API inconsistencies, model capability variations, and cost tracking. A layered architecture design featuring a unified adapter layer and intelligent routing strategies is proposed to ensure service reliability, seamless model integration, and transparent cost management.

    I. Background: Multi-Model Coexistence as the Norm for Office Agents

    AI office agents handle a wide range of tasks, including document drafting, spreadsheet analysis, meeting notes summarization, coding assistance, and multi-turn Q&A. Different tasks have distinct requirements for reasoning depth, context length, response speed, and cost. A single model can rarely achieve optimal performance across all scenarios. Therefore, product teams generally adopt a multi-model approach: an in-house model serves as the default option, while several third-party models are offered for users to choose from as needed.

    For users, this design expands their choices. For the platform, however, it introduces three main challenges: how to uniformly integrate different models, how to help users understand the cost differences between models, and how to ensure service continuity when a specific model fails. The following sections address these challenges and outline a general engineering solution.

    II. Core Challenges of Multi-Model Integration

    2.1 Interface and Protocol Differences

    The request formats, streaming output methods, tool calling protocols, and error code definitions vary among model services. If business logic directly calls each provider’s API, the integration logic must be modified every time a new model is added, causing maintenance costs to grow linearly with the number of models. This is typically the first bottleneck exposed in a multi-model architecture.

    2.2 Capability Differences

    Models have different strengths in context window size, multimodal input support, function calling stability, and language comprehension. The output quality of the same prompt can vary significantly across different models. Therefore, models cannot be assumed to be seamlessly interchangeable. Routing strategies and evaluation processes must account for these capability differences.

    2.3 Cost Differences and Metering Standards

    Different models have varying unit consumption rates. A common approach is to set a quota consumption multiplier for each model: using a base model as the 1x benchmark, models with heavier reasoning loads or stronger capabilities will consume proportionally more quota. The metering standards must be transparently published in both the user interface and API documentation to prevent billing misunderstandings.

    2.4 Availability and Compliance

    Third-party services may experience rate limiting, timeouts, or temporary outages. Additionally, generative AI services available to the public must comply with regional regulatory requirements, including content safety moderation for both inputs and outputs. The more models integrated, the more compliance checkpoints need to be verified.

    III. Overall Architecture Design

    A layered architecture is recommended, where each layer has a single responsibility, making it easier to replace and test independently:

    1. User Request
    2. │
    3. ▼
    4. [Access Layer] Authentication, rate limiting, parameter validation
    5. │
    6. ▼
    7. [Routing Layer] Selects the model based on task type, user choice, cost, and health status
    8. │
    9. ▼
    10. [Adapter Layer] Converts unified requests into native protocols for each model
    11. │
    12. ▼
    13. [Execution Layer] Timeout control, retry, circuit breaking, fallback
    14. │
    15. ▼
    16. [Metering & Audit Layer] Logs usage, quota multipliers, and call records

    The key principle of layering is that the upper layers depend only on a unified internal data structure, while the protocol details of the lower layers are transparent to them. This way, when adding a new model, you only need to implement a new adapter; the routing, metering, and audit logic remains unchanged.

    IV. Implementing the Unified Adapter Layer

    The core of the adapter layer is defining a unified interface, encapsulating model-specific differences within their respective implementations. Below is a sample code snippet where class names and configurations are illustrative:

    1. from dataclasses import dataclass, field
    2. from typing import Protocol, AsyncIterator
    3. @dataclass
    4. class ChatRequest:
    5. messages: list[dict]
    6. max_tokens: int = 1024
    7. temperature: float = 0.7
    8. metadata: dict = field(default_factory=dict)
    9. @dataclass
    10. class ChatResponse:
    11. text: str
    12. input_tokens: int
    13. output_tokens: int
    14. model_id: str
    15. class ModelAdapter(Protocol):
    16. model_id: str
    17. quota_multiplier: float # Quota consumption multiplier, injected by config
    18. async def chat(self, req: ChatRequest) -> ChatResponse: ...
    19. async def stream(self, req: ChatRequest) -> AsyncIterator[str]: ...

    Each third-party model corresponds to an adapter implementation responsible for field mapping, error code translation, and streaming data parsing. The business layer only calls the unified interface and is unaware of the underlying protocols.

    A registry center manages all adapters and prevents duplicate registration:

    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

    API keys for the adapters should be read from environment variables or a key management service, and never hardcoded or logged. This is particularly important in multi-model scenarios, as the number of keys increases with each newly integrated model.

    V. Routing Strategies

    The routing layer determines which model will process each request. There are four common decision factors:

    1. Explicit User Choice: Prioritize the user’s selection while displaying the model’s quota multiplier in the UI, allowing users to weigh the costs themselves.
    2. Task Type: Simple tasks like rewriting or summarization can prioritize low-multiplier models; complex reasoning and long-document analysis can be directed to more capable models.
    3. Health Status: Models experiencing consecutive failures or significant latency spikes should temporarily have their priority reduced, with traffic gradually restored once they recover.
    4. Quota Balance: When quota is insufficient, the system should explicitly notify the user or fall back to a low-multiplier model instead of failing silently.

    The following sample function reflects these priorities:

    1. # Example configuration, model identifiers are placeholders
    2. TASK_PREFERENCE = {
    3. "summarize": ["economy", "base"],
    4. "reasoning": ["advanced", "base"],
    5. "long_document": ["long_context", "base"],
    6. }
    7. def choose_model(task_type: str,
    8. user_choice: str | None,
    9. healthy: set[str],
    10. quota_left: float,
    11. cost_table: dict[str, float]) -> str:
    12. # 1. Explicit user choice takes priority, provided the model is healthy and quota is sufficient
    13. if user_choice and user_choice in healthy \
    14. and cost_table.get(user_choice, float("inf")) <= quota_left:
    15. return user_choice
    16. # 2. Select the first available model based on task preference order
    17. for model_id in TASK_PREFERENCE.get(task_type, ["base"]):
    18. if model_id in healthy \
    19. and cost_table.get(model_id, float("inf")) <= quota_left:
    20. return model_id
    21. # 3. Explicitly raise an error if no model is available, letting the upper layer notify the user
    22. raise RuntimeError("No available model")