AI Coding Agent Routing: Why Lower Model Prices Can Double Your Bill
Lower per-token prices do not necessarily reduce the cost of running AI coding agents. Adaptive reasoning, growing tool-use loops, and timeout retries can push spending higher even when benchmark scores barely improve. This article explains how to measure cost per completed task, apply budget and timeout circuit breakers, and escalate reasoning effort only when validation fails, with an illustrative Python router and practical monitoring guidance.
1. Lower Unit Prices, Higher Bills
Over the past year, published prices for major large language model services have continued to fall. Input and output rates have generally moved into the single-digit-dollar range per million tokens, with some entry-level tiers priced even lower.
Yet when teams move from comparing prices per million tokens to measuring actual spending per completed task, the picture can reverse: a 20% reduction in unit price may coincide with a task cost that doubles—or rises even further.
The explanation is straightforward. AI coding workloads depend on more than the token rate. Their costs are driven by three interacting factors:
Cost per task ≈ Unit price × (Input tokens + Output tokens)× Retry/timeout multiplier
With adaptive reasoning, token consumption and retry overhead can grow nonlinearly as task difficulty increases. That growth can more than offset lower published prices.
2. Measure Cost per Completed Task, Not Just Token Prices
Static price comparisons are insufficient for evaluating agentic models. At a minimum, track three metrics:
- Tokens / Task: The average total token consumption required to complete a standard task. This captures expansion in the reasoning, tool-call, and result-reading loop.
- Steps / Task: The average number of steps, an early indicator that an agent loop may be getting out of control.
- Cost / Finished Task: The cost per completed task—the metric that aligns with financial reporting.
The reported tests illustrate a common pattern. Two models scored less than one percentage point apart on a real-session benchmark—60.4% versus 60.0%—but their resource consumption differed sharply:
| Metric | Model A | Model B |
|---|---|---|
| Benchmark score | 60.4% | 60.0% |
| Tokens per task | About 40,000 | About 350,000 |
| Steps per task | About 70 | About 218 |
| Cost per completed task | About $1.20 | About $12.80 |
Token consumption differed by nearly nine times, while average step counts differed by more than three times.
Similar scores with an order-of-magnitude cost difference are the central trade-off that routing decisions must address.
3. How Adaptive Reasoning Amplifies Costs
Adaptive thinking lets a model choose its reasoning depth based on task difficulty. This can save money on simple tasks, but long-running coding workflows can expose two side effects.
- An effort-level ratchet. Failed tool results or error logs in the context can cause the model to increase its reasoning effort. Subsequent steps may remain at the higher, more expensive level, effectively locking costs at an elevated rate.
- Step inflation. Higher effort can produce longer internal reasoning and more tool calls. More steps also increase input token consumption because the accumulated conversation and tool history are read repeatedly.
The reported evaluations also challenge the assumption that the highest effort setting always performs best. The highest setting produced a 60.0% session-benchmark score, while the next-highest setting showed 81.2% on a separate reasoning evaluation; the highest setting also incurred many timeouts. These are different evaluation contexts, rather than a like-for-like score comparison, but they do not support treating maximum effort as automatically preferable.
Effort selection should therefore be a budget-constrained scheduling decision, not a fixed configuration.
4. The Cost Trap of Long-Running Timeouts
When a task is allowed to run for roughly 12 hours, timeouts can create a costly mismatch between spending and useful output:
- A task is terminated near its deadline. Tokens already consumed are still billed, but no usable result is delivered.
- An upstream retry mechanism launches the same task again, adding another round of costs.
- Useful output remains zero while charges accumulate across attempts.
One reported result combined a 65.7% score with 28 timeouts out of 55 cases. That is a clear warning sign: substantial spending can go toward tasks that never finish, potentially consuming close to half the budget without producing completed results.
The first purpose of a circuit breaker is not optimization; it is stopping further losses.
5. Four Gates for Production Routing
A production routing layer should include four gates, applied in sequence.
1. Budget gate
Set token and monetary limits for each task. Use a soft threshold for warnings and a hard threshold for termination. When the hard threshold is reached, stop the task and persist its execution state.
2. Step and stagnation gate
Treat repeated calls to the same tool, or a sequence of N steps without meaningful file changes, as signs of a loop. Trip the circuit breaker rather than letting the agent continue indefinitely.
3. Timeout gate
Set a wall-clock limit substantially shorter than 12 hours. Reaching that limit should count as failure, not as a reason to keep waiting.
4. Validation-driven escalation gate
After an attempt finishes, run automated validation such as compilation, unit tests, and static checks. If validation passes, close the task without further escalation and favor lower effort for subsequent routing. If validation fails, escalate and retry only while budget remains.
Together, these gates turn model and effort selection from a manual judgment into a feedback loop driven by budget limits and validation results.
6. Reference Implementation: An Illustrative Python Router
The following example uses an abstract client interface so that it can be adapted to different model services.
import time, dataclassesfrom typing import Protocol, Callableclass LLMClient(Protocol):def run(self, prompt: str, effort: str) -> "Result": ...@dataclasses.dataclassclass Result:ok: boolinput_tokens: intoutput_tokens: intsteps: int@dataclasses.dataclassclass Budget:max_tokens: int = 120_000 # Hard token limit per taskmax_cost: float = 2.0 # Hard cost limit per taskmax_wall_clock: float = 1800 # Wall-clock limit in secondsprice_in: float = 1.0 / 1e6 # Input price per tokenprice_out: float = 10.0 / 1e6class BudgetExceeded(Exception): ...class CircuitRouter:LADDER = ["low", "medium", "high", "xhigh"] # Lowest to highestdef __init__(self, client: LLMClient, budget: Budget,verify: Callable[[], bool]):self.client, self.budget, self.verify = client, budget, verifydef _spent(self, r: Result) -> float:return (r.input_tokens * self.budget.price_in+ r.output_tokens * self.budget.price_out)def solve(self, prompt: str) -> tuple[str, list[dict]]:trace, level, spent, tokens, steps = [], 0, 0.0, 0, 0deadline = time.monotonic() + self.budget.max_wall_clockwhile level < len(self.LADDER):if time.monotonic() > deadline:raise BudgetExceeded("wall clock exceeded")effort = self.LADDER[level]r = self.client.run(prompt, effort)spent += self._spent(r)tokens += r.input_tokens + r.output_tokenssteps += r.stepstrace.append({"effort": effort, "cost": round(spent, 4),"tokens": tokens, "steps": steps})if tokens > self.budget.max_tokens or spent > self.budget.max_cost:raise BudgetExceeded(f"budget hit at {effort}")if r.ok and self.verify():return effort, trace # Finish once validation passeslevel += 1 # Escalate only after failureraise BudgetExceeded("ladder exhausted")
This is a routing sketch, not a complete implementation of all four gates. It checks elapsed time between client calls and accounts for usage after each call returns; it does not itself interrupt an in-flight call, detect stagnation, or persist the trace when an exception occurs.
Three implementation principles remain central:
- Start low, then escalate. Use the lowest effort setting by default and reserve higher settings for attempts that fail validation.
- Persist state when the circuit trips. Write the trace to logs on failure so that investigations can distinguish reasoning expansion from repeated tool loops.
- Enforce wall-clock limits independently of spending limits. Stop timed-out work rather than paying to “wait a little longer.”
7. Observability and Integration
Record a task-level cost ledger
For every task, capture:
- Reasoning effort level
- Token consumption
- Step count
- Elapsed time
- Validation result
- Whether a circuit breaker was triggered
These records should support aggregation into a task-level cost ledger.
Alert on operational cost signals
Set alert thresholds for:
- P95 cost per task
- Timeout rate
- Average step count
These metrics expose problems earlier than published token prices do.
Combine standard cloud services
A typical deployment combines a model service, object storage for execution state and traces, a message queue for traffic smoothing and retry isolation, and logging and monitoring services.
Platforms such as Baidu AI Cloud provide these as standard product categories that can be combined as needed, avoiding the need to build the entire infrastructure stack from scratch. Availability should be checked for the intended deployment region.
Maintain a fixed regression baseline
Whenever the effort ladder or budget thresholds change, rerun the same fixed task set. Compare Cost / Finished Task, not just unit prices.
8. Conclusion
Published token prices are only one part of the cost equation. Token consumption, step inflation, and timeout retries determine whether lower prices translate into lower bills.
A routing loop built around budget circuit breakers and validation-driven escalation makes those costs manageable. Using cost per completed task as the financial measure keeps routing decisions focused on useful outcomes—not merely cheaper tokens.
