Multi-Model Orchestration: Routing Tasks to Models While Preserving Context
This article explains how to route tasks across multiple LLMs by defining task layers, choosing rule-based, automatic, or hybrid routing, preserving context through a structured state object, and tracking standardized costs. It also outlines orchestration responsibilities, a simplified Python example, and a deployment checklist.
1. Background: A Single Model Rarely Covers Every Task
When enterprises and individual developers use large language models, they quickly encounter the same problem: different tasks have very different requirements for model capability, response speed, and cost. Retrieval, organizing long documents, writing code, and simple classification may either cost too much or fall short in some stages when all are run on the same model. A common past approach was to let users manually choose models, but this requires users to understand each model’s characteristics and make a decision before every task, which is a heavy burden.
The idea behind multi-model collaboration is to turn “model selection” from a manual decision into a configurable step inside the system. The system selects an appropriate model based on task characteristics and switches models as needed during task execution. From an engineering perspective, this approach needs to solve three types of problems: how to allocate tasks, how to ensure context continuity after switching, and how to make costs visible.
2. Task Layering: Define Tasks Before Choosing Models
Routing depends on classifying tasks. In practice, tasks can be divided along the following dimensions:
- Cognitive complexity: whether multi-step reasoning and integrated judgment are required.
- Information volume: whether the input is long and whether large amounts of material need to be processed.
- Latency requirements: whether a fast response is needed.
- Cost sensitivity: whether a rougher result is acceptable, or whether the task is suitable for batch processing.
- Output form: text, structured data, or code.
After layering, each task category corresponds to a set of candidate models. For example, long-document tasks that require detailed analysis can prioritize models with stronger long-context capabilities; batch field extraction tasks can use low-cost, fast models; and tasks that require strong synthesis and cross-step planning can be assigned to the most capable models. The layering table should be maintained by the team based on its own evaluation results, not set by impression.
3. Routing Strategies: Rules, Automatic, and Hybrid
There are three common routing strategies.
- Rule-based routing: developers explicitly configure mappings between task types and models. The advantage is predictable behavior and easy auditing; the disadvantage is that new task types require manual rule updates.
- Automatic routing: a classifier or small model determines the task type from the input content and then selects a model. The advantage is broad coverage; the disadvantage is that classification errors directly affect results, so classification accuracy must be continuously evaluated.
- Hybrid routing: rules first handle known, high-frequency tasks, and unmatched requests are passed to automatic classification. Most production systems use this approach to balance controllability and flexibility.
Whichever approach is used, a fallback model should be configured. When the preferred model times out, is rate-limited, or returns an exception, the system automatically switches to the backup model and records the reason for the switch for later troubleshooting.
4. Context Handoff: Making Intermediate Results Available Across Models
The most error-prone part of multi-model collaboration is context transfer. If every model switch only resends the original question, then conclusions already reached, intermediate tables, and verified facts from previous stages are lost, and different models effectively repeat the same work.
The solution is to extract task state from the model conversation and store it in a structured state object. The state object usually contains the following:
- Task goal: the final result the user wants, which remains unchanged throughout the workflow.
- Completed steps: the input, output, and model used for each step.
- Intermediate artifacts: summaries, retrieval results, structured data, and so on.
- To-do items: unfinished subtasks and their suggested models.
- Constraints: format requirements, word limits, prohibited items, and so on.
For each model call, the orchestration layer assembles the prompt from the state object and passes only the information required for the current step. This has two benefits. First, context length remains controllable, avoiding sending all history to the model. Second, when switching models, the new model receives structured intermediate results rather than natural-language history that must be inferred again.
Intermediate artifacts should be validated before handoff. For example, a step that requires JSON output should have field completeness validated before the next step begins; a summary that requires cited sources should have its citations checked. Otherwise, errors will be amplified step by step along the chain.
5. Cost Transparency: Unified Metering and Quota Accounting
In a multi-model environment, cost is more complex than with a single model. Different models may have different unit prices, billing units, and quota rules. If only the number of calls is counted, it is difficult to determine how many resources a task actually consumed.
A better approach is to establish a unified cost metric. The consumption of each model can be converted into the same unit of measurement, for example by multiplying input and output token counts by that model’s weight coefficient to obtain a standardized cost. The system records the standardized cost of each step after it completes and aggregates it at the end of the task. In this way, both users and administrators can see which step of a task costs the most, and then decide whether to adjust the routing strategy.
Weight coefficients should be based on the service provider’s official billing documentation and updated regularly. In implementation, it is recommended to place the coefficients in configuration files rather than hard-coding them in code.
6. Responsibilities of the Orchestration Layer
Multi-model collaboration depends on an orchestration layer, which usually handles the following responsibilities:
- Task decomposition: splitting user requests into executable subtasks.
- Routing decisions: selecting models for each subtask and handling timeouts and degradation.
- State management: maintaining task state and ensuring context continuity across models.
- Tool invocation: uniformly managing external capabilities such as retrieval, file reading and writing, and code execution.
- Execution control: setting maximum steps, timeouts, and retry policies to prevent tasks from looping indefinitely.
- Observability and auditing: recording the model, latency, cost, and result of each step.
The quality of the orchestration layer often determines the overall outcome. With the same model combination, different orchestration designs can produce large differences in result stability and cost. Therefore, multi-model collaboration is closer to engineering work than to simply comparing model parameters.
7. Example Code
The following code shows a simplified framework for routing and state passing. The code is only intended to illustrate the approach and omits error handling and real model invocation.
from dataclasses import dataclass, fieldfrom typing import Callable, Dict, List@dataclassclass TaskState:goal: strsteps: List[dict] = field(default_factory=list)artifacts: Dict[str, str] = field(default_factory=dict)cost: float = 0.0@dataclassclass ModelSpec:name: strunit_cost: float # Standardized cost coefficient, based on the provider's billing documentationcall: Callable[[str], str]RULES = {"analysis": "long_context_model","extract": "low_cost_model","synthesis": "strong_model",}def classify(subtask: str) -> str:# In a real system, this can be replaced by rules or a small-model classifierif "抽取" in subtask:return "extract"if "综合" in subtask:return "synthesis"return "analysis"def run_step(state: TaskState, subtask: str,models: Dict[str, ModelSpec], fallback: str) -> str:kind = classify(subtask)spec = models.get(RULES[kind]) or models[fallback]prompt = build_prompt(state, subtask)try:output = spec.call(prompt)except TimeoutError:spec = models[fallback]output = spec.call(prompt)state.steps.append({"subtask": subtask, "model": spec.name, "output": output})state.cost += spec.unit_cost * estimate_tokens(prompt + output)return outputdef build_prompt(state: TaskState, subtask: str) -> str:# Inject only the intermediate artifacts needed for the current step to control context lengthcontext = "\n".join(f"- {k}: {v}" for k, v in state.artifacts.items())return f"Goal: {state.goal}\nExisting results:\n{context}\nCurrent subtask: {subtask}"def estimate_tokens(text: str) -> int:return max(1, len(text) // 2) # Rough estimate; in practice, use the tokenizer for the corresponding model
This code reflects three points. First, routing rules are decoupled from models, so replacing a model only requires changing the mapping table. Second, the state object records the model and output of each step, so intermediate results remain available after a model switch. Third, cost is accumulated at each step, making later accounting easier.
8. Deployment Checklist
- Evaluate first: prepare a fixed set of examples for each task category, compare candidate models on quality, speed, and cost, and then determine the mapping.
- Set a fallback path: every route should have a backup model, and switch events should be recorded.
- Limit context: content passed to models should be trimmed by step to avoid unlimited growth of history.
- Validate intermediate results: structured outputs need format and field validation; on failure, retry or fall back.
