Multi-Model Routing and Cost Control for Office Agents: An Engineering Practice Guide
This article presents an engineering approach to integrating multiple large language models into office AI agents. It explains why office agents that handle document drafting, meeting notes, spreadsheet analysis, and report generation benefit from multi-model routing, then walks through a layered design: a unified access layer that hides provider differences through adapters, a task routing layer that matches each call to an appropriate model, and a cost center that handles quota accounting and budget control. It covers rule-based and scoring-based routing, cascade and fallback strategies, semantic caching and context compression, quota rate metering, off-peak scheduling, observability and regression testing, and security and compliance. A phased rollout roadmap rounds out the guide, helping teams deliver a balance of quality, speed, and cost in real production environments.
1. Background: Why Office Agents Need Multiple LLMs
Office products delivered in the form of AI agents have become increasingly common in recent years. These products target productivity scenarios such as document writing, meeting note organization, spreadsheet data analysis, report generation, and cross-document retrieval. Most follow an execution pattern of “understand the goal → plan steps → call tools → validate results → deliver outputs.” Steps along the execution chain, such as planning, reasoning, code generation, and content validation, rely heavily on large language models.
A single user task often requires multiple model calls: one to break down the task, one to summarize retrieval results, one to generate a draft, and another for self-check and revision. The number of calls rises with task complexity. The same task may involve long documents ranging from a few thousand to tens of thousands of words, scaling up both input and output token consumption. The impact of model choice on task quality, response speed, and quota consumption accumulates with every call.
Users have differing needs:
- Quality-first users: They care about output quality, such as the rigor of contract review or the accuracy of data analysis conclusions, and are willing to use more capable models for complex tasks.
- Efficiency-first users: They focus on response speed and want simple rewriting, summarization, and format conversion to return instantly.
- Cost-sensitive users: They have high daily task volume and want their limited quota to last as long as possible.
A single model can hardly satisfy all three needs at once. As a result, integrating multiple LLMs with different capabilities and costs into office agent products has gradually become a common architectural choice in the industry. Terms such as “multi-model routing” and “model gateway” are widely used to describe this approach.
From an engineering standpoint, integrating multiple models introduces at least three problems:
- Heterogeneity: Different model services differ in interface details, error semantics, context length, and the degree of tool-calling support.
- Selection: How to pick the right model for each call based on task characteristics and budget.
- Metering and governance: How to make quota consumption transparent and predictable for users, while continuously monitoring and optimizing it on the backend.
The sections below present a general design in the order of access layer → routing layer → metering and cost control → observability and governance → rollout roadmap.
2. Overall Architecture: Model Gateway, Task Routing, and Cost Center
A multi-model agent system can be abstracted into three decoupled core modules:
- Model gateway: Handles integration, adaptation, and protocol unification, hiding differences between model services and exposing a consistent calling interface to upper layers.
- Task routing: Decides which model to use for each call based on task characteristics, user preferences, budget state, and real-time load, and performs fallback when exceptions occur.
- Cost center: Handles usage collection, rate conversion, quota deduction, and budget control. It is the hub connecting the technical system with users’ cost awareness.
A governance module should also be in place, including logging, distributed tracing, monitoring and alerting, and regression evaluation. The following design principles are recommended:
- Capability abstraction: Routing logic depends only on “capability tags,” not on any specific vendor.
- Replaceability: Adapters correspond one-to-one with specific vendors; replacing or adding a vendor requires only a new adapter.
- Observability: Every call records task type, model identifier, usage, latency, and converted consumption.
- Rollback: Any policy change can be quickly rolled back through a configuration switch.
Schematic architecture:
┌──────────────────────────── User / Task Entry ──────────────────────────┐│ Office Agent (Plan → Tool Calls → Generate → Validate → Deliver) │└───────────────────────────────┬──────────────────────────────────────────┘│ Unified message format + capability tags + task type┌──────────▼──────────┐│ Model Gateway ││ Registry / Adapters / Protocol normalization ││ Retry / Circuit break / Fallback │└──────────┬──────────┘┌──────────────────┼──────────────────┐┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐│Light Model A│ │General Model B│ │Strong Reasoning Model C│└───────────┘ └───────────┘ └───────────┘│┌──────────▼──────────┐│ Task Routing / Cost Center ││ Rule routing / Scoring routing ││ Cascade / Fallback / Budget gate ││ Rate conversion / Usage accounting │└─────────────────────┘
3. Unified Access Layer: Hiding Heterogeneity
3.1 Why an Adapter Layer Is Needed
Common model services have converged in interface style, mostly using a “message array + role” structure. User input, assistant replies, and tool call results are placed in separate messages; the server returns text, tool call intents, and usage information such as input/output tokens in the response. But subtle differences remain, typically of five kinds:
- Authentication and access method: API key versus access token, and request header conventions;
- Error semantics: Rate limiting, parameter validation failure, timeout, content safety interception, and other scenarios may return different structures;
- Streaming: The way data chunks are concatenated and the end-of-stream marker may differ;
- Context length and output limits: These vary across models and directly affect how long-document tasks are handled;
- Capability support: Whether tool calling, structured output, multimodal input, and so on are supported.
If business code directly calls each vendor’s interface, cross-cutting logic such as routing, billing, and retries is forced to be implemented in a scattered way. Once a vendor needs to be replaced or added, the relevant code must be changed extensively. The value of the adapter layer is to converge these differences into one place.
3.2 Adapter Interface Design
The access layer can be described with a unified ModelConnector protocol:
from dataclasses import dataclassfrom typing import Protocol@dataclass(frozen=True)class ModelProfile:name: strtier: str # light / general / strong, determined by routing tagscontext_window: int # context window (tokens)quota_rate: float # quota consumption rate; the lower, the less consumedsupports_tools: boolsupports_stream: boolcost_index: float # cost index used for unified conversion@dataclassclass Usage:prompt_tokens: intcompletion_tokens: intcached_tokens: int = 0@propertydef total(self) -> int:return self.prompt_tokens + self.completion_tokensclass ModelConnector(Protocol):profile: ModelProfiledef chat(self, messages: list[dict], **kwargs) -> tuple[str, Usage]: ...def stream(self, messages: list[dict], **kwargs): ...def quota_of(self, usage: Usage) -> float:# Convert by rate as the unified metering "quota unit"return usage.total * self.profile.quota_rate
When adding a vendor, you only need to implement the two methods chat and stream, converting that vendor’s response format into the unified structure, for example:
class SomeVendorConnector:profile = ModelProfile(name="general-model-b",tier="general",context_window=128000,quota_rate=1.0,supports_tools=True,supports_stream=True,cost_index=1.0,)def chat(self, messages, **kwargs):raw = self._http_post(messages, **kwargs) # Call the specific vendortext = raw["choices"][0]["message"]["content"]usage = Usage(prompt_tokens=raw["usage"]["prompt_tokens"],completion_tokens=raw["usage"]["completion_tokens"],)return text, usage
3.3 Registry and Capability Detection
The model registry centrally maintains the metadata of all integrated models. For capabilities that may change, such as context length and tool-calling support, it is recommended to detect them automatically at startup and cache the results, so that routing logic does not run on outdated assumptions:
REGISTRY: dict[str, ModelConnector] = {"light-model-a": LightConnector(),"general-model-b": SomeVendorConnector(),"strong-model-c": StrongConnector(),}def find_by_tier(tier: str) -> list[ModelConnector]:return [c for c in REGISTRY.values() if c.profile.tier == tier]
3.4 Unified Error Classification and Retry Strategy
The adapter layer should normalize error codes from each vendor into unified error types, for example:
- Retryable: rate limiting, timeout, transient service unavailability;
- Non-retryable: parameter errors, authentication failures, content interception;
- Fallback-able: the current model does not support a feature, for example, no tool-calling support.
Only by clearly distinguishing error types can retry, circuit breaking, and fallback strategies be executed precisely.
4. Task Routing: Routing the Right Task to the Right Model
4.1 Factors in Routing Decisions
Routing decisions usually consider the following factors:
- Task type: Short-text tasks such as summarization, rewriting, extraction, and translation have lower reasoning requirements; tasks such as data analysis, solution planning, long-form writing, and code generation have higher reasoning requirements;
- Complexity signals: input length, number of documents involved, expected number of tool calls, and the user-selected execution mode (fast/standard/deep);
- Resource constraints: the user’s remaining quota, current system load, and real-time responsiveness of different models;
- Capability constraints: whether the context window can fit the input, and whether tool-calling capability is required.
4.2 Rule-Based Routing
Rule-based routing is simple to implement and its behavior is explainable, making it suitable as a first-version strategy. The core is to maintain a “task type → available models” mapping table and sort within the same tier by cost or load:
TASK_TIER = {"rewrite": "light","summarize": "light","extract": "general","analyze_data": "strong","plan": "strong",}def route_by_rule(task_type: str, prompt_len: int, quota_left: float):tier = TASK_TIER.get(task_type, "general")candidates = [c for c in find_by_tier(tier)if c.profile.context_window >= prompt_len]if not candidates:raise NoAvailableModel(tier)# When the budget is tight, prefer models with lower rate and cost indexif quota_left < LOW_BUDGET:candidates.sort(key=lambda c: c.profile.quota_rate)else:candidates.sort(key=lambda c: c.profile.cost_index)return candidates[0]
The limitation of rule-based routing is that thresholds are hard to fix: within the same task category, simple and difficult cases differ greatly, and a fixed mapping easily becomes unbalanced between “insufficient quality” and “excessive cost.”
4.3 Scoring-Based Routing
A more refined approach treats routing as a constrained optimization problem. A composite score is computed for each candidate model, and the highest-scoring one is chosen subject to hard constraints:
score = w1 × quality score − w2 × rate − w3 × predicted latency + w4 × load health
where:
- Quality score: the model’s normalized performance on samples similar to the current task type in the team’s self-built task set;
- Rate: represents the consumption of the user’s quota for this call;
- Predicted latency: can be estimated from recent historical statistics;
- Load health: computed from current queuing and error rate.
The weights w1~w4 can be configured according to business goals (quality-first or cost-first). Hard constraints include context length and required capabilities (such as tool calling). The advantage of scoring-based routing is that it can smoothly balance multiple objectives, but it also requires continuous data accumulation and parameter tuning.
4.4 Cascade and Fallback
Cascade: First use a lightweight model; when confidence is insufficient or the result fails validation, hand it over to a stronger model to redo. A typical flow is:
- The lightweight model generates a first draft;
- Run deterministic validation: whether JSON format is valid, whether required fields are present, whether references are traceable, and so on;
- If validation passes, return directly; if not, escalate to a general or strong reasoning model and pass the error information along to guide its correction.
def run_with_cascade(task, chain, max_retry=2):for model in chain:for _ in range(max_retry):output, usage = model.chat(build_messages(task))result = validate(task, output) # Deterministic validation, no model callif result.ok:return output, usagetask.feedback = result.reason # Feed the validation failure reason back to the modelraise TaskFailed(task)
Cascade strategies are especially effective for structured-output tasks (table extraction, information filling, report field validation). They shift part of the “correctness guarantee” responsibility from the model to verifiable rules, often achieving results close to a strong model at a lower cost.
Fallback: When the preferred model times out, is rate-limited, or is unavailable, routing should automatically switch to a backup model of the same or next-higher tier, avoiding overall task failure. Fallback needs to work with a circuit breaker: after the same model fails consecutively beyond a threshold within a short time, temporarily remove it from the candidate set and re-add it once recovery is detected.
4.5 Routing with Caching
In the agent’s plan-execute loop, sub-steps of the same task may repeatedly call the same model with the same prompt. It is recommended to add a semantic cache at the gateway layer: use “normalized prompt + tool definitions + key context summary” as the key, and reuse the result on a hit. Caching can significantly reduce consumption for high-frequency, low-complexity tasks, but it needs a reasonable invalidation strategy, such as setting a maximum cache duration or disabling caching for time-sensitive tasks.
5. Cost Control: Rate Metering, Quota Governance, and Off-Peak Scheduling
5.1 Quota Consumption Rate: Unified Metering Across Models
Different models may be priced differently for input and output tokens, so directly comparing raw token counts does not reflect true resource consumption. A common industry practice is to introduce a “quota consumption rate” that converts each model’s call cost into a unified quota unit:
quota consumed this time = input tokens × input rate + output tokens × output rate
The lower the rate coefficient, the less quota the same task consumes, and the longer the quota lasts. In product design, each model’s rate is usually labeled on the model selection page, so users have a clear cost expectation while choosing a capability tier. Rates should be driven by cost accounting and calibrated periodically to keep the labeled rate roughly consistent with actual cost, avoiding misleading users.
5.2 Budget Gates and User-Side Cost Awareness
The cost center needs to maintain user quota state before and after each call:
- Pre-call check: Estimate the expected consumption of this task, prompt in advance when the balance is insufficient, or suggest switching to a lower-rate model;
- In-call deduction: Deduct in real time based on actual usage and rate;
- Overspend protection: Set a maximum consumption limit per task to prevent the agent from falling into a loop that abnormally consumes quota;
- Transparent display: Show estimated consumption before the task starts, and actual consumption and remaining quota after the task ends.
def try_charge(user_id: str, model: ModelConnector, usage: Usage) -> bool:cost = model.quota_of(usage)return ledger.reserve(user_id, cost) # Pre-deduct
5.3 Caching and Context Compression
Beyond routing, the most direct way to reduce consumption is to cut unnecessary tokens:
- Context compression: Segment and summarize long documents, or extract key snippets, before sending them to the model, avoiding repeatedly feeding an entire document into the context;
- Prompt trimming: Remove redundant examples and repeated instructions to reduce fixed overhead;
- Result reuse: For multiple questions about the same document, reuse generated summaries or structured intermediate results.
5.4 Off-Peak Scheduling and Discount Mechanisms
System load differs markedly between high-capacity and tight-capacity periods. During resource-tight periods, queuing latency rises and response speed drops. Off-peak scheduling places some deferrable tasks in lower-load periods to shorten average wait time. Common forms include:
- Discount windows: Lower the quota consumption rate of participating models during specified periods, encouraging users to complete non-urgent tasks then and thereby smoothing peak load;
- Batch task queuing: Non-real-time tasks such as batch document processing and scheduled report generation are placed in an asynchronous queue and run in bulk during off-peak periods;
- Off-peak preference: When the preferred model is at peak, prefer lower-rate, lighter-load models and notify the user.
Offering free quota for simple, low-volume tasks is a common way to lower the barrier to adoption and promote product uptake. It depends on a clear definition of “low-volume,” such as a maximum token count per task or a daily free-call limit, combined with anti-abuse mechanisms to avoid abuse by large-scale scripts.
It should be emphasized that discount windows and rate reductions are operational levers. The specific rules need to be clearly shown to users, and page descriptions should be updated promptly when rules change to avoid expectation gaps.
6. Observability and Governance
6.1 Key Metrics
At a minimum, collect the following metrics:
- Quality: task success rate, first-pass rate, cascade escalation rate, fallback count;
- Cost: average quota consumed per task, call share of each model, cache hit rate;
- Performance: time-to-first-token, end-to-end latency P50/P95/P99, timeout and rate-limit counts.
metrics = {"task_success_rate": 0.97,"cascade_rate": 0.18, # Cascade escalation share"avg_quota_per_task": 12.5, # Average consumption per task"cache_hit_rate": 0.23,"latency_p95_ms": 4200,}
6.2 Logging and Distributed Tracing
Every call should record the task ID, task type, model identifier, input/output tokens, latency, error type, and converted consumption, forming a complete call chain. When quality or cost anomalies occur, this can be used to trace back the problematic step: whether the task itself was too complex, whether the routing strategy picked the wrong model, or whether a vendor had a fluctuation.
6.3 Regression Evaluation and Canary Release
Build a fixed evaluation set covering various office tasks. Before and after model integration, routing strategy adjustments, and prompt changes, compare quality and consumption on the same evaluation set to avoid “cost reduction causing quality degradation.” New strategies should first be canaried on a small fraction of traffic, and released fully only after confirming that metrics remain stable.
7. Security and Compliance
After integrating multiple external model services, the scope of data egress expands, requiring focus on:
- Data classification: Define which data may be sent to external models; desensitize sensitive information or process it locally before sending;
- Transmission and storage security: Encrypt the entire chain in transit, and avoid logging complete sensitive content in call logs;
- Content safety: Perform necessary safety review on inputs and outputs to prevent generation of non-compliant content;
- Access control: Implement authentication and quota management for model-calling interfaces to prevent unauthorized calls.
8. Rollout Roadmap
- Phase 1: Unified access. Package the adapter layer and registry, integrate 1–2 models, and connect logging and usage collection;
- Phase 2: Rule-based routing and cost center. Establish task classification and rule-based routing, and launch rate conversion, quota deduction, and budget gates;
- Phase 3: Cascade and caching. Introduce deterministic validation, cascade escalation, semantic caching, and context compression to continuously reduce per-task consumption;
- Phase 4: Scoring-based routing and off-peak scheduling. Tune scoring weights based on evaluation data, and launch discount windows and asynchronous queuing for batch tasks;
- Phase 5: Continuous governance. Establish regression evaluation and canary mechanisms, periodically calibrate rates, and form a “monitor–analyze–optimize” closed loop.
9. Conclusion
Integrating multiple LLMs into office agents is essentially about using “multi-model collaboration” to balance quality, speed, and cost. The engineering essentials can be summarized in four points:
- Use a unified access layer to hide heterogeneity, making adding or replacing models a low-cost incremental development;
- Use rule-based routing as the foundation and scoring-based routing as the advanced tier, so each call flows to an appropriate model;
- Reduce ineffective consumption through cascade validation, cache reuse, and context compression;
- Make user costs predictable and system load more balanced through rate metering, transparent display, budget gates, and off-peak scheduling.
On this foundation, backed by a complete monitoring, evaluation, and security-compliance system, office agents can continuously and stably deliver high-quality results in real, complex production scenarios.
