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.

    1. route: long_doc_analysis
    2. max_output_tokens: 2000 # Expected output cap; how to set this is explained below
    3. budget_per_call: <per-call budget cap> # Same currency as the invoice
    4. fallback_window_s: 60 # Counting window: rate-limit or server errors from the same model within 60 seconds
    5. models:
    6. - name: <long-context model A>
    7. model_version: <version returned by the platform>
    8. context_limit: <context limit in tokens>
    9. price:
    10. input_per_m: <input price per million tokens>
    11. output_per_m: <output price per million tokens>
    12. priority: 1
    13. timeout_s: 120
    14. max_retries: 1
    15. - name: <long-context model B>
    16. model_version: <version returned by the platform>
    17. context_limit: <context limit in tokens>
    18. price:
    19. input_per_m: <input price per million tokens>
    20. output_per_m: <output price per million tokens>
    21. priority: 2
    22. timeout_s: 180
    23. max_retries: 1
    24. fallback_triggers:
    25. - timeout
    26. - rate_limited_twice
    27. - server_error_twice
    28. - schema_validation_failed

    Several parameters need explanation:

    • max_output_tokens: 2000 is 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_twice means the same model returns two consecutive rate-limit errors within the fallback_window_s window. The counter resets after the window and also on any successful call. server_error_twice follows the same counting rule.
    • max_retries applies 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.

    1. import time
    2. import uuid
    3. class BudgetExceeded(Exception):
    4. pass
    5. class AllRoutesFailed(Exception):
    6. pass
    7. class WindowCounter:
    8. """Counts events within a time window."""
    9. def __init__(self, window_s):
    10. self.window_s = window_s
    11. self.events = []
    12. def hit(self, now):
    13. self.events = [t for t in self.events if now - t < self.window_s]
    14. self.events.append(now)
    15. return len(self.events)
    16. def reset(self):
    17. self.events = []
    18. def estimate_cost(input_tokens, output_tokens, price):
    19. """Estimates cost from unit prices. Output is billed at max_output_tokens, i.e., the worst case."""
    20. return (input_tokens * price["input_per_m"]
    21. + output_tokens * price["output_per_m"]) / 1_000_000
    22. def actual_cost(usage, price):
    23. """Bills based on actual usage returned by the platform. Cached input, if priced separately, should be computed separately."""
    24. return (usage.input_tokens * price["input_per_m"]
    25. + usage.output_tokens * price["output_per_m"]) / 1_000_000
    26. def fits_context(task, route, model):
    27. return task.input_tokens + route.max_output_tokens <= model.context_limit * 0.85
    28. def run_with_fallback(task, route, validate):
    29. for model in sorted(route.models, key=lambda m: m.priority):
    30. if not fits_context(task, route, model):
    31. log_event(task.id, route.name, model.name, status="skipped_context")
    32. continue
    33. limit_counter = WindowCounter(route.fallback_window_s)
    34. server_counter = WindowCounter(route.fallback_window_s)
    35. prompt = task.payload
    36. schema_retried = False
    37. attempt = 0
    38. while attempt <= model.max_retries:
    39. attempt += 1
    40. # Pre-call budget check: if the estimate exceeds the budget, skip this model and fall back
    41. est = estimate_cost(task.input_tokens, route.max_output_tokens, model.price)
    42. if est > route.budget_per_call:
    43. log_event(task.id, route.name, model.name,
    44. status="blocked_budget", estimate=est)
    45. break
    46. call_id = str(uuid.uuid4())
    47. started = time.time()
    48. try:
    49. resp = llm_call(
    50. model=model.name,
    51. prompt=prompt,
    52. max_tokens=route.max_output_tokens,
    53. timeout=model.timeout_s,
    54. )
    55. except TimeoutError:
    56. log_event(call_id, route.name, model.name, status="timeout", attempt=attempt)
    57. break # On timeout, switch directly to the next model
    58. except RateLimitError:
    59. if limit_counter.hit(started) >= 2:
    60. log_event(call_id, route.name, model.name, status="rate_limited_twice")
    61. break
    62. time.sleep(2 ** attempt) # Retry after exponential backoff
    63. continue
    64. except ServerError:
    65. if server_counter.hit(started) >= 2:
    66. log_event(call_id, route.name, model.name, status="server_error_twice")
    67. break
    68. time.sleep(2 ** attempt)
    69. continue
    70. # Only a successful call reaches this point
    71. log_usage(call_id, task.id, route.name, model.name, resp.model,
    72. started, resp.usage, status="ok", attempt=attempt)
    73. cost = actual_cost(resp.usage, model.price)
    74. if cost > route.budget_per_call:
    75. # The call has already happened; it can only be logged and alerted on, not reversed
    76. log_event(call_id, route.name, model.name,
    77. status="over_budget", cost=cost)
    78. if resp.model != model.model_version:
    79. log_event(call_id, route.name, model.name,
    80. status="model_version_mismatch", returned=resp.model)
    81. if validate(resp.text, task.schema):
    82. return resp
    83. log_event(call_id, route.name, model.name, status="schema_validation_failed")
    84. if schema_retried:
    85. break # Still failing after the format-constraint retry; switch to the next model
    86. schema_retried = True
    87. prompt = task.payload + "\n\n" + task.format_hint # Retry once with format constraints appended
    88. # All models failed or exceeded budget: enter the manual queue, never silently drop the task
    89. enqueue_manual(task.id, reason="all_routes_failed")
    90. 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_model and to_model: the model names and model_version before and after the handoff.
    • created_at: generation time as a UTC timestamp.
    • messages: the most recent turns of the conversation verbatim, including role and content, 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.

    1. {
    2. "task_id": "<task ID>",
    3. "handoff_version": "1.0",
    4. "route": "long_doc_analysis",
    5. "from_model": {"name": "<model A>", "model_version": "<version>"},
    6. "to_model": {"name": "<model B>", "model_version": "<version>"},
    7. "created_at": "<UTC timestamp>",
    8. "messages": [{"role": "user", "content": "<most recent redacted input>"}],
    9. "summary": "<compressed summary of earlier content, within the agreed length>",
    10. "schema": {"name": "report", "version": "v2"},
    11. "model_state": {"temperature": "<value>", "system_prompt_version": "<version>"},
    12. "token_estimate": "<estimated value>",
    13. "redaction": {"applied": true, "rule_version": "<version>"}
    14. }

    Handling rules during handoff:

    • If the new model’s context limit is smaller, compress summary first, then drop messages starting from the earliest.
    • Task instructions and schema must never be deleted, or the output format becomes uncontrolled.
    • Before sending, validate the handoff package’s JSON structure and check that token_estimate is within the limit.
    • Logs should record only task_id and a hash of the handoff package, never the raw messages.

    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:

    1. Fix a batch of samples, say 20, run them fully through the route, and record each call’s call_id, model_version, and usage.
    2. Compare the model version returned in responses against the configuration; log an alert on mismatch.
    3. Compute the cost per call using the formula and compare it against the cost field in the logs.
    4. Aggregate by date and model, reconcile against the invoice, and judge pass/fail against the tolerance.
    5. Count timeouts, rate limits, and fallbacks, and compute the fallback rate: tasks that fell back to the next model divided by total tasks.
    6. 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.