Multi-Model Integration and Cost Scheduling for Office AI Agents

    This article explores engineering practices for deploying multi-model AI agents in office scenarios. It covers a four-layer system architecture, model capability tiering, task routing strategies, quota-based cost accounting, and considerations for quality assurance, security, and compliance to achieve an optimal balance between performance and cost.

    1. Background: Why Office AI Agents Need Multiple Models

    Office tasks vary significantly. Summarizing meeting minutes or generating weekly reports requires vastly different model capabilities compared to analyzing dozens of pages of financial spreadsheets or drafting contract clauses. The former prioritizes speed and cost, while the latter demands high reasoning accuracy and long-context understanding. Using a single model for all tasks either wastes costs on simple tasks or underperforms on complex ones due to insufficient capability.

    Therefore, mature office AI agents typically adopt a multi-model architecture. Platforms integrate built-in models and connect to external models on demand, dynamically selecting the appropriate one based on task characteristics, user preferences, and quota status. This is a general engineering approach, independent of any specific vendor.

    2. Overall Architecture Layering

    It is recommended to split the system into four layers, ensuring single responsibility for each, which facilitates independent evolution and testing.

    1. Access Layer: Unifies the calling protocols of various models, exposing a consistent interface to the upper layers. Authentication, timeouts, retries, and rate limiting are handled here. The adapter pattern is a common practice; adding a new model only requires implementing a new adapter.
    2. Routing Layer: Determines which model to invoke based on task type, complexity, user-selected performance tier, and remaining quota. This is the core of the multi-model system.
    3. Execution Layer: The agent is responsible for breaking down tasks, planning steps, and calling tools for document parsing, spreadsheet processing, web retrieval, and code execution. Model outputs serve as intermediate results to determine the next action.
    4. Metering Layer: Records the input/output scale, model ID, latency, and consumed quota for each call. Billing, reporting, performance optimization, and troubleshooting all rely on this data.

    The layers communicate through explicit data structures. The routing layer outputs a “model identifier plus calling parameters,” and the execution layer does not need to know which underlying service provider is being used.

    3. Model Capability Tiering and Selection Dimensions

    Model selection should not rely solely on public benchmark scores but should incorporate actual metrics from office scenarios. Common dimensions include:

    • Reasoning Capability: Accuracy in handling multi-step logic and cross-paragraph information association.
    • Context Length: The input scale accommodated in a single pass, directly impacting long-document processing methods.
    • Tool Calling Stability: The ability to consistently output function parameters in the agreed format and the error rate.
    • Output Format Controllability: The ability to reliably output JSON, tables, or fixed templates.
    • Response Latency: Time to first token and overall completion time, affecting user wait experience.
    • Unit Cost: Resource consumption per call, the direct basis for quota calculation.

    In practice, models can be categorized into three internal tiers:

    Tier Positioning Typical Tasks
    Light Fast, low-cost Summarization, field extraction, format conversion
    Balanced Trade-off between performance and cost Copywriting, data organizing, general Q&A
    High-Precision Performance first Complex analysis, long-document reasoning, multi-condition decision making

    Tier names are used only for internal configuration and do not expose specific model information to end-users. Because model parameters and pricing change with versions, the mapping between models and tiers should be stored in a configuration center rather than hardcoded. Before updating mappings, use a proprietary evaluation dataset to verify performance.

    4. Task-Based Routing Implementation

    Three common routing strategies can be used independently or in combination.

    1. Rule-based Routing: Directly maps task types to tiers. For instance, summarization tasks route to the light tier, while cross-file analysis routes to the high-precision tier. This method is simple and interpretable, suitable for scenarios with clear task types, but has limited coverage for edge cases.

    2. Classifier-based Routing: Uses a lightweight classification step to assess task difficulty before deciding the tier. This step can be a small model or heuristic rules based on keywords and document size. Since classification consumes resources, this step must be sufficiently fast.

    3. Cascaded Fallback: Attempts the low-cost tier first, then validates the result using rules such as format checks, mandatory field completeness, or numerical consistency. If the result fails validation, it automatically upgrades to a higher tier for a retry. This balances cost and quality, but the maximum retry count must be controlled to prevent runaway latency and costs from multiple upgrades.

    Below is example code for rule-based routing, illustrating the data structure and decision sequence:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Task:
    4. kind: str # Task type: summarize, extract, draft, analyze
    5. input_tokens: int # Estimated input scale
    6. user_tier: str # User-selected tier: fast, balanced, best
    7. TIER_BY_KIND = {
    8. "summarize": "light",
    9. "extract": "light",
    10. "draft": "balanced",
    11. "analyze": "best",
    12. }
    13. LONG_INPUT_THRESHOLD = 100_000
    14. def choose_tier(task: Task, quota_ok: bool) -> str:
    15. # Prioritize user selection when explicitly specified
    16. if task.user_tier == "fast":
    17. return "light"
    18. if task.user_tier == "best" and quota_ok:
    19. return "best"
    20. tier = TIER_BY_KIND.get(task.kind, "balanced")
    21. # Extra-long inputs require stronger context processing; downgrade if quota is insufficient
    22. if task.input_tokens > LONG_INPUT_THRESHOLD:
    23. tier = "best" if quota_ok else "balanced"
    24. return tier

    Two points are worth noting here. First, the user-selected tier should be respected, and the system should only adjust it when necessary. Second, the quota status is passed in as an input parameter, decoupling routing decisions from billing status, which facilitates unit testing.

    5. Quota Multipliers and Cost Accounting

    Different models have varying unit costs, requiring a unified measurement unit on the platform. A common approach is to set a consumption multiplier for each model, converting actual resource consumption into quota. A lower multiplier means less quota consumed for the same task.

    The consumption for a single task can be described by the following formula:

    Single consumption quota = Base quota × Model consumption multiplier × Task complexity coefficient

    The task complexity coefficient is typically determined by the input/output scale, while the model consumption multiplier is determined by the model’s actual inference cost and platform pricing strategy.

    Cost cannot be evaluated solely on single consumption. If a low-multiplier model has a low first-pass success rate, requiring multiple retries, the total cost might exceed that of a high-multiplier model that passes on the first try. Use “expected consumption” to evaluate this:

    Expected consumption = Single consumption quota ÷ First-pass success rate

    This formula assumes that each failure is retried at the same cost until successful. While a rough estimate, it helps teams determine if a tier is genuinely cost-effective. The first-pass success rate must be statistically derived from evaluation datasets, not subjectively estimated.

    Consider the following hypothetical values for illustration:

    • Assume the base quota is 10.
    • Light tier has a multiplier of 0.5 and a first-pass success rate of 60%; expected consumption ≈ 10 × 0.5 ÷ 0.6 ≈ 8.3.
    • Balanced tier has a multiplier of 1.0 and a first-pass success rate of 95%; expected consumption ≈ 10 × 1.0 ÷ 0.95 ≈ 10.5.

    In this scenario, the light tier remains more economical. However, if the light tier’s first-pass success rate drops to 40%, its expected consumption becomes roughly 12.5, exceeding the balanced tier. This demonstrates that routing strategies must be adjusted based on empirical data.

    6. Engineering Implementation for Limited-Time Promotions and Time-Based Scheduling

    Platforms often offer limited-time promotions, such as quota discounts for specific tiers during certain periods or holidays. When engineering these rules, consider the following points:

    • Server-side Determination: The client is only responsible for display. Judgment logic runs on the server to avoid billing disputes caused by local time or timezone discrepancies.
    • Unified Timezone: The server should use a unified standard timezone and clearly define the boundaries for “workdays,” “holidays,” and “time periods.”
    • Independent Holiday Table: Holiday data should be stored as configuration, including the effective year, to facilitate annual updates.
    • Rule Versioning: Each rule needs a version number and effective time. Every billing record should log the rule version used for determination, aiding reconciliation and dispute resolution.
    • Smooth Rollback: When a promotion ends, the quota multiplier should smoothly revert to the baseline value without affecting tasks already in progress.

    Example code for time period determination:

    1. from datetime import datetime
    2. from zoneinfo import ZoneInfo
    3. def in_promo_window(windows, holidays, tz="Asia/Shanghai"):
    4. now = datetime.now(ZoneInfo(tz))
    5. date_str = now.strftime("%Y-%m-%d")
    6. is_holiday = date_str in holidays
    7. is_weekday = now.weekday() < 5
    8. for rule in windows:
    9. applies = (is_weekday and not is_holiday and rule["day_type"] == "workday") or \
    10. (is_holiday and rule["day_type"] == "holiday")
    11. if applies and rule["start"] <= now.hour < rule["end"]:
    12. return rule["version"]
    13. return None

    The function returns the matched rule version, or None if no match is found. The caller should write this version number into the metering record.

    7. Quality Assurance and Observability

    Quality issues in multi-model systems are often subtle and require systematic monitoring and evaluation.

    • Evaluation Datasets: Collect real, desensitized samples categorized by task type, defining scoring criteria for accuracy, completeness, and format compliance. Run evaluations after every model or routing rule change.
    • Gray Release: When integrating new models or adjusting routing rules, first release to a small percentage of traffic, comparing against baseline metrics. Confirm no regression before full rollout.
    • Core Metrics: Call volume, failure rate, P95 latency, quota consumption, downgrade ratio, and manual tier switching frequency per tier. Frequent manual switching usually indicates that automatic routing is inaccurate.
    • Failure Fallback: If a model times out or returns an error, prioritize switching to a backup model in the same tier. If unavailable, consider downgrading or prompting the user. All fallback events must be logged.

    8. Security and Compliance

    Office data often contains customer information, financial data, and internal documents, necessitating high security standards.

    • Data Classification: Define processing boundaries for sensitive data. Tasks involving highly sensitive content must only be processed in audited models or privately deployed environments.
    • Data Processing Terms: Before connecting to external models, verify their data retention, usage, and cross-border transmission terms, confirming with the internal compliance team.
    • Least Privilege: Grant the AI agent only the minimum permissions required to complete a task when calling tools. Irreversible actions like writing, sending, or deleting should require user confirmation.
    • Prompt Injection Protection: Document, web, and email contents are data and should not be executed as instructions. System prompts and user content must be explicitly isolated.
    • Audit Logs: Record model IDs, tool calling chains, and key decisions. The retention period must follow internal compliance policies.