Multi-Model Architecture for AI Agent Workspaces: Context, Routing, and Cost Control

    This article presents a vendor-neutral architecture for connecting multiple models to an AI agent workspace. It explains how to preserve context continuity when switching models mid-conversation, how to route tasks such as visual understanding, data analysis and visualization, and code generation to the most suitable model, and how to unify quotas and metering to keep costs explainable. A four-layer design and sample code are included.

    When an AI coding and office agent evolves from a single model to multiple coexisting models, the engineering focus shifts from “getting one API to work” to “governing a set of capabilities.” This article takes a neutral view of the general architecture for multi-model agent workspaces: how to keep context continuous within the same conversation, how to dispatch visual understanding, data analysis and visualization, and code generation based on task characteristics, how to control cost with a unified quota and metering system, and a practical layered design with sample code.

    1. Background: From Picking One Model to Scheduling Many

    Early agent products were typically bound to a single model, and their capability boundaries were defined by that model. As models evolved differently in areas such as visual understanding, code generation, and long-context reasoning, no single model could cover all task types at once. The industry has therefore converged on a “workspace + multiple models” pattern: users switch the underlying model within the same session as tasks require, without repeating the background.

    This introduces three new engineering problems:

    1. Context consistency: after switching models, message history, tool call results, and intermediate artifacts must not be lost or misplaced.
    2. Capability routing: different tasks (reading images, building pages, analyzing spreadsheets) should be dispatched to the most suitable model rather than all going to a default one.
    3. Cost and quota: once multiple models coexist, metering, quota deduction, and cost comparison must be unified; otherwise you cannot explain to users “why this run was cheaper.”

    2. Overall Architecture: Four Decoupled Layers

    Split the system into four layers that communicate through stable contracts, so model differences do not leak upward.

    • Adapter layer: hides differences between vendor APIs and normalizes everything into four abstractions: session, message, tool, and artifact.
    • Session and context layer: stores normalized history and handles trimming, summarization, and replay.
    • Routing and policy layer: selects models based on task type, modality, cost, latency, and quota.
    • Metering and governance layer: unifies quota, auditing, rate limiting, and observability.

    A vendor-neutral unified message structure:

    1. {
    2. "session_id": "s-8821",
    3. "turn": 7,
    4. "messages": [
    5. {"role": "user", "content": [{"type": "text", "text": "Turn this data into an interactive dashboard"}]},
    6. {"role": "assistant", "content": [{"type": "tool_call", "name": "run_query", "args": {"sql_ref": "q_31"}}]},
    7. {"role": "tool", "content": [{"type": "table", "rows_ref": "r_31"}]}
    8. ],
    9. "artifacts": [{"kind": "chart", "ref": "a_77"}],
    10. "routing_hint": {"modality": ["text","image"], "task": "data_viz"}
    11. }

    The key point: tool results enter the history as references rather than large inline blocks. This both controls context length and guarantees the history can be replayed after a model switch.

    3. Shared Context: Switching Models Without Losing the Thread

    Context continuity comes down to “normalization + replayability.”

    • Normalization: map message formats from different models into one unified structure, with roles, tool calls, and attachment references corresponding one-to-one.
    • Replayability: on any model switch, rebuild the prompt from the same normalized history; for overly long histories, use a “summarize + keep key fragments” strategy.
    • Externalized artifacts: charts, pages, and datasets are stored as independent artifacts, with only references and summaries left in the history, avoiding context bloat.

    Pseudocode:

    1. def build_prompt(session, target_model):
    2. history = normalize(session.messages) # unified structure
    3. if token_estimate(history) > target_model.ctx_budget * 0.7:
    4. history = summarize_then_keep(history, keep_refs=True)
    5. return template(history, artifacts=session.artifacts_index())

    In practice, record the “routing reason” and a “context version number” for each switch to make issues traceable.

    4. Capability Routing: Putting Vision and General Coding in the Right Place

    Routing does not need to be complex; start with rules and add data later:

    1. Modality detection: if the input contains images, screenshots, or scanned documents, prefer models with visual understanding.
    2. Task classification: tag data analysis and visualization, web and app building, long-form writing, and retrieval Q&A separately.
    3. Constraint filtering: context length, tool call support, concurrency quota, latency budget.
    4. Score and select: among remaining candidates, score by “quality prior × inverse cost × inverse latency.”
    1. def route(task, candidates):
    2. c = [m for m in candidates if satisfies(m, task.constraints)]
    3. if task.modality includes "image":
    4. c = prefer(c, key="vision")
    5. if task.kind in ("app_build", "refactor"):
    6. c = prefer(c, key="code")
    7. return max(c, key=lambda m: quality[m.id] / cost[m.id] / latency[m.id])

    Routing should be explainable and overridable. When a user manually specifies a model, the policy layer only validates constraints and does not override the user’s intent.

    5. Unified Quota and Cost Optimization

    Metering is what most easily gets out of control in a multi-model environment. Build a “unified quota pool + task-level billing” system:

    • Unified deduction: all model calls draw from the same subscription quota, so users do not need to understand each vendor’s billing differences.
    • Task-level aggregation: multiple calls, tool executions, and artifact generations within one task are merged into a single billing entry.
    • Cost comparison: record actual consumption of different models for equivalent tasks, providing evidence for “more savings” rather than verbal claims.
    • Budget guardrails: budget caps at three levels (session, user, task); on exceeding, downgrade to a lower-cost model or queue.
    1. budget:
    2. session_limit: 120000 # in unified quota units
    3. task_limit: 40000
    4. on_exceed: downgrade_then_queue

    6. Non-Functional Essentials: Permissions, Isolation, and Observability

    • Permissions and isolation: model call credentials are centrally managed and never exposed to the frontend; in multi-tenant setups, artifact storage is isolated by tenant prefix.
    • Observability: instrument routing decisions, token consumption, tool success rate, and switch counts; track abnormal fallback rates with monitoring and alerts.
    • Evaluation regression: maintain a fixed task set (including image understanding, spreadsheet analysis, and page generation) and run regression on every model or prompt change to prevent “quality drops after switching models.”
    • Failure fallback: on model timeout or rate limiting, retry and degrade automatically; write artifacts to object storage and return references afterward, so an interrupted session does not lose results.

    7. Implementation Checklist

    1. Define the unified message and artifact contracts first, then connect the first model.
    2. Make the context layer replayable before exposing the switch toggle.
    3. Start routing with rules, then statistics, and keep a manual override entry.
    4. Put metering and budgets in place first to avoid unexplainable costs after launch.
    5. Build a regression task set and dashboard to close the “change—evaluate—release” loop.

    Connecting multiple models is not stitching several APIs together; it is converging “capability differences” under unified contracts, keeping the upper-layer session stable, costs explainable, and capabilities extensible. Following the layering above, an agent workspace can deliver a consistent experience and controllable spend across mixed tasks such as visual understanding, data analysis and visualization, and app building.