AI Coding Assistants: How They Work and How Their Costs Are Calculated

    This article explains how AI coding assistants complete development tasks through model-driven execution loops, context management, tool use, and verification feedback. It also breaks down how such tasks generate multiple model requests and how to calculate costs across uncached input, output, cache reads, and cache writes. Readers will learn how to build unit-aware cost formulas, interpret gateway group multipliers and platform credits, log and reconcile billing records, and reduce costs without compromising engineering quality.

    AI coding assistants are often described as if they were standalone programs trained specifically to write code. In practice, most are task execution systems built around large language models. The model handles understanding and reasoning, while surrounding software manages context assembly, tool invocation, permission control, and feedback from execution results. Billing is mainly tied to model requests: input, output, cache usage, and the settlement rules of the service chain.

    To understand these systems, it helps to separate two related but distinct questions.

    1. Two Questions: How the Task Is Completed and How the Cost Is Calculated

    The first question is technical: How does the system read a project, understand a requirement, modify code, and continue working based on execution results?

    The second question is metering: How many model calls did these operations generate, which token categories were consumed, and what price and settlement rules were applied?

    Completing a coding task is not the same as making a single model call, and the total token count shown in a UI should not be treated directly as the final cost.

    2. Core Mechanism: The LLM-Driven Task Execution Loop

    2.1 From Natural-Language Requirements to Executable Steps

    When a user asks the assistant to fix an exception, add tests for a module, or explain a data flow in a project, the assistant must first understand the goal and constraints, then decide what information to obtain next.

    A typical process looks like this:

    User request → collect project context → model decides the next step → request a tool operation → execute the tool → return the result → decide again → produce a modification or conclusion.

    This process may repeat for multiple rounds. For example, the model may first request relevant files, then locate a function implementation, then propose a change, and finally use test results to judge whether the fix is effective.

    It is important to distinguish the model’s generated intent to perform an operation from actual execution. The model does not automatically run a test just because it outputs “run the tests.” An external execution component must recognize the request, check permissions, and actually invoke the corresponding capability.

    2.2 Context Management Determines What the Model Sees

    A model usually cannot read an entire project unconditionally in a single request. The surrounding system must select information relevant to the current task, such as:

    • The user requirement and earlier discussion of the task;
    • Relevant source files, configuration files, and interface definitions;
    • Symbol locations and reference relationships found through search;
    • Error information produced by builds, tests, or execution;
    • Project coding conventions and operational constraints;
    • Summaries of executed steps and their results.

    More context is not always better. Large amounts of irrelevant content increase input cost and may make it harder for the model to identify key constraints. Conversely, providing only a local code fragment while omitting callers, configuration, or test conditions may lead to incomplete conclusions.

    A more reasonable strategy is to read on demand: first identify the modules involved in the task, then add necessary dependencies; filter repeated logs, irrelevant files, and historical discussion; keep structured summaries for long tasks and allow original content to be reread when needed.

    Summaries also lose information, so a compressed description should not be treated as an absolute replacement for the source file.

    2.3 The Tool Layer Turns Suggestions into Operations

    Common tool capabilities include file reading, content search, file editing, diff display, and controlled command execution. These capabilities help the model verify its judgments, but they also introduce new risks.

    For example, reading files may expose sensitive configuration; editing may accidentally modify unrelated modules; command execution may delete files, access external networks, or change the runtime environment.

    The tool layer should therefore apply the principle of least privilege:

    • Limit the directories that can be accessed;
    • Authorize read-only and write operations separately;
    • Require human confirmation for high-risk execution;
    • Set execution timeouts and resource limits;
    • Record operation content, execution results, and error states;
    • Support restoration to the pre-change state through change records.

    Security controls should be enforced in the execution program, not left to the model to “remember not to perform dangerous operations.”

    2.4 Verification Results Create a Feedback Loop

    Generated code is only an intermediate product of the task. A reliable process also needs to check whether the modification meets the requirement, including syntax checks, build validation, targeted tests, and human review.

    If verification fails, the error information enters subsequent context, and the model adjusts the modification accordingly. This creates a loop of generate, execute, observe, and correct.

    However, passing tests only shows that the covered test conditions meet expectations; it does not prove that no other defects exist. Changes involving permissions, data consistency, concurrency behavior, or production environment configuration should still receive dedicated review.

    3. Why One Task Can Generate Multiple Model Charges

    A seemingly simple fix may go through requirement analysis, file location, code generation, test analysis, and result summarization. Each stage may initiate an independent model request.

    If a task contains n model calls, the total model-side cost can be expressed as:

    Task model cost = cost of request 1 + cost of request 2 + … + cost of request n.

    Later requests often need to carry part of the previous conversation, tool results, and current code. Therefore, task cost does not come only from the length of the final code output.

    Common reasons for cost growth include:

    • Repeatedly sending long project instructions;
    • Sending complete logs as input instead of filtering key errors;
    • Repeatedly modifying and verifying after multiple failures;
    • Requesting excessively long explanations or large-scale rewrites;
    • Continuing an automatic loop when the task already lacks necessary information.

    Cost analysis should treat the complete task as the unit while retaining per-request records. Only then can you identify whether the cause is oversized context, excessive output, or too many retries.

    4. The Metering Relationship Among Four Token Categories

    In services that support prompt caching, usage may be recorded under categories such as uncached input, output, cache reads, and cache writes. Actual fields and statistical definitions may differ between services, so the relevant documentation must be checked before reconciliation.

    4.1 Uncached Input

    This category usually refers to content that is not reused through cache and must be processed through the normal input path. User questions, newly added code fragments, and new tool results may all fall into this category.

    4.2 Output

    Output is content generated by the model. It may include explanations, code, and tool operation requests. Which generated content is included in the bill should be determined by the service’s usage definitions.

    4.3 Cache Reads

    When a request meets the conditions for cache reuse, part of the input may be metered as cache reads. Long, stable project specifications, tool instructions, or shared context may be suitable for reuse.

    Caching does not mean input no longer incurs cost, nor does it mean any similar content will hit the cache. Cache hits are usually affected by content consistency, validity periods, and service implementation.

    4.4 Cache Writes

    Cache writes correspond to the process of creating or updating reusable input content. Different caching strategies may use different pricing methods, and it should not be assumed that all write operations use the same price.

    In particular, avoid double counting: if a usage field already includes the cache portion, the cache quantity must not be added to the cost formula again without splitting it out first.

    5. Build a Cost Formula with Clear Units

    Assume a service records the four usage categories independently, and all prices are in “currency units per million tokens.” The base cost of one request is:

    Base cost = (uncached input × input price + output × output price + cache read × read price + cache write × write price) ÷ 1,000,000.

    Dividing by one million is a necessary unit conversion. If prices are listed per million tokens but the raw token count is multiplied by the price directly, the result will be off by orders of magnitude.

    The following is only a demonstration of the calculation method and does not represent the price of any real model or platform:

    Category Usage Assumed price per million tokens
    Uncached input 20,000 3
    Output 4,000 15
    Cache read 100,000 0.3
    Cache write 10,000 3.75

    The four costs are 0.06, 0.06, 0.03, and 0.0375, for a total base cost of 0.1875 currency units.

    This example shows that the category with the largest token count is not necessarily the largest cost contributor. When comparing costs, both the usage structure and the per-category prices must be considered.

    6. How Relay Gateway Group Multipliers Affect Settlement

    In one common forwarding settlement model, the gateway first calculates the request cost based on an agreed base price, then multiplies it by the multiplier of the group associated with the access credential:

    Settlement amount = base cost × group multiplier.

    Under this model, if two requests use the same model, the same actual route, and the same metering rules, and all four usage categories are identical, the group difference is mainly reflected in the final multiplier.

    This conclusion should not be extended into a universal rule for all services. Different gateways may also use independent price tables, additional fees, minimum charges, or different rounding methods. Whether such mechanisms exist should be determined from the actual settlement rules.

    More importantly, a group may affect not only price but also model access permissions and request routing. Therefore, the following should be confirmed separately:

    1. Whether the group allows access to the target model;
    2. Whether the request is actually routed to the expected model;
    3. Which price table and multiplier are used;
    4. Whether there is explicitly configured fallback behavior.

    Access failure does not equal automatic model switching. Whether fallback occurs must be determined by routing configuration and should not be inferred from the group name shown in a UI.

    7. Display Prices, Platform Credits, and Actual Currency Are Not the Same Thing

    Numbers on a pricing page may have different meanings:

    • A base unit price before multipliers;
    • An effective unit price after a group multiplier has been applied;
    • A displayed price for a default group;
    • A value corresponding to a platform’s internal credit unit.

    If the displayed price already includes the multiplier, applying the multiplier again will cause double counting.

    Likewise, a currency symbol before a credit amount does not by itself prove that it is equivalent to cash in that currency. Internal points, prepaid credits, and actual payment amounts may also involve recharge ratios, bonus credits, or other settlement arrangements.

    When comparing across channels, first normalize everything to the same actual currency, then compare costs under the same model, same request volume, and same cache conditions. Do not directly compare the numeric values shown on two pages.

    8. How Developers Should Log and Reconcile Bills

    It is advisable to record “task,” “logical request,” and “actual invocation attempt” at separate layers. A single logical request may produce multiple attempts due to timeouts or failures, and recording only the final result visible to the user can easily miss intermediate consumption.

    At minimum, retain the following information for each invocation:

    • Request identifier, task identifier, and timestamp;
    • Requested model and actual routing information;
    • Access group and the multiplier in effect at the time;
    • The four usage categories and their statistical definitions;
    • Effective prices and billing units;
    • Base cost and final deducted amount;
    • Request status, retry information, and rounding rules.

    Amount calculations should use precise decimal representations or integer minor units to avoid long-term accumulation of binary floating-point errors. Price and multiplier snapshots should be retained; otherwise, after later price changes, old bills cannot be accurately recalculated.

    When a discrepancy occurs, investigate in the order of “usage definition — price version — multiplier — unit conversion — rounding — retry” rather than checking only the total token count.

    9. Reduce Costs While Maintaining Engineering Quality

    Optimizing AI coding tasks should not focus only on a lower price per request.

    First, reduce invalid input. Provide only relevant code and necessary logs, and avoid repeatedly sending the entire project. Second, split large tasks into steps with clear boundaries so that each modification is easy to verify and roll back.

    Third, control execution loops. Set task budgets, maximum attempt counts, and conditions for human intervention. If repeated failures come from missing configuration or unclear requirements, add information instead of continuing to consume requests.

    Finally, choose an appropriate capability level for the task. Local formatting adjustments and complex architecture analysis place different demands on model capability. What is truly worth measuring is the total cost of completing a verifiable task, not merely the price per million tokens.

    The value of AI coding assistants comes from combining model understanding with an engineering execution system. By designing context, tool permissions, verification feedback, and cost accounting together, a system can do more than generate code: it can complete development tasks in a controlled and traceable way.