Coding Agent Token Costs: How Inference Costs Are Calculated

    Coding agents often consume far more tokens than chat-style interactions because they repeatedly resend context and append tool output. This article explains why token usage grows, how KV caching and speculative decoding affect unit cost, how subscription pricing relates to average cost, and what engineering teams can do to keep context and costs under control.

    1. Why Usage and Billing Do Not Match

    Recently, many developers have found that their large-model usage far exceeds expectations. At list prices, a month of token consumption can appear to correspond to a very high amount, while the actual subscription fee paid is much lower. This gap can lead to two conclusions: either the provider is operating at a loss, or the user’s usage statistics are wrong. Neither conclusion is accurate enough.

    To understand the gap, two questions need to be answered first. How is token usage generated? And what are the real cost components of inference services? The first depends on the application pattern; the second depends on the underlying computation mechanism. Looking only at total volume and unit price rarely produces a reliable conclusion.

    This article proceeds in the following order: first, why coding agents amplify token consumption; second, how caching and speculative decoding reduce unit cost; third, the mathematical logic of subscription pricing; and finally, practical recommendations for engineering teams.

    2. From Linear Chat to Iterative Execution

    2.1 The Token Model of Chat-Style Interaction

    Early chat applications followed a simple pattern: the user enters text, and the model returns an answer. On each turn, the input is the user’s new message plus the conversation history, and the output is the content generated for that turn. Token usage is roughly proportional to conversation length, so users can estimate consumption relatively intuitively.

    2.2 The Execution Loop of a Coding Agent

    A coding agent works differently. After receiving a task, it repeatedly executes a loop of “think, call a tool, read the result, think again.” A typical pseudocode example looks like this:

    1. context = [system_prompt, user_task]
    2. while not task_done(context):
    3. reply = model(context) # The entire context is sent to the model on every turn
    4. context.append(reply)
    5. if reply.has_tool_call():
    6. result = run_tool(reply.tool_call)
    7. context.append(result) # Tool output also enters the context

    This loop has two key characteristics. First, every turn sends the full context back to the model, even if most of it is identical to the previous turn. Second, tool output—such as file contents, command logs, and test results—is continuously appended to the context, so the input size keeps growing.

    2.3 How Input Volume Grows

    Let the initial context length be c₀, the average amount of new content added per turn be g tokens, and the number of turns be n. If the full input is processed on every turn, the cumulative input over n turns is:

    Σ(c₀ + i·g), for i from 1 to n, which equals n·c₀ + g·n(n+1)/2

    Cumulative input grows quadratically with the number of turns. For a task that requires dozens of tool calls, cumulative input can far exceed the information content of the task itself. This explains why the token count for a single task can appear unusually large.

    It is important to note that “high token consumption” does not mean “the model generated a large amount of original content.” Most consumption comes from repeatedly processing existing context, not from producing new content.

    3. KV Cache: Why Repeated Prefixes Are Cheaper

    3.1 The Two Phases of Inference

    Large-model inference is usually divided into two phases. The first is prefill, in which the model processes all input tokens at once and computes key-value vectors for each position—the KV cache. The second is decode, in which the model generates output tokens one by one, reading the existing KV cache each time a new token is generated.

    Prefill is computationally heavy but can be parallelized. Decode involves little computation per step but requires frequent reads from cache in GPU memory, making it more sensitive to memory bandwidth.

    3.2 How Prefix Reuse Works

    Coding-agent context has a clear pattern: system prompts, tool definitions, project instructions, and other prefixes remain unchanged throughout a session, while only a small amount of new content is appended at the end of each turn. If the server can identify and retain the KV cache for this prefix, subsequent requests do not need to recompute it.

    This mechanism is commonly called prefix caching. Its effectiveness depends on three factors: whether the prefix is stable, whether the cache is still valid, and whether requests can hit the same cache.

    3.3 Cost Model

    With prefix caching, the input cost of a single request can be split into two parts: uncached new tokens billed at the regular unit price, and cached tokens billed at a lower unit price. This can be expressed as:

    1. def request_cost(input_tokens, cached_tokens, output_tokens,
    2. price_in, price_cache, price_out):
    3. """Estimate the cost of a single request. Price parameters should follow the provider's official billing rules."""
    4. fresh_tokens = input_tokens - cached_tokens
    5. return (fresh_tokens * price_in
    6. + cached_tokens * price_cache
    7. + output_tokens * price_out)

    This model shows that cache hit rate is a key variable affecting cost. In long sessions, the longer the prefix and the higher the hit rate, the more input cost approaches linear growth rather than quadratic growth. This is why prefix caching is especially valuable for coding scenarios.

    4. Speculative Decoding: Output Efficiency in Long Sessions

    4.1 Basic Idea

    The bottleneck in the decode phase is generating tokens one by one, with each step requiring a full run of the large model. Speculative decoding first uses a small draft model to quickly generate several candidate tokens, and then the large model verifies those candidates in parallel in one pass. Verified tokens are accepted directly; at the first mismatch, the large model regenerates from that position.

    4.2 Estimating Expected Gains

    Let α be the probability that each candidate token from the draft model is accepted, and let the draft generate k candidate tokens each time. The average number of tokens produced per verification is:

    E = (1 − α^(k+1)) / (1 − α)

    When α is close to 1, E approaches k+1. In other words, the more accurate the draft model’s predictions, the more tokens a single large-model call can produce.

    4.3 Fit with Coding Scenarios

    Code has strong structural regularities. Indentation, bracket pairing, variable naming, and repeated boilerplate are all easy for a small model to predict accurately. As a result, acceptance rates in coding scenarios are often higher, and the gains from speculative decoding are more pronounced.

    For users, the implication is that long outputs from coding agents may have a lower unit computational cost than open-ended writing. The provider’s actual benefit depends on the specific implementation and workload; this article does not make a quantitative judgment about it.

    5. From Per-Request Cost to Subscription Pricing

    5.1 The Mathematical Nature of Flat Rates

    The core of a subscription model is average-cost pricing. Suppose a platform serves N users, the monthly fee per user is F, and the monthly inference cost of user u is C_u. The platform’s gross profit on this group of users is:

    N·F − Σ C_u

    As long as total cost is below total revenue, the platform can be profitable. However, usage distribution among users is usually highly uneven. A small number of heavy users may consume dozens of times more than the median user, so the platform needs to control tail usage rather than looking only at the average.

    5.2 Common Risk-Control Measures

    In practice, platforms usually adopt measures such as:

    • Offering tiered plans that direct high-usage demand to higher-priced tiers.
    • Setting limits on rate, concurrency, and single-task size.
    • Providing separate billing or quota rules for specific scenarios.
    • Continuously monitoring usage distribution and adjusting strategy in time.

    These measures fall within commercial operations. Specific rules vary widely across platforms, and users should rely on official descriptions.

    5.3 A Caution About Per-Request Cost Estimates

    Various “multiples based on list prices” circulating online are usually based on a specific set of assumptions—for example, calculating at standard API prices, assuming all cache hits, or ignoring differences in billing definitions. Such estimates have limited reference value and should not be treated directly as evidence of platform profit.

    6. Practical Recommendations for Engineering Teams

    6.1 Design a Stable Context Prefix

    Prefix caching depends on prefix stability. The following practices help improve hit rates:

    • Put invariant content such as system prompts and tool definitions at the very beginning of the context.
    • Avoid inserting timestamps, random IDs, or other content that changes every time into the prefix.
    • Keep tool declaration order and format fixed to reduce unnecessary byte differences.

    6.2 Control the Size of Tool Output

    Tool output is one of the main sources of context expansion. The following measures can help:

    • For long logs, keep only the beginning, the end, and key error lines.
    • Read file content on demand and avoid injecting entire files.
    • Set a maximum length for command output and replace the excess with a summary.
    1. def trim_output(text, max_chars=4000):
    2. if len(text) <= max_chars:
    3. return text
    4. head, tail = text[:max_chars // 2], text[-max_chars // 2:]
    5. return f"{head}\n...[omitted {len(text) - max_chars} characters in the middle]...\n{tail}"

    6.3 Split Long Tasks

    Splitting a task with dozens of steps into several subtasks, each using an independent and shorter context, can significantly reduce the cumulative input caused by quadratic growth. Subtasks should be connected through brief result summaries rather than by passing the full history.

    6.4 Establish Cost Observability

    Teams should record the following metrics per request: input tokens, cache-hit tokens, output tokens, number of calls, and task completion rate. With this data, teams can calculate “cost per completed task,” which reflects real efficiency better than “price per thousand tokens.”

    Logging services and monitoring/alerting platforms can be used to incorporate these metrics into regular dashboards.

    1. def cost_per_task(records, prices):
    2. total = 0.0
    3. completed = 0
    4. for r in records:
    5. total += request_cost(r["input"], r["cached"], r["output"],
    6. prices["in"], prices["cache"], prices["out"])
    7. if r["task_done"]:
    8. completed += 1
    9. return total / completed if completed else float("inf")

    7. Boundaries to Keep in Mind

    This article discusses general mechanisms. Prefix cache lifetime, hit-determination rules, cache price discounts, and the specific implementation of speculative decoding all vary by provider and deployment. Any decision involving specific costs should be based on the relevant platform’s official billing documentation and actual bills.

    In addition, high token consumption for a single task does not necessarily mean high unit cost for the provider, and vice versa. Judging cost structure requires looking at multiple factors at once, including usage, cache hit rate, model size, and request scheduling. A conclusion based on a single metric is easily distorted.

    For developers, the more practical goal is to enable agents to complete the same work with less context. Stable prefixes, concise tool output, and reasonable task splitting can reduce bills and also reduce the attention-dilution problem that models encounter in overly long contexts, thereby improving task quality.