Multi-Model Integration for Office Agents: Adaptation, Routing, and Orchestration Practices

    Different office tasks require distinct AI capabilities, making multi-model integration essential. This article explores architectural practices for building office agents, covering unified interface adaptation, intelligent model routing, DAG-based task orchestration, result fusion strategies, and data security measures to optimize performance, cost, and stability.

    I. Why Office Agents Need Multi-Model Integration

    A single model rarely performs well across all office tasks. Some models excel at long-document understanding, while others offer greater stability in mathematical reasoning or code generation. Meeting minutes, data analysis, document drafting, schedule planning, and cross-system operations each demand different capabilities.

    Therefore, the goal of multi-model integration is to assign each type of task to the most suitable model. This requires architectural-level design of unified access standards, scheduling strategies, and fault tolerance mechanisms. Simply stacking multiple API interfaces cannot resolve issues related to cost, latency, and stability.

    During implementation, it is recommended to clarify three things first: the target task type, acceptable limits for latency and cost, and the data sensitivity level. These three factors determine the subsequent routing rules, fusion strategies, and security measures.

    II. Unifying Interfaces: Capability Decoupling and Adaptation Layer

    2.1 Define Unified Request and Response

    An office agent provides task capabilities externally, such as “generate a project weekly report” or “extract key contract terms.” The upper-layer business logic should not directly call a specific model’s interface. The system must first convert the user’s intent into a structured unified request, which is then transformed into the native format of each model by the adaptation layer.

    The unified request should contain the following fields:

    Field Type Description
    task_id string Unique task identifier for tracing
    task_type enum Task type, e.g., summarize, analyze, write, schedule
    input object Structured input, sensitive fields already desensitized
    context_tokens int Estimated context length
    require_tools bool Whether function calling is required
    max_latency_ms int Upper limit of response time
    budget_tier enum Cost tier: low, standard, or high

    The unified response should contain the following fields:

    Field Type Description
    status enum ok, partial, or error
    output object Standardized result
    model_id string Identifier of the actual executed model
    usage object Input and output token count
    latency_ms int End-to-end latency
    error_code string Filled in on error (see table below)

    An example of unified error codes is shown below. Specific codes can be adjusted according to team standards:

    Error Code Meaning Handling
    E1001 Invalid parameters Return directly, no retry
    E1002 Authentication failed Check key configuration, no retry
    E1003 Context limit exceeded Enter degradation process
    E1004 Model rate limited Switch to a candidate model once
    E1005 Upstream timeout Retry or degrade based on latency policy
    E1006 Security policy triggered Intercept and log to audit log

    2.2 Adapter Interface

    Each model corresponds to an adapter, and all adapters implement the same interface. When adding a new model, you only need to add a new adapter and register its configuration, without modifying the core business code.

    1. from abc import ABC, abstractmethod
    2. class ModelAdapter(ABC):
    3. name: str # Model identifier, e.g., "model-a-v2"
    4. @abstractmethod
    5. def max_context(self) -> int:
    6. """Returns the maximum context token count acceptable by this model."""
    7. @abstractmethod
    8. def supports_tools(self) -> bool:
    9. """Returns whether this model supports native function calling."""
    10. @abstractmethod
    11. def to_native(self, req: UnifiedRequest) -> dict:
    12. """Converts the unified request into the model's native request body, including parameter mapping."""
    13. @abstractmethod
    14. def from_native(self, raw: dict) -> UnifiedResponse:
    15. """Converts the model's native response into a unified response, including field standardization."""
    16. @abstractmethod
    17. def map_error(self, raw_error: Exception) -> str:
    18. """Maps upstream errors to unified error codes."""

    2.3 Handling Overlong Contexts and Missing Tool Calls

    When the context is too long, handle it in the following order:

    1. Truncate by paragraph priority, retaining task instructions and the most recent content. Note the truncated portion in the output.
    2. Split the long input into multiple segments for separate calls, then merge the results at the orchestration layer.
    3. If there is a long-context model among the candidates, route directly to it.

    If the model does not support native function calling, a two-stage approach can be used. The model first outputs a structured execution plan, the orchestration layer calls the tools, and then the tool results are passed back to the model to generate the final content.

    III. Smart Routing: Filter First, Then Score

    3.1 Candidate Filtering

    Routing occurs in two steps. The first step is hard filtering to eliminate models that do not meet the conditions, which include:

    • The context limit is not less than the context_tokens of the current request.
    • It supports the capabilities required by the task, such as native tool calling when function calls are needed.
    • The model’s cost tier does not exceed the budget_tier.
    • Health check status is available, and the recent error rate has not exceeded the threshold.

    3.2 Weighted Scoring

    The second step scores the remaining candidate models. Each metric is first normalized to a value between 0 and 1, with higher scores being better. Weights can serve as initial values and be adjusted later using live data.

    1. score = 0.40 × quality_score + 0.25 × latency_score + 0.20 × cost_score + 0.15 × load_score

    The quality score comes from the task type’s score in the offline evaluation set. Latency score, cost score, and load score are normalized from live monitoring data.

    Example: A document summarization task has two candidate models.

    Model Quality Score Latency Score Cost Score Load Score Total Score
    Model A 0.86 0.70 0.50 0.90 0.754
    Model B 0.80 0.90 0.30 0.60 0.695

    Model A has a higher total score, so routing selects Model A. If the task’s budget_tier is low, the cost score will have a greater impact, and the result may differ.

    3.3 Timeout, Retry, and Degradation

    • The timeout for the first call is set to 60% of max_latency_ms.
    • On rate limits or 5xx errors, switch to the next candidate model, with a maximum of one retry.
    • If all candidates fail, return the result from the default model configured in the rules; if the default model is also unavailable, return a partial status and explain the missing parts.

    IV. Using DAG for Task Orchestration

    4.1 Example: Market Competition Analysis Report

    “Generating a market competition analysis report” requires multiple steps, and some steps depend on external tools. The process is represented below using a Directed Acyclic Graph (DAG):

    1. N1 Goal Parsing (llm)
    2. ├── N2 Material Retrieval (tool: search)
    3. └── N3 Competitor Data Query (tool: database)
    4. ↓ (After N2 and N3 are complete)
    5. N4 Key Point Analysis (llm)
    6. ↓
    7. N5 Drafting (llm)
    8. ↓
    9. N6 Quality Check (rules + review model)
    10. ↓
    11. N7 Document Output (tool)

    N2 and N3 have no mutual dependencies and can be executed in parallel. N4 must wait for both N2 and N3 to complete before starting.

    4.2 Node Status Fields

    Each node records the following fields to facilitate troubleshooting and re-execution:

    Field Description
    node_id Node identifier
    type llm, tool, or check
    status One of pending, running, succeeded, failed, skipped
    attempts / max_attempts Number of attempts and limit
    input_ref / output_ref References to input and output in the context store
    error_code Error code on failure
    started_at / ended_at Start and end times

    4.3 Context Passing

    The output of each node is written to a shared context store, using the node_id as the key. Downstream nodes read the required content via references instead of copying the full context. This controls memory usage and makes it easier to trace the input and output of each step. The context store needs to set a size limit per node; content exceeding the limit should be summarized before being stored.

    4.4 Failure Rollback Rules

    • Tool node failure: Retry up to 2 times with exponential backoff. If it still fails, mark as failed and skip non-essential nodes that depend on it.
    • LLM node failure: Switch to a candidate model and retry once.
    • Quality check failure: Return to N5 to redraft, up to once. If it still fails, enter partial status.
    • In partial status, the system delivers the generated content and lists the missing parts and reasons, allowing the user to decide whether to supplement.

    V. Result Fusion: Only for High-Value Tasks

    Parallel multi-model calls simultaneously increase costs and make latency dependent on the slowest model. Therefore, fusion strategies are only used for high-value or high-error-cost tasks.

    5.1 Application Boundaries of Three Strategies

    Strategy Applicable Tasks Trigger Conditions Inapplicable Scenarios
    Voting Selection Classification, information extraction, boolean checks Parallel 3 models, at least 2 results consistent Open-ended writing, because there is no single correct answer
    Ranking Fusion Generation tasks like drafting, polishing Generate 2 to 3 candidates, scored by a review model, take the highest score Short text or low-value tasks
    Layered Verification Contract terms, financial figures, citation checks Main model generates, review model only checks facts, figures, and citations Creative content not involving fact-checking

    5.2 Concurrency and Budget Control

    • When budget_tier is low or standard, default to single-model calls.
    • When budget_tier is high, set concurrency to 2 or 3.
    • Set a daily model invocation budget for each tenant. Once the budget is exhausted, fusion strategies are automatically disabled and single-model execution is used instead.
    • The cost of parallel calls is approximately N times that of a single call, where N is the number of concurrent models. Latency depends on the slowest call.

    VI. Data Security: Desensitization, Auditing, and Permissions

    Office data often contains trade secrets, personal information, and financial data. After multi-model integration, data may flow to multiple model services, so every step needs control.

    6.1 Data Processing Checklist

    • Desensitization: Before entering the adaptation layer, replace phone numbers, ID numbers, bank card numbers, etc., with placeholders. The mapping between placeholders and original values is stored locally and not sent with the request.
    • Data Classification: Label each input as public, internal, confidential, or restricted, and select available models based on the classification during routing.
    • Private Deployment Priority: Restricted data is only allowed to call models deployed privately or in dedicated resource pools.
    • Transmission Encryption: All external calls use TLS encryption.
    • Model-side Logging: Disable the retention of request content to the extent supported by the service provider, and confirm that the data is not used for model training. This depends on the service provider’s contract and console configuration.

    6.2 Permission Matrix Example

    Role Public Data Internal Data Confidential Data Restricted Data Callable Cloud Models
    General Employee Allowed Allowed Forbidden Forbidden Public, internal data
    Department Head Allowed Allowed Allowed for own department Forbidden Public, internal, confidential data
    Finance Staff Allowed Allowed Allowed Forbidden Public, internal data
    Security Admin Allowed Allowed Allowed For auditing Does not call directly, only views audit logs

    The matrix should be jointly confirmed by the business side and the security team, and incorporated into the permission system configuration, rather than hardcoded.

    6.3 Prompt Injection and Instruction Injection Protection

    Models may receive maliciously crafted inputs, such as text embedded in documents saying “ignore the above instructions.” Protective measures include:

    • Input Validation: Limit length and filter abnormal characters and known attack patterns.
    • Isolate Instructions and Data: System instructions and user data are passed separately, and the prompt explicitly informs the model that the data portion does not constitute instructions.
    • Output Filtering: Perform compliance checks on generated content to intercept sensitive information and unauthorized operation suggestions.
    • Tool Calling Whitelist: Models can only call pre-registered tools, and high-risk operations require manual confirmation.

    6.4 Key and Log Management

    • Model API keys are stored in a key management service (KMS), separated by model and environment, and rotated regularly. Keys must not appear in code repositories or logs.
    • Audit logs record the operator, task_id, model_id, data level, and timestamp. The original text is not recorded in logs.
    • The request body in debug logs is not persisted by default. If troubleshooting is needed, it should be temporarily enabled in a permission-controlled environment with an automatic expiration time set.
    • The retention period of audit logs is set according to compliance requirements.

    VII. Version Management and Quality Evaluation

    7.1 Version Management

    Each model maintains an independent version status, including online versions and candidate versions. New versions are first rolled out with a small proportion of traffic for gray release to observe key metrics. In case of anomalies, the routing configuration can switch back to the previous version within minutes.

    7.2 Evaluation