LLM API Cost Estimation and Coding Agent Practices

    This article breaks down the cost structure of token-based LLM APIs and explains how to build a predictable, constrained, and fallback-ready cost engineering system for Coding Agents. It covers context budgeting, retrieval strategies, structured output constraints, tiered model routing, budget guardrails, and evaluation loops, with practical formulas and pseudocode to help developers control long-term API spending.

    1. Why Developers Need to Recalculate API Costs

    Over the past year or two, LLM service pricing has changed more frequently, with limited-time discounts, tiered pricing, and cache discounts appearing constantly. For teams, the real risk is not a high unit price but unpredictable costs: a prototype that looks cheap can quickly become expensive once it is connected to a real codebase and real user traffic.

    As developers, we usually worry about two things:

    • Capability fluctuations: the same prompt may work well today and produce lower-quality output tomorrow, making downstream workflows unstable.
    • Price fluctuations: once a workflow is working, a change in billing rules or discounts can immediately invalidate the budget model.

    Therefore, the goal of model selection should not be “find the cheapest model,” but to build a measurable, constrained, and fallback-ready cost engineering system. This article uses “running a stable Coding Agent at low cost” as the main thread and discusses general methodology and practical engineering details.

    2. Cost Model: Break the Bill into Computable Variables

    Setting aside marketing language, the cost of a single call to any token-based model service can be abstracted as follows:

    1. Cost per call = Input tokens × Input price
    2. + Output tokens × Output price
    3. + Cached tokens × Cache price
    4. + Repeated context that misses the cache × Input price

    The third and fourth items are the most easily underestimated. Coding tools typically have long contexts, multi-turn calls, and highly repeated prefixes: system prompts, tool definitions, repository retrieval snippets, and conversation history remain almost unchanged in every turn. This means:

    1. If the platform supports prefix caching (a common industry capability; refer to each platform’s documentation for billing details), repeated prefixes can be billed at a lower price.
    2. If the cache is missed, the same content is billed at full input price in every turn, and costs grow roughly linearly with the number of turns.

    An Illustrative Calculation

    Assume a task requires about 500,000 tokens of context input and about 20,000 tokens of output. Using symbolic prices (in CNY per 1,000 tokens):

    1. No discount: 0.5 × P_in + 0.02 × P_out
    2. With discount (50% off): 0.5 × (P_in × 0.5) + 0.02 × (P_out × 0.5) = 50% of the original cost

    The conclusion is simple: discounts only change coefficients, not structure. What really determines the long-term bill is the “input-to-output ratio” and the “proportion of repeated context.” Therefore, the optimization order should be: first compress invalid context, then discuss unit prices.

    3. Context Budget: The First Principle of Coding Agents

    A 1M-level ultra-long context window is indeed essential for code-related tasks, but “can be stuffed in” does not mean “should be stuffed in.” It is recommended to introduce a context budget table and manage the window as a limited resource:

    Component Suggested Share Description
    System instructions and tool definitions 5%–10% Keep stable to improve cache hit rate
    Retrieved relevant code 40%–55% Determined by retrieval strategy; requires deduplication and trimming
    Dialogue and intermediate conclusions 20%–30% Summarize and compress periodically
    Output reserve 15%–25% Avoid truncation that causes rework

    Recommended retrieval strategies:

    • Locate first, then expand: first use file names, symbol names, and call relationships for coarse filtering, then read candidate files in detail.
    • Slice by symbol: split by function or class, with signatures and dependencies attached, instead of stuffing entire files.
    • Deduplication and fallback: keep only one copy of duplicate snippets; when retrieval returns nothing, fall back to keyword search instead of enlarging the window.

    Illustrative pseudocode:

    1. def build_context(query, repo_index, budget):
    2. plan = rough_locate(query, repo_index) # Coarse-filter candidates
    3. chunks = [read_symbol(c) for c in plan]
    4. chunks = dedup_and_rank(chunks, query)
    5. ctx, used = [], 0
    6. for c in chunks:
    7. if used + c.tokens > budget.content:
    8. break
    9. ctx.append(c); used += c.tokens
    10. return assemble(system_prompt(), ctx, budget.output_reserve)

    4. Stability Design: Making Output “Parseable” Matters More Than “Smarter”

    Cost overruns often come from rework. Improving the first-pass success rate is equivalent to directly lowering the price. Four general methods:

    1. Structured output constraints: require strict JSON structures with fixed fields and null for missing values, avoiding free-text parsing.
    2. Minimize tool calls: split “read files, retrieve, run tests” into explicit tools to reduce the model’s guessing space.
    3. Capped validation and retries: when parsing fails or tests fail, retry with error information, and fall back to manual handling after at most N attempts.
    4. Prioritize determinism: commands involving build and test should be executed by programs, while the model is only responsible for generation and explanation.
    1. {
    2. "files": [{"path": "src/a.py", "action": "modify", "reason": "..."}],
    3. "diff_summary": "...",
    4. "tests_to_run": ["pytest -q tests/test_a.py"],
    5. "risk": "low|medium|high"
    6. }

    5. Tiered Routing and Budget Guardrails

    Assigning tasks of different difficulty to models with different capabilities and price levels is the most effective structural means of cost control:

    • L1 lightweight tier: formatting, comments, and small single-file changes, using low-cost general model capabilities.
    • L2 main tier: cross-file modifications and defect localization, using models with stronger general capabilities.
    • L3 review tier: review of high-risk changes, only performing small-sample review on the diff.

    Set guardrails at the same time:

    1. if estimated cost > per-task limit: shrink context or split subtasks
    2. if daily cumulative cost > threshold: switch to L1 and alert
    3. if cache hit rate < target: check whether the system prompt is frequently changed

    Among these, “keeping the system prompt stable” is the key to improving the cache hit rate—any timestamp or random ID written into the prefix will invalidate the cache.

    6. Evaluation Loop: Replace Feelings with Data

    Optimization without evaluation is guesswork. It is recommended to maintain a small regression set of 50–200 cases covering single-file modification, cross-file refactoring, defect localization, test generation, and long-context retrieval. Run it after each prompt or model configuration adjustment, and record three metrics:

    • First-pass success rate (completed without manual intervention)
    • Average token consumption (input/output/cache counted separately)
    • End-to-end latency

    Using “pass rate ÷ average cost” as the core metric allows intuitive comparison of different configurations and quick judgment of whether it remains cost-effective after the discount period ends.

    7. Common Pitfalls

    • Only looking at unit price, not structure: in scenarios with a high input proportion, small differences in input unit price are amplified.
    • Blindly stuffing the context: increased noise leads to lower output quality and higher total costs.
    • Ignoring cache invalidation: an unstable prefix completely nullifies cache optimization.
    • Lacking fallback paths: without L1 downgrade and manual takeover, abnormal tasks will keep burning budget.
    • Writing limited-time discounts into long-term budgets: discounts are variables; architecture is the constant.

    8. Summary

    Running a stable Coding Agent at low cost essentially comes down to three things: manage context as a budget, constrain output as an interface, and monitor cost as a metric. Unit prices and discounts will change, but cost structure, cache hit rate, and first-pass success rate can be continuously improved through engineering. Get these three solid first, then talk about model selection, and the bill will naturally be under control.