Multi-Model Integration and Orchestration for Office AI Agents: A Practical Implementation Guide

    Office AI agents often begin with a single self-built model that handles summaries, Q&A, form filling, and document extraction. As tasks multiply, user volume grows, and the model ecosystem shifts faster, a single-model architecture eventually hits walls around capability gaps, peak-time throttling, cost pressure, and vendor lock-in. This guide is written for backend and platform developers designing the model integration layer for office agents. It shows how to build a vendor-neutral abstraction layer with adapters, turn capability, price, latency, quality, and health into routable metadata through a model registry, choose routing policies that trade off cost, latency, and quality, write fallback chains grounded in retryable and non-retryable error classification, keep behavior consistent across models through context management, and add quality, cost, observability, and compliance governance, closing with a minimal day-one checklist.

    Introduction: Why Office AI Agents Need a Multi-Model Architecture

    Office agents usually start by integrating a single self-built model that clears the bar for basic tasks such as summarization, Q&A, form filling, and document extraction. But as tasks multiply, user volume rises, and the model ecosystem changes faster, a single-model architecture gradually runs into capability limits, peak-time throttling, cost pressure, and vendor lock-in. At that point, the platform needs to move from “one model does everything” to multi-model orchestration, turning model capability into pluggable, routable, governable gateway capabilities.

    This article is aimed at backend and platform developers building the model integration layer for office agents. After reading it, you should be able to decide when a multi-model architecture is warranted, how to design a unified abstraction layer and adapters, how to use LLM routing strategies to trade off cost, latency, and quality, and how to fill in fallback, observability, cost, compliance, and a checklist of common mistakes.

    1. When Do Office Agents Need Multiple Models, and When Is One Model Enough?

    A single-model architecture is not a mistake. If call volume is low, task types are narrow, there is no obvious disaster-recovery requirement, and model quality already meets business goals, staying with a single model is actually simpler. But once the business enters a growth phase, multi-model orchestration typically delivers the following benefits:

    Single-model pain point Multi-model benefit
    Different tasks demand different capabilities: long-document summarization, structured extraction, code generation, and multi-turn dialogue each have their own preferences Complementary capabilities: pick the most suitable model per task and improve overall quality
    A single provider may queue, throttle, or fluctuate during peak hours High availability and disaster recovery: automatically switch to a backup model when the primary fails
    High-frequency simple tasks are expensive if they all run on a large model Cost and performance trade-off: simple tasks go to lightweight models, complex tasks to high-quality models
    Deep coupling to a single provider limits future negotiating room and migration options Reduced lock-in risk: keep the ability to switch providers, run canary releases, and roll back
    A self-built model’s iteration pace struggles to cover every niche scenario Ecosystem collaboration: self-built models run alongside third-party open-source models and commercial API models

    So the point of multi-model integration is not “the more models, the better,” but turning the model from a hard-coded implementation into infrastructure capability that can be registered, routed, degraded, metered, and governed.

    2. The Unified Abstraction Layer: How to Avoid if model == A Everywhere in Business Code

    The most common problem in a multi-model architecture is scattering model differences across business code. For example:

    1. if model == "model_a":
    2. resp = call_a(prompt)
    3. elif model == "model_b":
    4. resp = call_b(prompt)

    This looks simple in the short term but leads to high integration cost, inconsistent parameters, and hard-to-diagnose errors over time. The right approach is to first build a vendor-neutral unified abstraction layer, then confine each model’s differences to adapters.

    1. Minimal Abstraction Interface

    1. from abc import ABC, abstractmethod
    2. from dataclasses import dataclass, field
    3. from typing import Iterator
    4. @dataclass
    5. class ModelRequest:
    6. prompt: str
    7. messages: list = field(default_factory=list)
    8. max_tokens: int = 1024
    9. temperature: float = 0.7
    10. extra: dict = field(default_factory=dict)
    11. @dataclass
    12. class ModelResponse:
    13. content: str
    14. model_id: str = ""
    15. latency_ms: float = 0.0
    16. tokens_used: int = 0
    17. @dataclass
    18. class ModelStreamEvent:
    19. delta: str
    20. model_id: str
    21. done: bool = False
    22. class ModelAdapter(ABC):
    23. @abstractmethod
    24. def chat(self, req: ModelRequest) -> ModelResponse:
    25. """Forward the request to the underlying model and normalize it into a unified response."""
    26. ...
    27. def chat_stream(self, req: ModelRequest) -> Iterator[ModelStreamEvent]:
    28. """For streaming responses, normalize incremental output from different providers into unified events."""
    29. raise NotImplementedError("this adapter does not support streaming")

    The business layer depends only on ModelAdapter and the unified request/response objects. When adding a new model, business code should not need to change; however, if the new model offers new capabilities—for example, a new modality, a new tool-calling format, or a new pricing structure—you still need to update the registry metadata, routing policy, and metering configuration.

    2. An Open-Source Model Adapter Example

    The following example assumes the target model exposes an OpenAI-compatible interface and can be deployed locally or in a self-hosted environment.

    1. import os
    2. import time
    3. import requests
    4. class RetryableModelError(Exception):
    5. pass
    6. class NonRetryableModelError(Exception):
    7. pass
    8. class OpenAICompatibleAdapter(ModelAdapter):
    9. def __init__(
    10. self,
    11. model_id: str,
    12. base_url: str,
    13. api_key_env: str,
    14. timeout: float = 5.0,
    15. max_retries: int = 2,
    16. ):
    17. self.model_id = model_id
    18. self.base_url = base_url.rstrip("/")
    19. self.api_key = os.environ[api_key_env]
    20. self.timeout = timeout
    21. self.max_retries = max_retries
    22. def _messages(self, req: ModelRequest):
    23. if req.messages:
    24. return req.messages
    25. return [{"role": "user", "content": req.prompt}]
    26. def _payload(self, req: ModelRequest):
    27. return {
    28. "model": self.model_id,
    29. "messages": self._messages(req),
    30. "max_tokens": req.max_tokens,
    31. "temperature": req.temperature,
    32. **req.extra,
    33. }
    34. def chat(self, req: ModelRequest) -> ModelResponse:
    35. start = time.time()
    36. resp = requests.post(
    37. f"{self.base_url}/chat/completions",
    38. json=self._payload(req),
    39. headers={"Authorization": f"Bearer {self.api_key}"},
    40. timeout=self.timeout,
    41. )
    42. if resp.status_code in (401, 403):
    43. raise NonRetryableModelError(f"auth failed: {resp.status_code}")
    44. if resp.status_code in (400, 422):
    45. raise NonRetryableModelError(f"invalid request: {resp.text[:200]}")
    46. if resp.status_code == 429 or resp.status_code >= 500:
    47. raise RetryableModelError(f"retryable status: {resp.status_code}")
    48. data = resp.json()
    49. usage = data.get("usage", {})
    50. return ModelResponse(
    51. content=data["choices"][0]["message"]["content"],
    52. model_id=self.model_id,
    53. latency_ms=(time.time() - start) * 1000,
    54. tokens_used=usage.get("total_tokens", 0),
    55. )

    3. Parameter Mapping for Commercial API Models

    Parameter names often differ between vendors. Some interfaces use max_tokens, others use max_completion_tokens; some place system inside messages, others require a separate system field. The adapter’s job is to handle these mappings.

    1. class CommercialApiAdapter(OpenAICompatibleAdapter):
    2. def _payload(self, req: ModelRequest):
    3. messages = self._messages(req)
    4. system_parts = [m["content"] for m in messages if m.get("role") == "system"]
    5. other_messages = [m for m in messages if m.get("role") != "system"]
    6. return {
    7. "model": self.model_id,
    8. "messages": other_messages,
    9. "system": "\n".join(system_parts),
    10. "max_completion_tokens": req.max_tokens,
    11. "temperature": req.temperature,
    12. **req.extra,
    13. }

    4. How to Unify Streaming Responses

    Data formats diverge even more for streaming output. The adapter should normalize incremental content into ModelStreamEvent, so the business layer consumes only unified events instead of parsing vendor response bodies directly.

    1. def chat_stream(self, req: ModelRequest) -> Iterator[ModelStreamEvent]:
    2. with requests.post(
    3. f"{self.base_url}/chat/completions",
    4. json={**self._payload(req), "stream": True},
    5. headers={"Authorization": f"Bearer {self.api_key}"},
    6. timeout=self.timeout,
    7. stream=True,
    8. ) as resp:
    9. if resp.status_code in (401, 403, 400, 422):
    10. raise NonRetryableModelError(f"stream init failed: {resp.status_code}")
    11. if resp.status_code == 429 or resp.status_code >= 500:
    12. raise RetryableModelError(f"stream retryable: {resp.status_code}")
    13. for line in resp.iter_lines():
    14. if not line:
    15. continue
    16. text = line.decode("utf-8")
    17. if text.startswith("data: "):
    18. text = text[6:]
    19. if text == "[DONE]":
    20. break
    21. data = json.loads(text)
    22. delta = data["choices"][0].get("delta", {}).get("content", "")
    23. if delta:
    24. yield ModelStreamEvent(delta=delta, model_id=self.model_id)
    25. if data["choices"][0].get("finish_reason"):
    26. yield ModelStreamEvent(delta="", model_id=self.model_id, done=True)

    3. Model Registry and Discovery: Turning Capability, Price, Latency, and Health into Schedulable Metadata

    Once you have adapters, you also need a registry to maintain model metadata. The router needs more than just “Model A and Model B”—it needs each model’s capability tags, context length, price, concurrency quota, latency profile, quality score, health, and fallback order.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class ModelMeta:
    4. model_id: str
    5. provider: str
    6. capabilities: set # {"chat", "code", "long_context", "multimodal"}
    7. context_window: int
    8. price_per_1k: float
    9. concurrent_quota: int = 0
    10. latency_p50: float = 0.0
    11. latency_p95: float = 0.0
    12. latency_p99: float = 0.0
    13. quality_score: float = 0.0 # 0~1, from an offline evaluation set
    14. health: float = 1.0 # updated in real time by monitoring
    15. priority: int = 0 # lower value means higher priority
    16. class ModelRegistry:
    17. def __init__(self):
    18. self._models: dict[str, ModelMeta] = {}
    19. def register(self, meta: ModelMeta):
    20. self._models[meta.model_id] = meta
    21. def get(self, model_id: str) -> ModelMeta:
    22. return self._models[model_id]
    23. def by_capability(self, cap: str):
    24. return [m for m in self._models.values() if cap in m.capabilities]

    The quality_score should come from an offline evaluation set. For example, build a test set covering office scenarios with tasks such as long-document summarization, structured extraction, table Q&A, code generation, and multi-turn dialogue. Score each capability dimension separately to produce a quality score between 0 and 1. If sample volume is insufficient, start with manual spot-check scoring and automate gradually. It is generally recommended to refresh once a week or before each routing-rule change.

    4. Choosing a Multi-Model Routing Strategy: Task, Cost/Latency, Quality, and Load

    Routing is the core of a multi-model architecture. There are three common routing dimensions:

    1. Routing by task capability: code generation goes to a model with strong coding ability, long-document handling goes to a long-context model, casual chat goes to a lightweight model.
    2. Routing by cost and latency: set budget ceilings and a latency SLO, and prefer the model with the best cost-performance ratio while meeting quality requirements.
    3. Routing by quality and load: combine model health, concurrency quota, and real-time latency to pick a model, avoiding pushing traffic onto an already overloaded model.

    Below is a routing example that combines all three dimensions. It no longer uses an inconsistent formulation like health * 1000; instead, it normalizes cost, latency, quality, and health separately and then sums them with weights.

    1. class ModelRouter:
    2. def __init__(self, registry: ModelRegistry):
    3. self.registry = registry
    4. def _candidates(
    5. self,
    6. task_cap: str,
    7. max_latency_ms: float | None = None,
    8. max_price_per_1k: float | None = None,
    9. min_concurrent: int | None = None,
    10. ):
    11. candidates = self.registry.by_capability(task_cap)
    12. if max_latency_ms is not None:
    13. candidates = [
    14. m for m in candidates
    15. if m.latency_p95 and m.latency_p95 <= max_latency_ms
    16. ]
    17. if max_price_per_1k is not None:
    18. candidates = [
    19. m for m in candidates
    20. if m.price_per_1k <= max_price_per_1k
    21. ]
    22. if min_concurrent is not None:
    23. candidates = [
    24. m for m in candidates
    25. if m.concurrent_quota >= min_concurrent
    26. ]
    27. # Models with too-low health do not participate in this routing decision
    28. candidates = [m for m in candidates if m.health >= 0.2]
    29. if not candidates:
    30. raise RuntimeError(f"no model for capability: {task_cap}")
    31. return candidates
    32. def ordered(
    33. self,
    34. task_cap: str,
    35. policy: str = "balanced",
    36. max_latency_ms: float | None = None,
    37. max_price_per_1k: float | None = None,
    38. min_concurrent: int | None = None,
    39. ):
    40. candidates = self._candidates(
    41. task_cap,
    42. max_latency_ms=max_latency_ms,
    43. max_price_per_1k=max_price_per_1k,
    44. min_concurrent=min_concurrent,
    45. )
    46. max_price = max([m.price_per_1k for m in candidates] + [1e-6])
    47. max_latency = max([m.latency_p95 for m in candidates] + [1.0])
    48. def score(m: ModelMeta) -> float:
    49. # Cost score: cheaper is better
    50. cost_score = 1 - m.price_per_1k / max(max_price, 1e-6)
    51. # Latency score: lower is better
    52. latency_score = 1 - min(m.latency_p95 / max(max_latency, 1.0), 1.0)
    53. # Quality and health are clamped to 0~1
    54. quality_score = max(0.0, min(1.0, m.quality_score))
    55. health_score = max(0.0, min(1.0, m.health))
    56. if policy == "cost":
    57. # Cost-first
    58. wc, wl, wq, wh = 0.55, 0.15, 0.20, 0.10
    59. elif policy == "quality":
    60. # Quality-first
    61. wc, wl, wq, wh = 0.10, 0.10, 0.65, 0.15
    62. else:
    63. # balanced: a compromise across cost, latency, quality, and health
    64. wc, wl, wq, wh = 0.20, 0.15, 0.40, 0.25
    65. return (
    66. wc * cost_score
    67. + wl * latency_score
    68. + wq * quality_score
    69. + wh * health_score
    70. )
    71. return sorted(
    72. candidates,
    73. key=lambda m: (score(m), -m.priority),
    74. reverse=True,
    75. )
    76. def select(
    77. self,
    78. task_cap: str,
    79. policy: str = "balanced",
    80. max_latency_ms: float | None = None,
    81. max_price_per_1k: float | None = None,
    82. min_concurrent: int | None = None,
    83. ) -> str:
    84. return self.ordered(
    85. task_cap,
    86. policy=policy,
    87. max_latency_ms=max_latency_ms,
    88. max_price_per_1k=max_price_per_1k,
    89. min_concurrent=min_concurrent,
    90. )[0].model_id
    91. def fallback_chain(
    92. self,
    93. task_cap: str,
    94. policy: str = "balanced",
    95. max_latency_ms: float | None = None,
    96. max_price_per_1k: float | None = None,
    97. min_concurrent: int | None = None,
    98. limit: int = 3,
    99. ):
    100. ordered = self.ordered(
    101. task_cap,
    102. policy=policy,
    103. max_latency_ms=max_latency_ms,
    104. max_price_per_1k=max_price_per_1k,
    105. min_concurrent=min_concurrent,
    106. )
    107. # The first is the primary model; the rest are backup models
    108. return [m.model_id for m in ordered[1:1 + limit]]

    5. Writing the Fallback Chain: Retryable Errors, Non-Retryable Errors, and Circuit Breaking

    The fallback chain is the bottom line for multi-model platform stability. Note that not every exception should trigger a model switch. Authentication failures (401/403), parameter errors, and context-overflow issues generally should not be solved by switching to a backup model; timeouts, rate limiting, and 5xx errors are the ones suited to retry or degradation.

    1. def chat_with_fallback(
    2. router: ModelRouter,
    3. adapters: dict,
    4. req: ModelRequest,
    5. task_cap: str,
    6. policy: str = "balanced",
    7. max_latency_ms: float | None = None,
    8. max_price_per_1k: float | None = None,
    9. max_retries: int = 1,
    10. ):
    11. primary = router.select(
    12. task_cap,
    13. policy=policy,
    14. max_latency_ms=max_latency_ms,
    15. max_price_per_1k=max_price_per_1k,
    16. )
    17. fallback = router.fallback_chain(
    18. task_cap,
    19. policy=policy,
    20. max_latency_ms=max_latency_ms,
    21. max_price_per_1k=max_price_per_1k,
    22. )
    23. candidate_ids = [primary, *fallback]
    24. last_error = None
    25. for mid in candidate_ids:
    26. adapter = adapters[mid]
    27. for attempt in range(max_retries + 1):
    28. start = time.time()
    29. try:
    30. resp = adapter.chat(req)
    31. # The adapter should populate model_id; this is only a safeguard to avoid masking adapter errors
    32. if not resp.model_id:
    33. resp.model_id = mid
    34. logger.info({
    35. "model_id": mid,
    36. "policy": policy,
    37. "attempt": attempt + 1,
    38. "latency_ms": (time.time() - start) * 1000,
    39. "tokens_used": resp.tokens_used,
    40. "degraded": mid != primary,
    41. })
    42. return resp
    43. except RetryableModelError as e:
    44. last_error = e
    45. logger.warning({
    46. "model_id": mid,
    47. "attempt": attempt + 1,
    48. "error": repr(e),
    49. })
    50. if attempt < max_retries:
    51. time.sleep(min(2 ** attempt, 5))
    52. except NonRetryableModelError as e:
    53. logger.error({
    54. "model_id": mid,
    55. "error": repr(e),
    56. "retryable": False,
    57. })
    58. raise
    59. # The current model failed repeatedly; trigger a circuit break or lower its health
    60. adapter.report_failure(last_error)
    61. raise RuntimeError("all candidate models failed") from last_error

    The key principles here are:

    • Only log and swallow retryable exceptions;
    • Non-retryable exceptions such as 401, 403, 400, and 422 should be raised directly;
    • Every retry, switch, and degradation should be logged;
    • Models that fail repeatedly should enter a circuit-broken state or have their health lowered;
    • Prefer the adapter’s returned resp.model_id, with the caller only providing a fallback when it is missing.

    6. Consistency and Context Management: Avoiding Sudden Behavior Shifts After Switching Models

    Different models differ in context window, message format, system-prompt adherence, and tool-calling format. Without unified context management, switching models can cause sudden shifts in output style, truncated prompts, or broken structured output.

    It is recommended to define a unified session context object at the request layer:

    1. @dataclass
    2. class AgentContext:
    3. session_id: str
    4. system_prompt: str
    5. history: list
    6. current_input: str
    7. attachments: list = field(default_factory=list)
    8. expected_schema: dict | None = None
    9. max_output_tokens: int = 512

    Before sending to the model, the router or adapter should allocate the budget based on model metadata:

    1. Available total context = context_window - max_output_tokens - safety_margin.
    2. Keep the system prompt first.
    3. Then add the current input and summaries of necessary attachments.
    4. Assign the remaining space to historical messages.
    5. If it still exceeds the limit, use a sliding window to truncate old messages, or summarize early history.

    Note: tokenization differs across models, so the same character count may map to very different token counts. When truncating, it is best to count against the real tokenizer and reserve a 10% to 20% safety margin to avoid prompts being truncated at the last moment.

    7. Quality and Effectiveness Governance: How to Validate No Quality Regression Before a New Model Ships

    One of the biggest risks of multi-model setups is that the same task produces different output styles and quality fluctuations across models. So routing is not a one-time configuration—it needs continuous evaluation.

    It is recommended to build an offline evaluation set covering each capability:

    • Long-document summarization: key-information coverage, factual consistency, length control.
    • Structured extraction: JSON schema compliance rate, field accuracy.
    • Code generation: executability, unit-test pass rate.
    • Multi-turn dialogue: intent retention, context consistency.
    • Table and document Q&A: answer accuracy, citation traceability.

    A new model launch, a routing-rule change, or a weight change should all trigger an offline regression. The regression report should include at least:

    • Quality-score change;
    • Average and P95 latency;
    • Cost change per task;
    • Error-rate change;
    • Format-validation failure rate.

    If quality drops beyond a threshold, automatically switch back to the old routing, or roll back gradually by tenant or traffic percentage.

    For format-sensitive tasks such as long documents and structured extraction, add schema validation after the model returns. On validation failure, retry once first; if it still fails, degrade to a more stable model.

    8. Observability and Cost Governance: Making Every Call Meterable and Traceable

    A multi-model architecture must be observable; otherwise you easily end up with “not knowing where the money went,” “not knowing which model is flapping,” and “not knowing whether degradation actually took effect.”

    It is recommended to log the following structured fields for each call:

    1. {
    2. "trace_id": "trace-123",
    3. "session_id": "session-456",
    4. "model_id": "model_a",
    5. "policy": "balanced",
    6. "degraded": true,
    7. "tokens_in": 1200,
    8. "tokens_out": 300,
    9. "cost": 0.0045,
    10. "latency_ms": 860,
    11. "retry_count": 1,
    12. "error_type": "timeout"
    13. }

    Key monitoring metrics include:

    • QPS, success rate, and error rate per model;
    • P50, P95, and P99 latency;
    • Input/output token consumption;
    • Cost per tenant and per business line;
    • Number of degradations and degradation success rate;
    • Number of rate-limit, timeout, and circuit-break events;
    • Routing-policy hit rate.

    Logs, metrics, and tracing can be implemented with general-purpose cloud capabilities. For example, in a common cloud environment, you can write call logs to object storage for offline analysis, use a monitoring and alerting service to set thresholds on error rate, latency, and cost, and retain traces to support cross-service troubleshooting.

    For cost governance, you cannot estimate by tokens alone. Record actual spend, and compute total cost factoring in retries, failed requests, streaming interruptions, and cache hits. It is recommended to set budget thresholds per tenant, business, and environment, and to alert or trigger degradation strategies when the budget is exceeded.

    One caveat: for synchronous dialogue pipelines, it is not advisable to force traffic through a message queue just to smooth out peaks, because this significantly raises P95 latency. Message queues are better suited to asynchronous tasks, offline analysis, log aggregation, or batch processing.

    9. Security, Compliance, and Risk Warnings: Data Boundaries Cannot Rely on Routing Defaults Alone

    Multi-model integration means data may flow to different backends. Before launch, data boundaries must be defined clearly:

    • Which data is allowed to leave the boundary;
    • Which fields must be masked;
    • Which tenants may only use private or compliant models;
    • Whether third-party models use inputs for training;
    • How long data is retained;
    • Whether cross-border transfer is involved;
    • Whether you meet the relevant compliance obligations for generative AI services, including security assessments and protection of minors.

    It is recommended to add a “data classification + allowlist” check at the routing layer. For example, highly sensitive requests may only enter privately deployed models or compliant models that explicitly commit to not using data for training; only ordinary requests may enter commercial API models.

    At the same time, business teams should be warned about the following risks:

    • The same task may produce output-style and quality fluctuations across models;
    • Routing-parameter tuning must be regressed against an offline evaluation set, not judged by online intuition alone;
    • Third-party APIs carry risks of throttling, price increases, deprecation, and parameter changes;
    • Backup models may change output format, so downstream needs schema validation;
    • Mid-stream failures in streaming pipelines need unified handling to avoid handing the frontend an incomplete result.

    10. Alternatives: Do Small Teams Have to Build Their Own Routing Layer?

    Not necessarily.

    If a team is small, integrates only a few models, and has no complex canary-release or cost-governance needs, it can use a cloud provider’s model gateway or an open-source model gateway directly. For example, tools like LiteLLM can provide multi-model proxying, a unified interface, and basic routing and rate-limiting capabilities.

    When is it appropriate to build your own routing layer?

    • When you need complex policies across tenant, cost, latency, and quality;
    • When you need deep integration with internal authentication, auditing, and data classification;
    • When you need fine-grained control over model health, circuit breaking, and degradation;
    • When you need to connect model capabilities to your enterprise’s own agent platform;
    • When you need unified metering, budgets, quotas, and multi-environment release processes.

    In other words, an open-source gateway is good for getting started quickly, while a self-built routing layer suits platform-level governance.

    11. Common Mistakes in Multi-Model Integration

    1. Writing if model == A in business code: this creates tight coupling and makes adding models costly.
    2. Integrating models without timeouts and circuit breaking: once one model flaps, it affects the entire pipeline.
    3. Inconsistent scales in routing scores: for example, using health * 1000 to represent quality, which breaks the quality policy.
    4. Directly multiplying health, causing false degradation: a slightly lower health sends all models into the fallback chain; set a threshold instead of multiplying crudely.
    5. Swallowing all exceptions during degradation: 401 and parameter errors should not switch models, or failures get masked.
    6. Overwriting resp.model_id on the caller side: prefer the adapter’s returned value and only fall back on the caller when it is missing.
    7. Estimating cost by tokens alone: ignoring retries, failures, streaming interruptions, and cache differences distorts the budget.
    8. Having no offline evaluation set: routing changes rely on gut feeling, and post-launch quality fluctuations cannot be diagnosed.
    9. Truncating context without looking at the tokenizer: different models tokenize differently, so simple character-based truncation can break prompts.
    10. Not validating backup-model output format: after switching, downstream parsing fails and causes a secondary failure.
    11. Ignoring third-party data compliance: failing to check training use, retention period, cross-border transfer, and compliance obligations.
    12. Forcing a message queue into synchronous pipelines to smooth peaks: this raises latency and hurts the real-time experience of office scenarios.

    12. Implementation Checklist: A Minimal Solution You Can Ship on Day One

    • [ ] Complete ModelRequest, ModelResponse, and ModelAdapter.
      Acceptance: adding a model requires 0 lines of change in business code.

    • [ ] Complete ModelRegistry with fields for capability, context length, price, concurrency quota, latency, quality, and health.
      Acceptance: candidates can be filtered by task capability, budget, and latency SLO.

    • [ ] Complete ModelRouter.select and fallback_chain.
      Acceptance: after the primary model times out, it automatically switches to a backup model.

    • [ ] Complete exception classification: retryable vs. non-retryable.
      Acceptance: 401 is raised directly, while 429/5xx is retried and triggers a circuit break.

    • [ ] Complete structured logging and basic metrics.
      Acceptance: latency, error rate, tokens, and cost can be queried by model, tenant, and policy.

    • [ ] Complete the security allowlist.
      Acceptance: highly sensitive requests are never routed to disallowed models.

    • [ ] Establish a minimal offline evaluation set.
      Acceptance: after a routing-rule change, a quality, latency, and cost regression report is produced automatically.

    13. Conclusion

    Moving office agents from a single model to multi-model orchestration is fundamentally about lifting model capability out of concrete implementations and turning it into pluggable, routable, governable infrastructure. The unified abstraction layer solves extensibility; routing and degradation solve effectiveness and availability; context management solves behavioral consistency after switching models; quality and cost governance keep long-term operation stable; and security and compliance determine whether the platform can enter enterprise-grade production.

    Multi-model is not the goal—stably, controllably, and cost-effectively serving office scenarios is the goal. Mastering this set of integration and orchestration methods gives a team the ability to keep delivering a stable product experience at a controlled cost.