Building a Low-Cost Coding Agent: Practical Cost Controls
Learn how to estimate coding agent costs, reduce token usage through context pruning and caching, and control spending with model routing, budget limits, and reliable request handling. Includes illustrative Python code and a deployment checklist.
1. Why Coding Agent Costs Can Escalate
Coding agents typically read large amounts of source code, configuration files, and project history before producing recommendations or patches. These workloads have two important characteristics.
First, input tokens often far outnumber output tokens. Analyzing a medium-sized repository may require hundreds of thousands of context tokens, while the resulting recommendations may contain only tens of thousands. As a result, input pricing often has a greater impact on total cost than output pricing.
Second, agents make multiple model calls. A single task may involve retrieval, planning, editing, and self-review, with context sent again at each step. As the number of calls grows, individually inexpensive requests can add up to a substantial bill.
Provider pricing can also change because of promotions, pricing updates, or subscription changes. Hardcoding prices into application logic makes spending harder to predict. Effective cost control therefore requires both accurate per-call accounting and engineering practices that reduce unnecessary token consumption.
2. Build a Cost Accounting Model
2.1 The Basic Formula
The cost of a single call can be calculated as:
Cost per call =(Uncached input tokens × Input price+ Cached input tokens × Cache read price+ Output tokens × Output price)/ 1,000,000
This formula assumes prices are quoted per million tokens. Cache reads typically cost less than uncached input, but not every platform supports caching. Refer to the provider’s billing documentation for the applicable rules.
2.2 Example Calculation
The following prices are illustrative only and do not represent any actual provider. Assume these rates:
- Input: CNY 1.0 per million tokens
- Output: CNY 4.0 per million tokens
- Cache reads: CNY 0.2 per million tokens
Consider a repository analysis task with 500,000 input tokens and 20,000 output tokens.
Without caching:
0.5 × 1.0 + 0.02 × 4.0 = CNY 0.58
With an 80% input cache hit rate:
Cached input: 0.4 × 0.2 = CNY 0.08Uncached input: 0.1 × 1.0 = CNY 0.10Output: 0.02 × 4.0 = CNY 0.08Total: CNY 0.26
The same task costs less than half as much when most of its input can be reused from cache. The next section explains how to structure requests to support that reuse.
2.3 Keep Pricing in Configuration
Do not hardcode prices in business logic. Store rates in a configuration file and record when they take effect. When pricing changes, update the configuration and rerun cost estimates to assess the impact on the budget.
3. Engineering Techniques to Reduce Token Usage
3.1 Retrieve First, Then Trim Context
Sending an entire repository to the model is the most expensive approach. A more efficient workflow retrieves relevant material before reading it:
- Use keywords or a symbol index to identify files related to the task.
- Read only the relevant functions, classes, or code sections, including enough surrounding lines to preserve context.
- Summarize very long files and load the original content only when needed.
This reduces input costs while limiting irrelevant information that could distract the model.
3.2 Keep Prompt Prefixes Stable
Prompt caching commonly relies on matching request prefixes. If system instructions, tool definitions, and project guidelines retain the same content and order across requests, that prefix can be reused. Inserting a timestamp or random ID at the beginning can prevent cache hits.
Place stable content first and request-specific material, such as task descriptions and file excerpts, afterward.
3.3 Match Model Capability to Task Difficulty
Not every step requires the most capable model. A common allocation is:
- File classification, log summarization, and format conversion: Use a lightweight model.
- Code changes and bug localization: Use a mid-tier model.
- Cross-module refactoring and complex design reviews: Use the most capable model, with a limit on the number of calls.
Some models use a mixture-of-experts (MoE) architecture, activating only a subset of parameters for each token to reduce computation. The practical benefits vary by implementation, so model selection should still be based on your own test results.
3.4 Constrain Output Format and Length
Longer output costs more. Request a consistent patch format or structured JSON, and set a maximum output token limit. Asking for only the code blocks that need to change, rather than entire files, can substantially reduce output volume.
3.5 Cache Analysis Results
Save analysis results for unchanged file versions. A hash of the file contents can serve as the identifier. If the file has not changed, reuse the local result instead of making another model call.
4. Design for Reliability
A cost-controlled agent also needs to run reliably. The following practices address common failure modes.
Timeouts and retries. Network problems and rate limits can cause requests to fail. Use exponential backoff for retryable errors and set a maximum retry count. For unrecoverable errors, such as invalid parameters or insufficient permissions, fail immediately and log the error.
Output validation. Model responses may not follow the requested format. Validate structured output using a mechanism such as JSON Schema. If validation fails, retry once with the validation error or route the result for human review.
Fallback behavior. If the preferred model is unavailable, switch to a backup model only if it has passed the same test suite.
Version pinning and regression testing. Provider model updates can change output style and accuracy. Pin model versions where possible and maintain a representative regression test set. Run those tests before switching versions.
5. Illustrative Python Code
The following code demonstrates the structure only. Replace the client interface with your team’s SDK or HTTP wrapper.
import timefrom dataclasses import dataclass@dataclassclass Pricing:input_per_m: float # Input price, CNY per million tokensoutput_per_m: float # Output price, CNY per million tokenscache_read_per_m: float # Cache read price, CNY per million tokensdef estimate_cost(p: Pricing, input_tokens: int, output_tokens: int,cached_tokens: int = 0) -> float:fresh = input_tokens - cached_tokenscost = (fresh * p.input_per_m+ cached_tokens * p.cache_read_per_m+ output_tokens * p.output_per_m)return cost / 1_000_000class BudgetGuard:"""Reject new requests when they would exceed the daily budget."""def __init__(self, daily_limit: float):self.limit = daily_limitself.spent = 0.0def charge(self, cost: float) -> None:if self.spent + cost > self.limit:raise RuntimeError("Daily budget exhausted; request rejected")self.spent += costclass TransientError(Exception):"""Retryable errors, such as network timeouts and rate limits."""def call_with_retry(client, request, max_retries: int = 3):for attempt in range(max_retries):try:return client.chat(request, timeout=60)except TransientError:if attempt == max_retries - 1:raisetime.sleep(2 ** attempt) # Exponential backoff
Use estimate_cost to estimate the cost of a call, pass that estimate to BudgetGuard.charge for budget accounting, and then issue the request through call_with_retry. Keeping these components separate makes them easier to test and replace.
6. Deployment Checklist
- Is pricing configured separately from business logic, with effective dates recorded?
- Does each task record input, cached input, and output token counts?
- Is context retrieved and trimmed rather than loaded from the entire repository?
- Are prompt prefixes kept stable to support cache hits?
- Are tasks assigned to different model tiers according to difficulty?
- Are output formats constrained and output lengths capped?
- Are daily budget limits, timeouts, and retry policies in place?
- Are model versions pinned, with regression tests covering key tasks?
Working through this checklist helps teams maintain a manageable balance between cost, quality, and reliability.
