Practical Notes on LLM Costs and Model Selection for Coding Agents
This article explains how token consumption in coding agents drives LLM costs and how teams can approach model selection. It covers cost components, a basic estimation method, a comparison framework for effectiveness, speed, and cost, tiered model routing, usage monitoring with budget controls, and engineering practices for keeping agent costs under control.
1. Background: Coding Scenarios Make Token Consumption a Key Variable
Traditional question-answering requests typically consume a few thousand tokens, so their costs are easy to estimate. Coding agents work differently. They read code context, call retrieval and compilation tools, and repeatedly modify code based on test results. A single task can involve dozens of model requests, and cumulative consumption can reach millions of tokens.
In this setting, unit prices, context length, output length, concurrency limits, and quota conversion rules together determine the actual cost. Choosing a model based only on public benchmark scores makes it hard to answer the question “how much does this task actually cost?”
Recently, the industry has seen a recurring pattern. Some services attracted many users during free or low-price phases, and daily usage dropped quickly once those phases ended. Models with more stable prices then regained calls. This shows that developers are highly sensitive to cost, and cost has become part of the product experience. Teams should manage cost as an architectural metric rather than calculating it after the fact.
2. Understanding Token Metering and Cost Structure
Most pay-as-you-go services price input tokens and output tokens separately, and output prices are usually higher than input prices. In coding tasks, input often includes large amounts of code context, while output includes code patches and explanatory text. The ratio between the two directly affects total cost.
Besides base prices, several other factors should be included in the calculation:
- Context length: Each request resends the context, so longer context means more input tokens per call.
- Number of calls: Multi-step reasoning and tool calls multiply the cost of a single task.
- Quota conversion: Some services convert actual usage into quota using a multiplier. The same unit price can therefore lead to different real costs under different conversion rules.
- Caching rules: Some services support context caching, and cache hits may be billed differently. Check the provider’s documentation for the exact rules rather than assuming them.
Based on these factors, you can build a basic estimation formula:
Cost per task = number of calls × (average input tokens × input price + average output tokens × output price) ÷ 1,000,000 × quota multiplier
The example below shows how to apply this formula. The prices are fictional values for illustration only. Replace them with the prices published by your provider.
define model:name = "Example Model A"input_price = 1.0 # price per million input tokens (example value)output_price = 4.0 # price per million output tokens (example value)quota_multiplier = 1.0function estimate_task_cost(model, call_count, avg_input, avg_output):cost_per_call = (avg_input × model.input_price + avg_output × model.output_price) ÷ 1,000,000return cost_per_call × call_count × model.quota_multiplierestimate_task_cost(model, call_count=40, avg_input=30000, avg_output=2000)# result is approximately 1.52 (example unit)
The result shows that input context is usually the main source of cost. Controlling context size therefore has a bigger effect than simply reducing output length.
3. Selection Framework: Evaluating Effectiveness, Speed, and Cost
Evaluate models on your team’s own task set rather than relying only on public leaderboards. Consider the following three dimensions.
| Dimension | Key metrics | Common pitfalls |
|---|---|---|
| Effectiveness | Bug-fix success rate, unit test pass rate, recall of issues in code review | Relying only on overall leaderboard scores and ignoring fit with your own workload |
| Speed | Time to first token, total generation time, rate-limit frequency | Looking only at averages and ignoring how long-tail latency affects developer wait time |
| Cost | Cost per call, cost per successful task | Comparing unit prices only and ignoring extra spending from failed retries |
Cost per successful task is the most important metric:
Cost per successful task = total task cost ÷ number of successfully completed tasks
A model with a low unit price may fail often and need multiple retries. Its cost per successful task can then exceed that of a model with a higher unit price but a higher first-pass success rate. When comparing models, record both success rate and cost to get a realistic comparison.
4. Tiered Routing: Avoid Using One Model for All Requests
Sending every request to one high-capability model raises costs. Sending every request to a low-cost model increases failure rates on complex tasks. A better approach is to route tasks by type.
- Simple tasks: Formatting, comment generation, and local renaming suit a low-cost model.
- Medium tasks: Single-file changes and routine feature implementation can use the default model.
- Complex tasks: Cross-file refactoring, architecture changes, and hard-to-locate bugs suit a high-capability model.
The routing logic can be written as the following pseudocode:
function select_model(task):if task.type in {"formatting", "renaming", "comment generation"}:return "lightweight model"if task.context_tokens > 100000 or task.type == "refactoring":return "high-capability model"return "default model"
The routing rules should also include an escalation mechanism. When a lightweight model fails tests twice in a row, the system switches automatically to a more capable model and retries. This keeps average cost under control while maintaining completion rates for complex tasks.
5. Usage Monitoring and Budget Control
Without monitoring, cost control depends on checking bills after the fact. Teams should record the following information at the request level:
- The model name and version used;
- Input token count and output token count;
- The project, team, and task type;
- The final task result (success, failure, or aborted).
With this data, you can track costs by project, identify abnormal tasks, and send alerts when spending nears a budget limit. On cloud platforms such as Baidu AI Cloud, you can build a usage dashboard with general-purpose log services and monitoring and alerting components, without building a custom data pipeline.
Budget control can operate at three levels:
- Per-task limit: Abort the task automatically and notify the developer when the threshold is exceeded.
- Daily budget limit: After the threshold is exceeded, move non-critical tasks to a lower-cost model.
- Anomaly detection: A sudden increase in token usage for a single task often indicates runaway context or a call loop.
6. Engineering Recommendations
Several measures can directly reduce cost and improve stability in agent implementations.
First, control context size. Do not inject the entire code repository into every request. Use retrieval to provide only the files and snippets relevant to the current task.
Second, set a maximum number of iterations to prevent the agent from getting stuck in a call loop:
max_steps = 20loop step from 1 to max_steps:result = execute_step(state)if result.completed:breakelse:raise exception("Task exceeded the maximum number of iterations and was aborted")
Third, set output length limits. Where possible, ask the model to provide a short plan before generating full code. This reduces unnecessary output.
Fourth, cache repeated retrieval results and tool outputs so that the same content is not billed more than once.
Fifth, save the model, token consumption, and test results for each task, and run regular regression analysis. This data supports model selection decisions and serves as a basis for adjusting budgets.
7. Implementation Steps
Teams can proceed in the following order:
- Build an evaluation set from real tasks that covers simple, medium, and complex categories.
- For each candidate model, measure success rate, latency, and cost per successful task.
- Design tiered routing rules based on the results, and add an escalation mechanism for failures.
- Launch usage monitoring and budget thresholds. Observe the data for one to two weeks before adjusting parameters.
- Review unit prices and quota rules regularly, since providers may change their billing policies.
No fixed optimal balance exists between cost and effectiveness. Only by comparing token consumption, success rate, and latency under the same set of metrics can a team make reproducible model selection decisions for its specific scenario.
