Multi-Model Workbench in Practice: Model Selection, Routing, Handoff, and Usage Reconciliation
As the number of large language models grows, the developer's question shifts from "is there a usable model" to "which model fits this task, how do I preserve context when switching, and what did each call cost?" All three require an engineering approach. Using a multi-model workbench as an example, this article walks through task-based model selection, routing with fallback, context handoff between models, and usage reconciliation, then closes with common mistakes to avoid. Only with all four steps built as inspectable configuration and logs can a team diagnose problems instead of guessing.
As the number of large language models grows, the developer’s question shifts from “is there a usable model” to “which model fits this task, how do I preserve context when switching, and what did each call cost?” All three require an engineering approach. This article uses a multi-model workbench to walk through task-based model selection, routing with fallback, context handoff, and usage reconciliation, then closes with common mistakes.
1. Choosing Models by Task Type
Selection starts with the task type. The table below outlines how to choose for common tasks—it answers “which category of model to use.”
| Task Type | Suitable Model Category | Key Constraints | Risks and Notes | Fallback Strategy |
|---|---|---|---|---|
| Long-document analysis (reports, contracts) | Long-context models with strong analytical ability | Input plus reserved output must stay below the context limit; reserve 10–20% headroom | Very long inputs increase latency and usage; extract key points per segment first, then summarize. Redact sensitive data beforehand | Switch to a long-context model in the same family; if still over the limit, process in segments |
| Summarization, format conversion, simple Q&A | Lightweight models | Sensitive to response speed and per-call cost | Accuracy on complex reasoning may drop; validate with sampling | Escalate to a mid-tier model when structural validation fails |
| Multi-step planning, complex code | Flagship models | High output quality required; longer latency acceptable | High per-call usage; set a max output length and pilot on a small scale first | Downgrade to a mid-tier model on timeout or over-budget, and add human review |
| Batch classification, tagging | Lightweight or small models | Throughput and unit price first | Output format must be fixed, or post-processing costs rise | Retry once on parse failure; send to a manual queue if it still fails |
Specific model names, context limits, and unit prices change as platforms update. Before configuring, always check the platform’s current model list and record the verification date.
A selection table only gives you a category. To pick a concrete model, run a sampling evaluation: prepare 20–50 real samples per task type, compare at least two candidate models, and record three metrics:
- Accuracy: the share of outputs judged correct by humans or rules.
- Structural pass rate: the share of outputs passing schema validation.
- Per-call cost: the average cost per call computed with the formula in Section 4, noting the measurement date and model version.
Write the evaluation results into the configuration file rather than relying on impressions.
2. Writing Routing with Fallback
The routing layer maps tasks to models and switches by priority on failure. In the configuration example below, model identifiers and prices are placeholders; obtain actual values from the platform’s model list.
route: long_doc_analysismax_output_tokens: 2000 # Expected output cap; how to set this is explained belowbudget_per_call: <per-call budget cap> # Same currency as the invoicefallback_window_s: 60 # Counting window: rate-limit or server errors from the same model within 60 secondsmodels:- name: <long-context model A>model_version: <version returned by the platform>context_limit: <context limit in tokens>price:input_per_m: <input price per million tokens>output_per_m: <output price per million tokens>priority: 1timeout_s: 120max_retries: 1- name: <long-context model B>model_version: <version returned by the platform>context_limit: <context limit in tokens>price:input_per_m: <input price per million tokens>output_per_m: <output price per million tokens>priority: 2timeout_s: 180max_retries: 1fallback_triggers:- timeout- rate_limited_twice- server_error_twice- schema_validation_failed
Several parameters need explanation:
max_output_tokens: 2000is not a universal value. It should come from sample statistics: take the 95th percentile of output tokens and add roughly 20% headroom. Also require that “estimated input tokens plus max_output_tokens” stay within 85% of the context limit, consistent with the headroom rule in the selection table.rate_limited_twicemeans the same model returns two consecutive rate-limit errors within thefallback_window_swindow. The counter resets after the window and also on any successful call.server_error_twicefollows the same counting rule.max_retriesapplies only to rate limits and server errors. On timeout, switch directly to the next model, since a timeout usually means the input is too large or the model is busy—waiting another round on the same model rarely helps. On schema validation failure, retry once with the same model after appending format constraints; switch only if it fails again.
Here is the routing execution pseudocode. The implementations of log_event, log_usage, and llm_call depend on the SDK you use; only the flow logic is shown.
import timeimport uuidclass BudgetExceeded(Exception):passclass AllRoutesFailed(Exception):passclass WindowCounter:"""Counts events within a time window."""def __init__(self, window_s):self.window_s = window_sself.events = []def hit(self, now):self.events = [t for t in self.events if now - t < self.window_s]self.events.append(now)return len(self.events)def reset(self):self.events = []def estimate_cost(input_tokens, output_tokens, price):"""Estimates cost from unit prices. Output is billed at max_output_tokens, i.e., the worst case."""return (input_tokens * price["input_per_m"]+ output_tokens * price["output_per_m"]) / 1_000_000def actual_cost(usage, price):"""Bills based on actual usage returned by the platform. Cached input, if priced separately, should be computed separately."""return (usage.input_tokens * price["input_per_m"]+ usage.output_tokens * price["output_per_m"]) / 1_000_000def fits_context(task, route, model):return task.input_tokens + route.max_output_tokens <= model.context_limit * 0.85def run_with_fallback(task, route, validate):for model in sorted(route.models, key=lambda m: m.priority):if not fits_context(task, route, model):log_event(task.id, route.name, model.name, status="skipped_context")continuelimit_counter = WindowCounter(route.fallback_window_s)server_counter = WindowCounter(route.fallback_window_s)prompt = task.payloadschema_retried = Falseattempt = 0while attempt <= model.max_retries:attempt += 1# Pre-call budget check: if the estimate exceeds the budget, skip this model and fall backest = estimate_cost(task.input_tokens, route.max_output_tokens, model.price)if est > route.budget_per_call:log_event(task.id, route.name, model.name,status="blocked_budget", estimate=est)breakcall_id = str(uuid.uuid4())started = time.time()try:resp = llm_call(model=model.name,prompt=prompt,max_tokens=route.max_output_tokens,timeout=model.timeout_s,)except TimeoutError:log_event(call_id, route.name, model.name, status="timeout", attempt=attempt)break # On timeout, switch directly to the next modelexcept RateLimitError:if limit_counter.hit(started) >= 2:log_event(call_id, route.name, model.name, status="rate_limited_twice")breaktime.sleep(2 ** attempt) # Retry after exponential backoffcontinueexcept ServerError:if server_counter.hit(started) >= 2:log_event(call_id, route.name, model.name, status="server_error_twice")breaktime.sleep(2 ** attempt)continue# Only a successful call reaches this pointlog_usage(call_id, task.id, route.name, model.name, resp.model,started, resp.usage, status="ok", attempt=attempt)cost = actual_cost(resp.usage, model.price)if cost > route.budget_per_call:# The call has already happened; it can only be logged and alerted on, not reversedlog_event(call_id, route.name, model.name,status="over_budget", cost=cost)if resp.model != model.model_version:log_event(call_id, route.name, model.name,status="model_version_mismatch", returned=resp.model)if validate(resp.text, task.schema):return resplog_event(call_id, route.name, model.name, status="schema_validation_failed")if schema_retried:break # Still failing after the format-constraint retry; switch to the next modelschema_retried = Trueprompt = task.payload + "\n\n" + task.format_hint # Retry once with format constraints appended# All models failed or exceeded budget: enter the manual queue, never silently drop the taskenqueue_manual(task.id, reason="all_routes_failed")raise AllRoutesFailed(f"route={route.name}, task={task.id}")
Three points to note in this logic. First, the budget check happens before the call: it can block over-budget requests but cannot reverse calls that already happened. Second, models skipped for budget reasons push the flow toward cheaper subsequent models, so order routes by capability from high to low and cost from high to low—or reorder them according to business needs. Third, tasks that fail everywhere enter the manual queue with the reason preserved for later review.
3. Context Handoff
After switching models, the new model cannot see the previous model’s session state. The workbench must generate a handoff package that explicitly carries over the information the task needs. The handoff package should be structured JSON, not a raw copy of the entire conversation.
At minimum, the handoff package should contain:
task_id: the task’s unique ID, consistent across all calls for that task.handoff_version: the handoff format version, e.g.,1.0, for backward compatibility when upgrading.route: the current route name.from_modelandto_model: the model names andmodel_versionbefore and after the handoff.created_at: generation time as a UTC timestamp.messages: the most recent turns of the conversation verbatim, includingroleandcontent, already redacted.summary: a compressed summary of earlier conversation, with a length cap.schema: the name and version of the output structure, e.g.,report_v2.model_state: parameters that affect output, such as temperature, system prompt version, and tool-call state.token_estimate: the handoff package’s estimated input tokens, used to check against the new model’s context limit.redaction: whether redaction was applied and which redaction rule version was used.
An example follows; all values are placeholders.
{"task_id": "<task ID>","handoff_version": "1.0","route": "long_doc_analysis","from_model": {"name": "<model A>", "model_version": "<version>"},"to_model": {"name": "<model B>", "model_version": "<version>"},"created_at": "<UTC timestamp>","messages": [{"role": "user", "content": "<most recent redacted input>"}],"summary": "<compressed summary of earlier content, within the agreed length>","schema": {"name": "report", "version": "v2"},"model_state": {"temperature": "<value>", "system_prompt_version": "<version>"},"token_estimate": "<estimated value>","redaction": {"applied": true, "rule_version": "<version>"}}
Handling rules during handoff:
- If the new model’s context limit is smaller, compress
summaryfirst, then dropmessagesstarting from the earliest. - Task instructions and
schemamust never be deleted, or the output format becomes uncontrolled. - Before sending, validate the handoff package’s JSON structure and check that
token_estimateis within the limit. - Logs should record only
task_idand a hash of the handoff package, never the rawmessages.
Redaction must be completed before the handoff. Replace fields such as names, phone numbers, ID numbers, and monetary amounts with placeholders like [PERSON_1]. Store the mapping between placeholders and original values separately—never in logs, and never sent to the model with the handoff package.
4. Usage Reconciliation
Each call’s cost is computed as:
Per-call cost = input tokens × input price ÷ 1,000,000 + output tokens × output price ÷ 1,000,000
If the platform prices cached input separately, split it out as a cached_input_tokens item and multiply by its own price before summing.
Task cost equals the sum of all calls for that task, including timed-out, rate-limited, and schema-failed calls. Those calls still consumed tokens and the platform usually bills them too; don’t count only the successful one.
Reconciliation variance is calculated as:
Reconciliation variance = |sum of logged costs for a given day, model, and version − invoice amount| ÷ invoice amount
Teams can set their own tolerance, say 1%, and investigate when it’s exceeded. This number is a team choice, not a platform standard.
Reconciliation steps:
- Fix a batch of samples, say 20, run them fully through the route, and record each call’s
call_id,model_version, andusage. - Compare the model version returned in responses against the configuration; log an alert on mismatch.
- Compute the cost per call using the formula and compare it against the
costfield in the logs. - Aggregate by date and model, reconcile against the invoice, and judge pass/fail against the tolerance.
- Count timeouts, rate limits, and fallbacks, and compute the fallback rate: tasks that fell back to the next model divided by total tasks.
- Record the verification date, the price source, and the version of the model list.
If a timed-out call returns no usage, record it with an estimated value and mark that log entry estimated=true so it can be handled separately during reconciliation.
Each log entry should include: call_id, task_id, route, model, model_version, attempt, started_at, usage (input, output, cached input), cost, and status.
5. Common Mistakes
- Looking only at unit price and ignoring context limits. Cheaper models may have smaller contexts, so long documents get truncated or fail outright.
- Ignoring output headroom. When input is near the limit, output gets truncated or the request fails outright.
- Not recording model versions. When bills or quality change, you can’t trace which version caused it.
- Counting only successful calls. Timeouts and retries consume tokens too; omitting them makes the reconciliation variance grow steadily.
- Pricing cached input as regular input, inflating cost estimates so they don’t match the invoice.
- Writing raw text into logs. Sensitive content like contracts or medical records entering logs is a second data leak.
- Not validating output structure after fallback. The problem only surfaces when downstream parsing fails, making it expensive to debug.
Build model selection, routing, handoff, and reconciliation into inspectable configuration and logs, and your team can pinpoint the cause of problems instead of guessing.
