Multi-Model Tiered Routing: Cost Control for Agentic Coding
This article explains why agentic coding consumes large token budgets, how to route tasks to L1, L2, and L3 model tiers by difficulty, when to upgrade or fall back, which usage metrics to monitor, and how a Python example can implement budget-aware routing and usage tracking.
1. Why Agentic Coding Consumes So Many Tokens
Ordinary chat is a single question-and-answer exchange with a relatively short context. Agentic coding first reads multiple files to build context, then analyzes code structure, generates a modification plan, runs tests, and continues modifying based on test output. Each request usually carries prior conversation and tool output, so total consumption accumulates across rounds rather than depending only on the length of a single prompt.
Actual usage varies widely depending on project size, task description, and the model’s context window. Teams should use their own call logs to measure the average token count for each task category instead of directly applying experience numbers from other teams.
Cost also affects productivity. If developers spend time researching billing windows or model price fluctuations, their attention shifts from business problems to the bill. Cost control should therefore be handled by programmatic mechanisms. These mechanisms still require human review and anomaly alerts; automatic routing cannot replace code review.
2. Use Task Difficulty to Decide Model Tier
The core of multi-model calling is tiering: use lower-cost models for low-difficulty tasks and more capable models for high-difficulty tasks. Common coding tasks can be divided into three categories:
| Task type | Typical characteristics | Recommended tier | Cost impact | Result validation | Risk note |
|---|---|---|---|---|---|
| Mechanical changes | Renaming, formatting, adding comments, generating boilerplate | L1 small model | Low unit price, few rounds | Compile, lint, unit tests | Human check needed when change scope becomes too large |
| Routine development | Implementing clearly specified features, fixing well-localized defects, writing tests | L2 medium model | Moderate | Unit and integration tests | Cross-module changes may exceed model capability |
| Complex problems | Cross-module refactoring, concurrency or performance issues, architecture decisions, hard defects | L3 strong model | Higher unit price, but can reduce failed retries | Benchmarks, code review, human acceptance | Highest cost; control call count |
Tiering is based on three criteria: whether cross-file reasoning is required, whether there is a clear validation method, and how costly failure would be. When unsure, mark the task as a higher tier. A low-tier failure often triggers more rounds, and the total cost may not be lower.
This approach does not apply to every scenario. Code involving security vulnerability fixes, cryptography implementations, or compliance requirements should directly use the strongest evaluated model without downgrading. If task volume is small, or the team uses only one model, the savings from tiering may not offset the cost of maintaining routing logic. In that case, consider other measures, such as limiting the scope of file reads, compressing historical context, and caching recurring project information.
3. Model Selection and Upgrade Mechanism
Selection should compare price per call, context window size, code capability, response speed, and stability. The table below is a reference framework; for specific models, use the provider’s current published pricing and capability descriptions.
| Tier | Suitable tasks | Selection rationale | Boundary | Alternative |
|---|---|---|---|---|
| L1 | Mechanical changes, batch replacement | Lowest unit price, fast response | Not suitable for changes requiring reasoning | Local small model or rule scripts |
| L2 | Routine feature development, unit tests | Good cost-performance, covers most daily tasks | Complex cross-module tasks are error-prone | Other provider models at the same level |
| L3 | Complex refactoring, hard defects, architecture evaluation | Strongest reasoning capability | High cost; use only when necessary | Split tasks manually and assign to L2 |
Upgrade to a higher tier when any of the following conditions is met:
- The same task fails tests in two consecutive rounds, and the error information does not change.
- Cumulative tokens for a single task exceed the tier’s budget cap.
- The model’s modification plan clearly deviates from the requirement, or it repeatedly modifies the same file.
- The task involves security-sensitive code or a core module.
Downgrade and fallback require more caution. Only try a lower tier when the task is clearly simple and all tests in the previous round have passed. Failed retries should have a cap, for example, at most two retries at the same tier; after that, upgrade or hand off to a human. Without a retry cap, cost can grow rapidly in an invalid loop.
4. Usage Monitoring and Code Example
Monitoring should cover the following metrics, not just total tokens:
- Input and output tokens per round, to locate the round where usage starts to inflate.
- Rounds per task. A high number of rounds usually indicates poor task decomposition.
- Call count and upgrade count for each tier, to judge whether tiering is too coarse or too fine.
- Test pass rate and retry count, to judge whether upgrade thresholds are appropriate.
- Estimated cost per task, converted using each tier’s unit price.
Running the example below requires Python 3.10 or later. The API key is read from the environment variable LLM_API_KEY; do not write it into code or logs. The example only demonstrates routing and usage logging logic. Model names and API calls must be replaced with your provider’s configuration.
import osimport timefrom dataclasses import dataclass, fieldTIERS = [{"name": "L1", "model": "small-model", "price_per_m": 0.5},{"name": "L2", "model": "medium-model", "price_per_m": 2.0},{"name": "L3", "model": "large-model", "price_per_m": 10.0},]MAX_RETRY_PER_TIER = 2TASK_BUDGET_TOKENS = 300_000@dataclassclass TaskStats:level: int = 0total_tokens: int = 0rounds: int = 0retries: int = 0logs: list = field(default_factory=list)@propertydef tier(self) -> dict:return TIERS[self.level]def estimated_cost(self) -> float:return self.total_tokens / 1_000_000 * self.tier["price_per_m"]def call_model(model: str, prompt: str) -> tuple[str, int]:api_key = os.environ["LLM_API_KEY"] # Raise an error if missing# Replace with a real SDK call and use api_key for authenticationreply = "placeholder reply"used = (len(prompt) + len(reply)) // 2 #
