How to Calculate LLM API Costs: A Practical Guide for Deploying Coding Agents

    A practical guide to estimating LLM API costs for coding agents. It covers billing structure, prompt caching, multi-turn agent usage, model evaluation metrics, and the steps to build a low-cost, secure coding agent prototype.

    1. Why Developers Are Watching LLM API Bills Closely

    Over the past year, several vendors have cut the prices of their LLM APIs. Lower prices let developers use LLMs more freely in real workloads, without recalculating the cost of every debugging session.

    Lower prices also raise new questions. Is the output quality stable on a low-cost plan? Can the cost of long contexts be controlled? Will prices go up when a limited-time discount ends? If an automated workflow exceeds its budget overnight, the original cost estimate no longer means anything.

    When choosing an API model, you therefore need to weigh two things: cost you can control, and capability that is reliable enough. This is both a technology selection decision and a question of engineering effort and long-term maintenance cost.

    This article focuses on text and code models for coding assistance. Multimodal inputs such as images, audio, and video are billed differently and are not covered here.

    2. How to Calculate Cost: Billing Structure and Scope

    Many people estimate API costs by multiplying the input price by the input volume and adding the output price times the output volume. This method gives a rough figure, but it misses several common charges, so the budget ends up too low.

    The cost of a single call usually consists of the following parts:

    1. Input cost: The number of tokens sent to the model, including the system prompt, conversation history, and context files.
    2. Output cost: The number of tokens the model uses to generate its response.
    3. Cache read cost: If the provider supports prompt caching, input tokens that hit the cache are usually billed at a much lower rate than standard input tokens.

    The example below shows how the calculation works. The prices are fictional and are used only to demonstrate the logic. They do not reflect the actual pricing of any real platform.

    • Input: 0.8 CNY per million tokens (original price), 0.4 CNY per million tokens (limited-time discount)
    • Output: 2.8 CNY per million tokens (original price), 1.4 CNY per million tokens (limited-time discount)
    • Cache read: 0.23 CNY per million tokens (original price), 0.115 CNY per million tokens (limited-time discount)

    Assume you are analyzing a medium-sized code repository. A single call sends about 500,000 input tokens and generates about 20,000 output tokens of modification suggestions and code snippets.

    No cache, before discount:
    (0.5 × 0.8) + (0.02 × 2.8) = 0.4 + 0.056 = 0.456 CNY

    No cache, after discount:
    (0.5 × 0.4) + (0.02 × 1.4) = 0.2 + 0.028 = 0.228 CNY

    With cache, after discount: Assume 400,000 of the 500,000 input tokens hit the cache, and the remaining 100,000 do not.
    (0.4 × 0.115) + (0.1 × 0.4) + (0.02 × 1.4) = 0.046 + 0.04 + 0.028 = 0.114 CNY

    The higher the cache hit rate, the lower the input cost. Cache hits depend on an exact prefix match. If the beginning of the system prompt or project context includes content that changes on every call, such as timestamps or random IDs, the cache will not hit.

    The example above covers only a single call. Real agent tasks often require multiple calls. Each round resends the conversation history and tool results to the model, so input tokens accumulate with every round. Suppose a task takes 10 rounds, and each round carries about 500,000 tokens of context. The total input is about 5 million tokens. At the discounted price, input alone costs about 2 CNY, roughly 10 times the input cost of a single call.

    You also need to state what the estimate excludes. The figures above do not include:

    • Charges for repeated calls caused by failed retries
    • Extra tokens from tool results added back into the context
    • Infrastructure costs such as networking, storage, and logging
    • Labor costs for development and maintenance

    At 0.228 CNY per call and 1,000 calls per month, the model cost is about 228 CNY. This figure covers only the model calls themselves. It does not replace a development labor budget, and it does not prove that such a project is worth the investment.

    3. Selection Metrics: Test Them Yourself Instead of Trusting Marketing

    Price matters, but model capability determines whether a model is fit for production. For coding agents, the metrics below are most closely tied to actual performance. Measure each one with your own samples rather than relying on published claims.

    Metric What to check How to test Reference criteria
    Context window Whether key information in long text can be recalled correctly Place function definitions at different positions in a long text, then ask about their call relationships Whether the recall accuracy meets the threshold your team sets
    Tool calling Whether the model selects the right tool, fills in correct parameters, and calls tools in the right order Prepare hundreds of task cases and measure tool selection and parameter accuracy Tool selection accuracy, valid parameter rate, and task completion rate
    Response latency Time to first token and total response time Record time to first token and total time across many requests, then calculate the median and the 95th percentile Whether the 95th percentile latency is within an acceptable range
    Effective unit price Whether actual billing matches the listed price Calculate costs from the actual token usage on your bill Whether the deviation from the estimate is within an acceptable range

    Two points matter for the context window. First, a longer window means higher input costs. Putting an entire repository into the prompt is convenient, but you pay for every one of those tokens on every call. Second, a large window does not guarantee that the model uses information at every position accurately. Content in the middle of a long text is especially likely to be overlooked, so test this directly.

    For tool calling, common mistakes include giving a conclusion directly when a tool call is needed, reading files repeatedly when they are not needed, and passing parameters of the wrong type so that execution fails. Test cases should cover these failure modes, not just the normal path.

    Mixture of Experts (MoE) architectures activate only some expert parameters for each token through sparse activation. This usually reduces the compute per token. However, lower compute does not guarantee a lower price. Pricing also depends on the provider’s cost strategy, promotions, and quota policies. Your bill is the final reference.

    4. From Prototype to Deployment: Building a Low-Cost Coding Agent

    If the analysis above suggests that a model is worth trying, you can build a prototype by following the steps below. The example scenario is refactoring an automation script. The goal is to run a reliable coding agent at low cost.

    Step 1: Define the Agent’s Responsibilities

    Before you start, write down what the agent should do. Typical responsibilities include:

    • Locate: Based on a natural-language instruction or bug description, find the relevant files and functions.
    • Analyze: Understand the existing code logic and propose a modification plan.
    • Execute: Modify files and attach a description of the changes.
    • Verify: Run the relevant tests and check whether the changes introduce regressions.

    Start with single-file tasks, then expand to multi-file and module-level tasks. If the agent is asked to refactor an entire module from the start, it is hard to locate the cause when a task fails.

    Step 2: Design the Prompt and Cache Prefix

    Place the fixed content at the beginning of the prompt, including the system prompt and the core structure of the project. This content is what gets cached. Put the dynamic user instruction at the end.

    1. [System prompt]
    2. You are a rigorous Python code review and modification assistant. Your task is to locate issues in the given project context and generate a modification plan based on the user's description. Every change must consider its impact on other modules.
    3. [Project context, fixed content, placed at the prefix]
    4. (Core file tree, key variable definitions, interface descriptions)
    5. [User instruction, changes on every call, placed at the end]
    6. Refactor the URL extraction function in src/utils/string_helper.py so it supports links that include authentication information, and add unit tests for the new logic.

    Step 3: The Function Calling Loop

    The example below uses a Python SDK compatible with the OpenAI Chat Completions interface. It requires the openai library version 1.x and Python 3.10 or later. If your provider uses a different interface format, adjust the field names according to its documentation.

    The example has three key points. First, the assistant message must keep its tool_calls field intact. Otherwise, the subsequent tool messages cannot be matched to it. Second, each tool message must be linked to its corresponding call through tool_call_id, one to one. Third, tool output must be truncated so that long results do not make input costs spiral.

    1. import json
    2. import os
    3. from openai import OpenAI
    4. client = OpenAI(
    5. api_key=os.environ["LLM_API_KEY"], # Read the key from an environment variable; do not hard-code it
    6. base_url=os.environ["LLM_BASE_URL"],
    7. )
    8. MAX_TURNS = 10 # Maximum turns, to prevent infinite loops
    9. MAX_TOOL_OUTPUT = 4000 # Maximum characters per tool output
    10. def run_agent(user_task: str, context: str) -> str:
    11. messages = [
    12. {"role": "system", "content": SYSTEM_PROMPT},
    13. {"role": "user", "content": f"{context}\n\n{user_task}"},
    14. ]
    15. for _ in range(MAX_TURNS):
    16. resp = client.chat.completions.create(
    17. model=CHEAP_MODEL,
    18. messages=messages,
    19. tools=TOOL_DEFINITIONS,
    20. )
    21. msg = resp.choices[0].message
    22. # Keep the full assistant message structure, including tool_calls
    23. messages.append(msg.model_dump(exclude_none=True))
    24. if not msg.tool_calls:
    25. return msg.content or ""
    26. for call in msg.tool_calls:
    27. try:
    28. args = json.loads(call.function.arguments)
    29. result = execute_tool(call.function.name, args) # Whitelist validation inside
    30. except Exception as e:
    31. result = f"Tool execution failed: {e}"
    32. messages.append({
    33. "role": "tool",
    34. "tool_call_id": call.id, # Must match the corresponding tool_call
    35. "content": str(result)[:MAX_TOOL_OUTPUT],
    36. })
    37. raise RuntimeError("Maximum turns exceeded, task aborted")

    SYSTEM_PROMPT, CHEAP_MODEL, TOOL_DEFINITIONS, and execute_tool must be implemented for your specific project.

    Step 4: Security Boundaries

    An agent that can read and write files and run commands needs tight permissions. Follow these practices:

    • Command allowlist: Allow only fixed commands such as running tests or formatting code. Do not expose an arbitrary shell.
    • Sandboxed execution: Run tools in a container or isolated environment, with external network access disabled by default.
    • File permissions: Limit write access to the project directory. Block changes to .env files, key files, and CI configuration.
    • Redaction of sensitive data: Filter passwords, tokens, and internal domain names before sending any context.
    • Human review: Require manual review before changes are merged into the main branch or deployed.
    • Version control: Have the agent work on a separate branch. If a run fails, you can discard the branch without overwriting the existing code.

    Step 5: Stability and Cost Monitoring

    To keep the agent stable during overnight batch runs, set up the following mechanisms:

    • Timeouts and retries: Set the timeout for each request to 60 seconds. When you encounter network fluctuations or service overload, retry with exponential backoff, up to 3 times, and add random jitter to each wait time.
    • Structured output validation: Require the model to return modification suggestions in JSON format, and validate the fields with a local parser. If validation fails, retry once. If it still fails, log the error and mark the task as failed.
    • Circuit breaker rules: If the agent fails 5 times in a row, or if the daily cost exceeds a preset threshold, pause the task immediately and notify the person responsible.
    • Usage logging: After each call, read the usage fields in the response and record the input, output, and cache-hit token counts for each session. Field names differ between providers, so check their documentation.

    Common Troubleshooting

    • Tool parameter parsing failures: Check that the tool’s JSON Schema matches the actual parameters, and include an example of one correct call in the prompt.
    • Task does not terminate: Check whether a maximum turn limit is set.