Why AI Coding Agent Bills Explode: Breaking Down the Three Cost Accounts

    AI coding agents can burn through tokens dozens of times faster than a normal chat, even when a task only touches a handful of files. The root cause is the turn-based, stateless execution model, which re-submits the entire conversation history on every turn. This article breaks the bill into three accounts—input, caching, and output—and explains how each behaves: input grows roughly quadratically with context length and turn count, prompt caching can slash repeated reads to about one-tenth, and output tokens are the most expensive and cannot be cached. It includes a cost-estimation model with a Python script, six practical cost-reduction techniques, and a pre-launch checklist for measuring and controlling agent spend.

    1. Why the Bill “Mysteriously” Explodes

    When you use an AI coding assistant or code agent for long-running tasks, you often hit a counterintuitive pattern: the task only modified a dozen or so files, yet token consumption is dozens of times that of a normal chat, and the billing curve rises along a steep edge.

    The root cause isn’t “how many times an API was called.” It’s the turn-based execution model these tools rely on. An agent doesn’t solve a problem in a single request; it loops “read files → think → call a tool → see the result → reason again” dozens of times. On every turn the model is stateless—the server doesn’t remember what happened in the previous round—so the entire conversation history has to be resubmitted from scratch.

    This means context length doesn’t grow linearly; it’s amplified twice over, by “number of turns × context length.” To save money, you first have to break the cost structure into its component parts.

    2. First Account: Input — the Cumulative Cost of Repeated Reading

    Input tokens include far more than “the sentence you just typed”:

    • The system prompt and tool definitions (the tool schema);
    • Always-on context such as project structure, coding standards, and directory indexes;
    • The contents of every file read in previous rounds;
    • Return values from prior tool calls (log snippets, command output, search results);
    • Everything you’ve said, plus the body and reasoning the model produced earlier.

    The key point: history accumulates, and you pay for it again on every turn. If the context at turn r is C_r, then total input cost is proportional to Σ C_r, not max(C_r). When the average context reaches into the hundreds of thousands of tokens and the turn count climbs into the dozens, total input can easily hit the tens of millions of tokens—which is why a long task like “79 turns, re-reading ~148K tokens per turn on average” can consume the bulk of the budget on the input side alone.

    A useful mental model: long-task cost is roughly quadratic. Because C_r grows roughly linearly over time, the sum behaves like a second-order curve. Turn count is the steepest independent variable on the cost curve.

    3. Second Account: Caching — Cutting Repeated Reads to One-Tenth

    The good news is that mainstream large-model services generally offer prompt (prefix) caching: when multiple requests share an identical prefix, the server can reuse the already-computed attention state for that portion, bill those tokens at a significant discount, and also noticeably reduce time-to-first-token.

    Typical billing rules (these vary slightly by provider—confirm against the official documentation before you commit):

    Item Multiplier Notes
    Cache write (cache creation) input price × 1.25 TTL ~5 minutes; a longer TTL (e.g., 1 hour) is usually × 2
    Cache read (cache hit) input price × 0.1 Billed at one-tenth after a hit
    Minimum cacheable prefix usually ≥ 1024 tokens Short prompts don’t get the discount
    Output tokens no caching Always billed at full price

    The break-even point is easy to calculate: one write + one read = 1.25 + 0.1 = 1.35, which is already below the 2.0 you’d pay without caching (paying for the same content twice in full). In other words, write once and read once and you’ve broken even; read twice and you’re net ahead. For agent tasks that span dozens of turns, the cache hit rate often determines the order of magnitude of the bill.

    To capture this discount, the prefix must be byte-for-byte stable. Common “killers” include: prepending the current timestamp, a randomly sorted file list, or the session ID to the top of the system prompt; tweaking tool descriptions on every change; and inserting changing dynamic content after the fixed instructions. Any single change forces the cache to rebuild from scratch, which means repeatedly paying the 1.25× write cost.

    Another pitfall is cache expiry: if the gap between two requests exceeds the TTL (for example, no request within the 5-minute window), the cache is invalidated and the next turn has to write it again. So long thinking pauses, or resuming after the user steps away, all erode the discount.

    4. Third Account: Output — the Most Expensive, and Impossible to Cache

    Content the model generates (the body plus its thinking/reasoning) is billed at the output price and cannot be cached at all. Taking a common flagship model as an example, input is about $2 per million tokens and output is about $10 per million tokens—the output unit price is 5× the input price.

    This leads to two practical conclusions:

    1. Making the model “write more” is very expensive. Asking it to output entire files verbatim, explain line by line, or produce long summaries drives costs up sharply.
    2. In thinking mode, the reasoning process counts as output too. Deeper thinking can improve accuracy and reduce rework, but it’s a real expense and should be applied by task difficulty tier, not switched on globally.

    5. Combining the Three Accounts into One Estimation Model

    Units: tokens; prices are per million tokens.

    1. Total cost ≈ Σ_r [ (new input_r × write multiplier) + (hit prefix_r × read multiplier) ] × input price / 1e6
    2. + Σ_r (output_r) × output price / 1e6

    A rough estimation script (for capacity and budget planning):

    1. def estimate_cost(turns, base_ctx, growth, out_tokens,
    2. price_in=2.0, price_out=10.0,
    3. write_mult=1.25, read_mult=0.10):
    4. total, prev_ctx = 0.0, 0
    5. for r in range(turns):
    6. ctx = base_ctx + growth * r # Context size at turn r
    7. hit = min(prev_ctx, ctx) # Prefix that hits the cache
    8. fresh = ctx - hit # Part that needs a fresh write
    9. in_bill = fresh * write_mult + hit * read_mult
    10. total += in_bill * price_in / 1e6 + out_tokens * price_out / 1e6
    11. prev_ctx = ctx
    12. return total

    Move turns from 10 to 80 and set growth to a few thousand tokens, and you’ll see the quadratic growth on the input side directly—this is exactly the target for optimization.

    6. Six Cost-Reduction Techniques That Actually Work

    1. Stabilize the prefix (biggest payoff, lowest cost)
    Put the “unchanging things” first: system prompt → tool definitions → long-term standards → dynamic content. Never insert timestamps, random values, or dynamically sorted results into the stable prefix. Be aware that editing a tool description invalidates the entire prefix.

    1. def build_request(static_prefix: str, dynamic_suffix: str) -> list:
    2. # static_prefix must stay byte-for-byte identical within a session to hit the prefix cache
    3. return [
    4. {"role": "system", "content": static_prefix},
    5. {"role": "user", "content": dynamic_suffix},
    6. ]

    2. Retrieve instead of “stuffing everything in”
    Don’t paste the whole repository or an entire long log into the context just to “be safe.” Have tools read the relevant fragments on demand, or use keyword/semantic search to locate first and then read closely. Every thousand tokens in context get billed again on every subsequent turn.

    3. Compress tool return values
    Truncate, deduplicate, and structure command output, build logs, and search results before they enter the context: keep only error lines and key stack frames, keep only a change summary instead of the full text, return file paths instead of file contents. This is an underrated way to save, because tool output is often the main source of context bloat.

    4. Converge and isolate tasks promptly

    • One session handles one thing; start a new session when switching tasks to avoid letting unrelated history sit in context;
    • Delegate broad research and batch searches to subtasks or separate sessions, and bring only the conclusion summary back into the main context (the subtask’s context never enters the main loop, which is effectively a circuit breaker for cost);
    • Set an explicit maximum turn count and a max_tokens cap so runaway loops terminate at the budget level early.

    5. Tiered model routing
    Route requests by difficulty: send format conversion, field extraction, and simple Q&A to lightweight models; send architecture design, complex debugging, and cross-module refactoring to flagship models. At the same time, switch deep thinking on or off by task difficulty rather than enabling it globally. This is the only lever that touches the unit price, and its effect is usually more pronounced than squeezing tokens.

    6. Match the cache TTL
    For high-frequency back-to-back calls, you can opt for a longer TTL in exchange for a higher hit rate; for low-frequency interactions, there’s no need to pay the higher write multiplier for a long TTL. The rule of thumb is simple: compare the average interval between requests within a session against the expected idle time.

    7. You Can’t Save What You Can’t Measure

    Optimization without measurement is guesswork. At a minimum, collect the following dimensions and log the four token categories—input, cache write, cache read, and output—for each request:

    • Attribution by session/task: know which repository and which type of task burns the most money;
    • Cache hit rate: a low hit rate usually means an unstable prefix or an interval that exceeds the TTL;
    • Turn count and average context: these two metrics have a roughly quadratic relationship with cost and are the core early-warning signals;
    • Budget threshold alerts: set threshold notifications for the per-task token ceiling and cumulative daily spend.

    On the implementation side, unified instrumentation at the gateway, centralized log delivery, and feeding metrics into a monitoring-and-alerting system is enough to close the loop. Logging services, monitoring and alerting, and metrics dashboards of this kind are available in the LLM service and observability product suites of major cloud platforms (including Baidu AI Cloud) and can be reused directly, without building your own.

    8. Pre-Launch Self-Check List

    1. Are the system prompt and tool definitions byte-for-byte stable, with dynamic content moved to the end?
    2. Does the prefix length stay reliably above the minimum cache threshold (usually 1024 tokens)?
    3. Are tool return values truncated/structured rather than pasted in as-is?
    4. Have you set up subtask isolation and summary return for broad research?
    5. Are a maximum turn count, an output-length cap, and budget alerts configured?
    6. Have you implemented model tiering and deep-thinking tiers by task difficulty?
    7. Are tasks split by session to prevent history from accumulating without bound?

    Conclusion

    An AI coding tool’s bill isn’t mysterious—it equals “the input you repeatedly read + cached discounts + full-price output.” The genuinely effective optimization order is: first stabilize the prefix to capture the full caching discount, then compress the context to lower the per-turn baseline, then isolate tasks to hold down the turn count, and only then use model tiering to adjust the unit price. Get these four steps right and a long task’s cost can usually drop by an order of magnitude—but all of it starts with breaking the three accounts down clearly first.