LLM Token Cost Accounting and Building a Low-Cost Coding Agent

    This article explains how to account for LLM token costs in coding agents. It covers the billing model for input, output, and cached tokens, the trade-offs of long context windows, and the role of model architecture. It then describes practical ways to lower costs, including context retrieval, cache-friendly prompt design, model routing, output control, retry handling, and usage monitoring. Finally, it recommends comparing models on a fixed task set using pass rate, cost per task, number of rounds, and latency.

    1. Why Coding Agents Need Separate Cost Accounting

    Simple question-answering applications send short inputs and receive short outputs in each call, so their costs rarely get out of control. Coding agents work differently. They read project files, trace call relationships, modify code over multiple rounds, and run tests. Each round can carry a large amount of context. The relevant files in a mid-sized codebase alone can reach several hundred thousand tokens. As the number of calls grows, costs add up quickly.

    When evaluating a coding agent, do not look only at the unit price. Also look at the full cost of a single task: input volume, output volume, cache hit rate, and the number of call rounds needed to finish the task.

    2. Breaking Down the Token Billing Model

    Most LLM services charge by token. Billing usually includes three categories:

    1. Input tokens: system prompts, conversation history, file contents, and tool results included in a request.
    2. Output tokens: the answers, code, and reasoning content the model generates (if reasoning is billed).
    3. Cached read tokens: when the prefix of a request matches recent requests, the service can reuse the part it already computed. These tokens are usually priced lower.

    You can estimate the cost of a single call with the following formula:

    1. Cost per call = (uncached input tokens / 1M) × input price
    2. + (cached input tokens / 1M) × cached read price
    3. + (output tokens / 1M) × output price

    Below is an example estimation function. The prices are assumed values for demonstration. Always check the provider’s current prices before use.

    1. def estimate_cost(input_tokens: int,
    2. output_tokens: int,
    3. cached_tokens: int = 0,
    4. price_in: float = 1.0, # Price per million input tokens (assumed)
    5. price_out: float = 4.0, # Price per million output tokens (assumed)
    6. price_cache: float = 0.25): # Price per million cached read tokens (assumed)
    7. """Estimate the cost of a single call. The result uses the same unit as the prices."""
    8. if cached_tokens > input_tokens:
    9. raise ValueError("Cached tokens cannot exceed total input tokens")
    10. uncached = input_tokens - cached_tokens
    11. cost = (uncached * price_in
    12. + cached_tokens * price_cache
    13. + output_tokens * price_out) / 1_000_000
    14. return cost
    15. # Example: 500K input tokens, 300K of them cache hits, and 20K output tokens
    16. print(round(estimate_cost(500_000, 20_000, cached_tokens=300_000), 4))

    This code makes two points. First, cached tokens are a subset of input tokens, so they must be subtracted first to avoid double billing. Second, input and output prices are usually very different, and the more output a call produces, the faster the cost rises.

    3. The Benefits and Costs of Long Context

    A long context window lets an agent read more code at once, which reduces errors caused by missing information. This matters most for tasks that require understanding dependencies across files.

    Long context does not always pay off, for three reasons:

    • Cost grows linearly with input size. Resending the entire repository on every call can push expenses far beyond expectations.
    • The more information the model receives, the easier it is to distract with irrelevant content, and locating the key code becomes harder.
    • Response times get longer, so the total time for multi-round iteration increases.

    Treat long context as spare capacity, not as the default input method. Whether to use the full context should depend on whether the task truly needs a global view across modules.

    4. Architectural Factors in Efficiency

    Some LLMs use a mixture-of-experts (MoE) architecture, which activates only part of the parameters for each inference. This keeps the computation per call under control even when total model capacity is large. Sparse attention and linear attention mechanisms also aim to reduce the cost of attention computation on long sequences. The shared goal of these methods is to cut compute consumption when processing longer inputs.

    For users, architecture details do not directly determine the bill. However, they explain why different models differ in price and speed in long-context scenarios. When choosing a model, use architectural characteristics as a reference, but base the final decision on quality and cost test results for your actual tasks.

    5. Building a Low-Cost and Stable Coding Agent

    Cost control should run through the whole agent design. Adjusting prices at the end is not enough. The following practices are commonly used.

    1. Keep Context Lean and Retrieve on Demand

    Do not put the entire repository into the prompt at once. Start by building a code index that covers the file structure, where functions and classes are defined, and how modules reference each other. The agent first retrieves the relevant files based on the task, then reads specific sections. This usually cuts input volume by an order of magnitude.

    2. Keep Prefixes Stable to Raise Cache Hit Rates

    Caching depends on the request prefix matching exactly. Place unchanging content, such as system prompts, tool definitions, and project background, at the start of the request, and keep it byte-for-byte identical. Put dynamic content, such as the current task description and the latest error logs, at the end. If the prefix changes every time, the cache cannot hit.

    3. Route Tasks to Models by Tier

    Not every step needs the strongest model. File retrieval, formatting, and simple completions can go to smaller, cheaper models. Complex architectural changes and hard bug diagnosis go to high-capability models. Routing rules can be based on task type or on the number of failed attempts.

    4. Control Output Length

    Set a maximum output token limit, and instruct the model to return only the changed code blocks. This prevents it from repeating entire files. Output tokens usually cost more than input tokens, so this step gives a direct return.

    5. Handle Failures and Retries

    Network timeouts, rate limits, and occasional formatting errors can all cause duplicate billing. Cap the number of retries and use exponential backoff. For tool calls, make operations idempotent so that repeated execution does not modify files multiple times.

    6. Track Usage and Set Budget Alerts

    Log input tokens, output tokens, cache hit tokens, and latency for every call, and aggregate them by task ID. When the cost of a single task exceeds a threshold or the number of rounds rises abnormally, trigger an alert and stop the task. This data also informs later optimization.

    6. Evaluating Quality and Cost on a Fixed Task Set

    Both model selection and optimization need a repeatable evaluation method. Prepare a fixed set of coding tasks, such as fixing known bugs, adding unit tests, and refactoring small modules. Record these metrics:

    • Task pass rate: whether all tests pass after the changes.
    • Cost per task: total spend to complete the task.
    • Average rounds: number of calls needed to reach a passing result.
    • End-to-end latency: time from submitting the task to getting a usable result.

    Judging by the per-call unit price alone easily leads to wrong conclusions. A model with a lower unit price may need more rounds to pass the tests, so its final cost can be higher. Only a comparison on a fixed task set yields reliable conclusions.

    7. Considerations

    1. Prices change over time. Limited-time discounts and price adjustments both change the results, so record the query date next to any prices in your documentation.
    2. Inject API keys and access credentials through environment variables or a secrets management service. Do not write them into code or logs.
    3. Before sending code to a third-party service, check whether it contains sensitive information, customer data, or content restricted by a license. Follow your team’s data security policies.
    4. Keep a margin in cost estimates. Actual token counts often exceed estimates, especially when tools return large logs.

    Key Takeaways

    Estimating the cost of a coding agent requires considering unit price, input size, cache hits, output length, and number of rounds together. By keeping context lean, stabilizing request prefixes, routing tasks to models by tier, and improving monitoring, you can keep the cost per task within an acceptable range without sacrificing task quality.