How to Make a Coding Agent Switch LLM Tiers by Task: Matching Model Capability to Task Difficulty
This article explains how to let a coding agent switch between large-model capability tiers on a per-task basis instead of hardcoding a single model. It introduces a four-layer architecture that pulls model selection out of business logic, defines a four-tier model (lite, standard, flagship, extreme) with a recommended default starting point, and shows decision rules driven by task difficulty rather than how clear the spec looks. It covers automatic escalation on repeated failures, the reasoning-effort parameter as a finer cost lever than switching tiers, the benefits and costs of sub-agents, and engineering guardrails such as budgets, caching, observability, and security. It closes with a data-driven evaluation loop, a list of common pitfalls, and a practical implementation checklist, all aimed at spending every unit of inference budget on tasks that genuinely need it.
Background: A Single Model Forces a Cost–Capability Trade-off
In the engineering practice behind AI coding assistants, one pattern keeps recurring. A team picks a model, hardcodes it into the configuration, and as usage expands, complaints split into two camps. One camp says the cost per call is absurdly high; the other says the model simply cannot handle complex refactors or stubborn defects. Both camps are right, because model capability and cost do not scale linearly, while the difficulty distribution of real tasks is long-tailed and highly uneven.
Most model services expose several capability tiers, from small to large. The smallest tier is cheap and low-latency, suited to structured, enumerable simple work. The middle tiers cover most day-to-day engineering tasks. The largest tier only pulls ahead on extreme problems, but its per-token cost can be several times that of the middle tier. Using only one tier forces a choice between “overpaying for simple tasks” and “lacking capability for complex ones.”
So the real problem is not “which model to choose.” It is turning model selection from a code constant into a decision capability that is configurable, measurable, and reversible. The goals are threefold: route tasks of different difficulty to the appropriate tier; make cost grow roughly linearly with difficulty rather than being averaged across everything; and let the system upgrade or downgrade automatically when the default tier fails, instead of letting the task fail outright.
Architecture: Extract “Model Selection” into Its Own Layer
A coding agent that switches models freely can usually be split into four layers:
- Adapter layer: A unified interface hides protocol differences across model services and declares capabilities explicitly as metadata, rather than scattering if-else branches through business code.
- Decision layer: Takes task features as input and outputs an execution plan of “tier + reasoning effort + budget cap.”
- Execution layer: The main agent handles the primary line of work, while sub-agents take on auxiliary work like retrieval, review, testing, and batch conversion.
- Governance layer: Budgets and circuit breakers, audit logs, offline evaluation, and versioned rollouts.
The key to the adapter layer is capability declaration, not just wrapping an HTTP client:
from dataclasses import dataclassfrom typing import Protocol, Sequence@dataclass(frozen=True)class Caps:context_window: int # available context lengthmax_effort: str # highest supported reasoning-effort levelsupports_tools: bool # tool/function calling supportsupports_stream: bool # streaming output supportsupports_batch: bool # batch async invocation supportclass ModelAdapter(Protocol):name: strcaps: Capsdef chat(self, req: ChatRequest) -> ChatResponse: ...
The policy can live entirely in configuration, so tiers change without touching code:
tiers:lite: # lite tier: classification, extraction, routing, batch jobseffort_levels: [low, medium]max_retries: 1standard: # standard tier: everyday changes with clear boundarieseffort_levels: [low, medium, high]flagship: # flagship tier: default starting point, covers most coding and knowledge workeffort_levels: [low, medium, high, extreme]is_default: trueextreme: # extreme tier: very hard problems, long unattended runseffort_levels: [low, medium, high, extreme]requires_budget_approval: true # high-cost tier requires budget approval
The Four Tiers and the Default Starting Point
| Tier | Typical role | Suitable tasks | Relative cost | Latency |
|---|---|---|---|---|
| Lite | High volume, low unit price | Intent classification, routing decisions, field extraction, format conversion, batch summarization | Lowest | Lowest |
| Standard | Everyday workhorse | Fixing defects with a clear location, implementing a single feature to spec, writing unit tests, code comments and docs | Low | Low |
| Flagship | Default starting point | Cross-file changes, architecture review, complex debugging, most coding and knowledge work | Medium | Medium |
| Extreme | High-difficulty ceiling | Very hard technical problems, large-scale migrations, performance bottleneck diagnosis, long unattended tasks | High | Higher |
Default recommendation: start from the flagship tier with medium reasoning effort. The reasoning is straightforward: the flagship tier is usually the official recommended starting point for “most coding and knowledge work,” its input/output unit price is generally about half that of the largest tier, and it offers broad coverage with a low rework rate. Placing the default here lets more than 70% of requests skip complex routing. The remaining tasks then adjust up or down by difficulty.
Downgrades come in two clear categories:
- Everyday work with clear boundaries drops to the standard tier. Note that “clear boundaries” means the requirements are enumerable and the verification method is deterministic, not that the task “looks simple.”
- Structured, high-volume, low per-item value tasks drop to the lite tier. Their total volume is large, so unit-price differences get amplified into significant differences; they are also well suited to parallel handling by sub-agents.
Typical upgrade scenarios:
- The hardest technical problems in coding, finance, or scientific computing;
- Tasks that keep failing under the flagship tier even at maximum reasoning effort;
- Long-chain tasks that run unattended for extended periods, where the cost of a single rework is very high and a stronger tier that passes on the first try is more economical;
- Highly irreversible operations (bulk data migration, large-scale delete-style refactoring), where the cost of a wrong decision far outweighs the inference cost.
Decision Rules: Difficulty First, Not “Is the Spec Clear”
The most common mistake is to see a clearly written requirements document, judge the task as simple, and drop it to a low tier. But tasks like migration, performance optimization, and concurrency defects are often precisely the ones with clear specs yet very high difficulty—the more precisely the requirement is described, the more it signals tight constraints, hard boundaries, and costly verification.
The practical approach looks at two kinds of signals at once:
Subjective semantic signals (a lite-tier model runs a classification pass first): the task belongs to a high-complexity domain such as refactoring, performance optimization, migration, security fixes, or cross-language porting; it involves external dependencies with high uncertainty; the requirement itself is ambiguous.
Objective, measurable signals (collected by the toolchain, independent of model judgment):
- Expected number of files changed and cross-module dependencies;
- The execution cost of testing and verification (build time, whether it depends on the environment);
- Whether it runs for a long time or involves irreversible operations;
- The historical rework count and manual-intervention rate for similar tasks.
def pick_plan(task: Task) -> Plan:# 1) high-risk + high-complexity domain: go straight to extreme tierif task.domain in {"large_refactor", "perf_opt", "migration", "security"} \and task.risk == "high":return Plan(tier="extreme", effort="high")# 2) objective complexity scoringscore = int(task.files_touched >= 20) + int(task.cross_module) \+ int(task.verify_costly) + int(task.long_running) \+ int(task.history_rework >= 2)if score >= 3:return Plan(tier="extreme", effort="high")if score == 2:return Plan(tier="flagship", effort="high")# 3) large batch, fixed output structure, low per-item valueif task.batch_size > 500 and task.output_schema:return Plan(tier="lite", effort="low")# 4) complete spec, low risk, simple verificationif task.spec_complete and task.risk == "low" and not task.verify_costly:return Plan(tier="standard", effort="medium")# 5) default pathreturn Plan(tier="flagship", effort="medium")
Front-loaded rules will always misjudge some tasks, so an automatic escalation fallback is mandatory: when the same task fails consecutively at a low tier past a threshold, move up one tier (raising reasoning effort at the same time when needed) and re-evaluate; if it still fails after two upgrades, hand off to a human rather than retrying indefinitely and burning through the budget.
def run_with_escalation(task: Task, plan: Plan, max_attempts: int = 3) -> Result:for attempt in range(max_attempts):res = adapters[plan.tier].chat(build_request(task, plan))record(task.id, plan.tier, plan.effort, attempt, res)if res.passed:return resplan = Plan(tier=upgrade(plan.tier), effort=plan.effort)return handoff_to_human(task, reason="auto_retry_exhausted")
Reasoning Effort: A Finer Cost Knob Than Switching Tiers
Beyond tier differences, most model services also offer several “reasoning effort” (thinking budget) settings that control how much internal computation a model spends before answering. This is an orthogonal dimension to the tier: the tier sets the model’s capability ceiling, while reasoning effort decides how much of that capability this particular call uses.
Three engineering realities must be understood:
- Monotonic but non-linear: capability increases with reasoning effort, but with diminishing marginal returns; raising reasoning effort on a low tier often yields more noticeable gains.
- A cost crossover exists: raising a tier’s reasoning effort by one more notch can cost nearly as much as—or more than—switching to a larger tier. So “thinking longer” is not always cheaper than “using a stronger model.”
- You must measure it yourself: the crossover point depends heavily on the task distribution and cannot be copied from others. The method is to run every combination over your own task set, plot a “pass rate vs. cost per task” curve, and find the cost-efficiency inflection point.
A usable combination matrix (example—replace with your own measurements):
| Task type | Recommended tier | Recommended reasoning effort | Notes |
|---|---|---|---|
| Classification, extraction, routing | Lite | Low | Fixed output structure, backed by validation |
| Single-file defect fix | Standard | Medium | Upgrade after one failure |
| Cross-module feature development | Flagship | Medium | Default combination |
| Complex debugging, hard defects | Flagship | High | Add effort first, don’t rush to switch tiers |
| Performance optimization, large-scale migration | Extreme | High | A clear spec doesn’t mean it’s simple |
| Unattended long-chain tasks | Extreme | High | Trade first-pass rate for total cost |
Sub-Agents: Parallelism and Context Isolation, at a Cost
A sub-agent is not just “calling more models.” Its core value lies in context isolation and parallelism. The main agent’s context window is a scarce resource; retrieval results, test logs, and review feedback fill it up quickly and degrade the quality of the main line of reasoning. Handing this work to single-purpose sub-agents means the main agent receives only structured conclusions and preserves its attention.
Auxiliary work suited for delegation: codebase retrieval and location, change review, test execution and failure attribution, batch format conversion, and documentation generation. What these share is clear input/output boundaries, feasibility on a lower tier, and results that a machine can verify.
The costs are equally clear and must be designed for up front:
- Lossy context handoff: a sub-agent cannot see the full background of the main task and is prone to locally optimal but globally wrong judgments; handoffs must state constraints and acceptance criteria explicitly.
- Higher total token consumption: the same context gets copied into several places, and cost can double or more.
- Merge and conflict cost: when multiple sub-agents edit the same area, conflicts arise; partition writes by file/directory and keep sub-agents read-only by default.
- Reduced debuggability: a unified trace is needed to link the main task with its sub-tasks.
The constraints can be written as three hard rules: each sub-agent has a single responsibility; its inputs and outputs use a fixed schema; and its conclusions are adopted only after passing a validator (compile, test, lint, schema check).
Engineering Guardrails: Budgets, Caching, Observability, and Security
- Budgets and circuit breakers: set token and spend caps per task, per user, and per day; on breach, automatically downgrade to a lower tier or hand off to a human, so a single runaway loop task cannot drag down total cost.
- Cache reuse: enable prompt caching for stable prefixes (system prompts, code context); cache results for repeated requests with identical inputs and parameters. These two measures usually cut cost more directly than switching tiers.
- Observability metrics: record per task the tier, reasoning effort, input/output tokens, latency, retry count, whether validation passed, and whether a human was involved, forming a cost–quality report that can be sliced by task type.
- Reproducibility: pin model versions, temperature, and other parameters; put tier and rule configuration under version control; route any policy change through a rollout and A/B test, so you avoid “tune once, and behavior changes everywhere.”
- Security and compliance: require human confirmation before highly irreversible operations; redact sensitive information in logs and prompts; use an approval or allowlist mechanism for model access in restricted professional domains instead of letting all tasks share the same permissions. Whether deployed on a self-managed cluster or a public cloud platform, common cloud product categories such as logging services, monitoring and alerting, and object storage can be reused directly rather than built from scratch.
Evaluation Loop: Let Data Drive the Selection Rules
Writing the rules is only the beginning. Maintain a representative task set of 100–300 items, bucketed by difficulty (simple changes, cross-module development, complex debugging, migration and optimization, batch processing), and run it every time the policy changes, producing:
- Pass rate and rework rate of each tier across each difficulty bucket;
- Cost per task (including retry amplification and manual rework time converted to cost);
- p50/p95 latency;
- The automatic escalation trigger rate—the core signal for judging whether the front-loaded rules are too strict; a persistently high escalation rate means the default tier is set too low.
One point deserves emphasis about the total-cost measure: looking at unit price alone leads to wrong conclusions. Three cheap-tier reworks, plus manual review time, often cost more than a single flagship-tier pass. Conversely, using a high tier for high-volume simple tasks is pure waste.
Common Pitfalls
- Treating “clear spec” as “simple task,” and thereby underestimating migration and optimization tasks.
- Comparing only token unit price while ignoring the total cost from retry amplification, rework, and manual intervention.
- Routing everything to the strongest tier—metrics look good in the short term, but cost spirals out of control over time.
- Letting sub-agents proliferate without order—cost doubles with unclear benefit, and conflict merging becomes the new bottleneck.
- Ignoring output consistency—different tasks in the same team use different tiers, and code style and interface conventions drift.
- Lacking versioning and rollouts—after an upgrade on the model-service side, the policy silently degrades until users complain.
Implementation Checklist
- Build an adapter layer with capability metadata, so business code contains no specific model names.
- Externalize the policy as a configuration file, so changing tiers requires no release.
- Set the default starting point to flagship tier + medium reasoning effort.
- Wire in objective difficulty signals (change surface, dependency count, verification cost, historical rework).
- Implement automatic escalation on failure and a human handoff fallback.
- Configure budgets, circuit breakers, and prompt caching.
- Partition sub-agents by write scope and enforce output validation.
- Build an offline evaluation set bucketed by difficulty and a cost report.
- Put rule configuration under version control and rollout.
- Re-measure the “reasoning effort vs. tier” cost-efficiency inflection point every quarter and update the decision table as models evolve.
In one sentence: the key to freely choosing a model is not adding a dropdown to the agent, but building the whole decision mechanism of “capability metadata + difficulty judgment + reasoning-effort tuning + failure escalation + cost observability,” so that every unit of inference budget is spent on the tasks that truly need it.
