Mid-Session Model Switching for Coding Agents
Coding agents often bind one high-capability model for an entire session, inflating cost and latency. This article explains capability tiers, step-level routing, context continuity, evaluation, and anti-patterns so model choice becomes a runtime scheduling decision rather than a one-time session setting.
1. The problem: running the strongest model for the whole session hides real cost
Early coding agents often pick the strongest available model at session start and keep it through intent understanding, code search, patch generation, test-and-fix, and summarization. Binding one model for the whole session is easy to implement, but it raises two costs at once.
The first is quota and spend. Early work is mostly intent, retrieval, and listing options. It does not need deep reasoning, yet it burns the most expensive tokens. The second is latency. Stronger models respond more slowly, and coding work is a long chain of tool calls, so per-turn delay compounds.
Public industry reports have described pairing a strong model with a lighter one and switching as the task progresses. Quality stayed roughly the same while token use fell by about a quarter and time to completion by about a fifth. The exact numbers matter less than the conclusion: model choice should be a step-level decision, not a session-level one.
2. Core idea: capability tiers plus step-level routing
Dynamic switching can be described along three independent dimensions.
Capability tiers. Rank models on reasoning depth, response speed, and unit cost. Two or three tiers are typical: a light tier for formatting, extraction, classification, and simple rewrite; a main tier for cross-file reasoning, defect localization, and complex refactoring; and, if needed, a deep tier for hard blockers. Tiers should follow an observed capability profile, not a model name.
Step-level routing. Before each step, the orchestrator (scheduler) picks a tier from the nature of that step, instead of deciding once at session start.
State continuity. On a switch, task context, intermediate conclusions, and tool-call state must pass to the new model without loss. That is the difference between a working system and a broken one.
Tiers give options, routing chooses, and state continuity keeps the choice from breaking the task.
3. When to switch: observable signals instead of hard-coded rules
Routing is easy to get wrong. A fixed pipeline such as “light for step one, main for step two” fails on real work. A more robust approach combines several signals.
- Task-phase signals: Intent clarification, context retrieval, and enumeration are low-depth. Root-cause analysis, cross-module refactoring, and concurrency-bug fixes are high-depth.
- Context-size signals: When context grows substantially, prefer a tier that is more stable on long context so a light model does not drift off instructions.
- Failure and retry signals: If the same tier fails validation twice in a row, escalate rather than retrying in place.
- Risk signals: Changes that touch permissions, payments, or data migration should force the deep tier and human confirmation.
- Remaining-budget signals: Near a quota threshold, step down so remaining quota is saved for steps that need deep reasoning.
A schematic routing decision (pseudocode; interface names are generic):
def pick_tier(step, ctx):if step.risk_level == "high":return "deep"if ctx.retry_count[step.tier] >= 2:return escalate(step.tier) # escalate on failureif ctx.token_budget_left < ctx.budget * 0.2:return "light" # step down on budgetif step.phase in ("clarify", "retrieve", "enumerate"):return "light"if ctx.context_tokens > 0.7 * ctx.window:return "main" # prefer stability on long contextreturn "main"
Routing must be logged and replayable. Every switch should write a structured record: step id, source tier, target tier, triggering signal, token delta, and validation result. Without that, later attribution is impossible.
4. Context consistency: why switches actually fail
Poor results after a switch are usually distorted context, not a wrong route. Four kinds of state need explicit handling.
- Dialogue and instruction state: System constraints, coding standards, and directory conventions must be fully re-injected on every switch. Do not assume the new model “remembers.”
- Intermediate artifacts: Generated patches and confirmed design decisions should pass as structured summaries, not raw long chat, to stay faithful and control tokens.
- Tool-call state: File handles, commands already run, and test results are external side effects. The orchestrator owns them; the model only sees result snapshots.
- Cache and prompt prefix: A switch changes the prompt prefix and can invalidate prefix cache. A stable prefix plus a variable tail, with the invariant part first, reduces duplicate billing.
A practical rule: make the orchestrator the single source of truth and treat the model as a stateless reasoner. Switching then becomes “rebuild the view,” not “migrate memory.”
5. Evaluation: quality alone hides the gain
To show the mechanism works, measure quality and efficiency together.
- Quality: task pass rate, first-review patch pass rate, regression-test failure rate, human rework rate.
- Efficiency: tokens per task, end-to-end latency, number of tier switches, escalate rate, and step-down rate.
- Stability: drop in instruction following after a switch, and extra questions caused by lost context.
A useful method is controlled replay on the same task set and random seed: a single strong-model baseline versus the dynamic policy. Check that quality stays within an acceptable band, then compare efficiency. If quality drops past a threshold, inspect context handoff and prompt re-injection before changing routing rules.
In deployment, the orchestrator often runs as a standalone service on a container platform. Switch logs and traces go to logging and object storage for offline analysis; quota and latency feed monitoring and alerts; long chains can be decoupled with a message queue. These are generic capabilities. Baidu AI Cloud primitives can be composed along the same lines.
6. Common anti-patterns
- Switching too often: Changing model on every tiny step can cost more in switch and re-injection than you save on inference. Set a minimum step granularity and a cooldown.
- Only stepping down: Skipping failure escalation leaves hard tasks failing on a cheap tier and can raise total cost.
- No stateless design: Leaving state in the model means a switch is amnesia.
- No fallback: If quality regresses, you cannot flip back to a single-model baseline; there is no gray release or fast kill switch.
- A single metric: Reporting only token savings ignores hidden human rework.
7. Summary
Switching models mid-task turns “pick a model” from a one-time architecture choice into a runtime scheduling problem. It works when three conditions hold: accurate capability tiers, observable routing signals, and context owned by the orchestrator. With all three, efficiency is a structural outcome; without any one of them, saved tokens come back as rework. A practical path is: establish a single-model baseline and a shared evaluation set, add two tiers and failure escalation, then add budget and risk signals, using controlled replay as the gate for each rollout.
