How AI Coding Tools Work and How Token Billing Is Calculated

    This article explains how AI coding tools are architected and how their usage is billed. It breaks billing into two separate stages—metering and pricing—and shows that the final charge equals the estimated cost at official rates multiplied by the rate multiplier of the key's access group. It walks through the main layers of an agentic coding tool, the four token categories used in usage reports, the base-cost estimation formula, and how group multipliers are the sole source of price differences across groups. It also highlights commonly misread details and ends with a practical checklist for cost governance.

    How AI Coding Tools Work and How Token Billing Is Calculated

    Start With the Key Point: Metering and Pricing Are Two Different Things

    Almost every developer asks the same question the first time they look at a bill: why does the same number of conversation turns, with a similar context length, deduct a noticeably different amount of quota after switching to another access group? The answer has nothing to do with the model itself. It lies in two independent stages of the billing pipeline.

    The first stage is metering. No matter which group a request finally lands in, the model splits input and output tokens the same way, and the usage figures returned in the response follow exactly the same convention. The second stage is pricing. The relay gateway first converts the request into a base amount using the upstream official price, then multiplies it by the rate multiplier of the group the current key belongs to. The product is the quota actually deducted from the account balance.

    In one sentence: charge = estimated cost at official rates × group multiplier. So as long as you have two numbers—the cost estimated at official rates for this request, and the multiplier of the group your key belongs to—you can calculate the bill with reasonable accuracy. This also means the key action in cost governance is not guessing model behavior, but knowing exactly which billing group you are in.

    How AI Coding Tools Work: It Is Not “One Model”

    Thinking of an AI coding tool as “a large model hanging behind a chat window” is a common misconception. From an engineering perspective, it is closer to an agentic execution framework with the model as its inference core, usually made up of the following layers.

    1. Context Assembly Layer

    The tool trims and assembles materials such as the system prompt, project structure information, the currently open file, the cursor selection, and the conversation history into the context of a single request. Because the context window is limited, the assembly layer must decide “what to keep and what to drop,” which directly determines the size of the input tokens.

    2. Tool-Calling and Loop Layer

    The model does not read or write to disk directly. Instead, it outputs structured tool-call intents, such as reading a file, searching for a symbol, executing a command, or making an edit. The outer runtime validates permissions, performs the action, feeds the result back into the context, and then enters the next round of inference. A single user question often maps to multiple model calls, which is the main reason token consumption multiplies.

    3. Prompt Caching Layer

    To reduce the overhead of repeated prefixes, the industry commonly uses a prompt caching mechanism: stable, unchanging prefixes (system prompts, repository descriptions, and so on) are cached and reused by subsequent requests. Caching introduces two new metering items—cache reads and cache writes—whose unit prices differ from regular input.

    4. Session and Permission Layer

    This includes workspace boundary control, command allowlists, and confirmation of sensitive operations. This layer produces no tokens, but it determines whether the tool can actually be used in a production project.

    Once you understand this structure, it becomes clear that cost optimization starts with “reducing wasted rounds, compressing context, and improving cache hit rates,” rather than agonizing over the wording of a single question.

    The Four Token Categories and the Official-Rate Estimation Formula

    The usage information returned each turn usually contains four counts: non-cached input, output, cache reads, and cache writes. Each has its own unit price (priced per million tokens). From this we can write the base-cost formula:

    1. base cost = non-cached input × input unit price
    2. + output × output unit price
    3. + cache reads × cache-read unit price
    4. + cache writes × cache-write unit price
    5. quota deducted = base cost × group multiplier

    An illustrative calculation (unit prices are sample values, used only to show the dimensions):

    1. def estimate_cost(inp, out, cache_read, cache_write, ratio,
    2. p_in=4.0, p_out=20.0, p_cr=0.2, p_cw=4.0):
    3. """Estimate deducted quota using unit prices per million tokens"""
    4. base = (inp / 1e6 * p_in + out / 1e6 * p_out
    5. + cache_read / 1e6 * p_cr + cache_write / 1e6 * p_cw)
    6. return base * ratio

    It is worth stressing that cache writes are usually more expensive than cache reads, but once a cache hit occurs, the read cost in subsequent rounds is significantly lower than regular input. So the “cache hit rate” is the metric most worth monitoring in long-session scenarios.

    Group Multipliers: The Only Source of Bill Differences

    The billing model of a relay gateway can be abstracted as a two-dimensional table: rows are models, columns are groups, and each cell is “official price × that group’s multiplier.” Different groups correspond to different resource pools, concurrency quotas, and service levels, and the multipliers vary accordingly. A common industry tiering looks roughly like this (multipliers are illustrative; the values published by the platform on the day prevail):

    Group type Multiplier characteristic Typical positioning
    Lightweight/promotional group Less than 1 Quota from specific sources or promotions
    Subscription-plan group About 2x Dedicated resource pool for subscription plans
    Official-key stable group 3x or more Stable channel with direct official keys
    Enterprise group Custom High concurrency, dedicated quota

    Three engineering conclusions you must remember:

    • The multiplier is applied on top of the official price, not as a replacement for it;
    • The multiplier changes with resource supply, so check the value published on the day before use;
    • The model lists of different groups are not the same. Calling a model that does not exist in the group throws an error directly, and the system will not automatically charge you under another group instead.

    Three Details That Are Easiest to Misread

    1. The Default “All” View Is Not the Official Price

    When no group is explicitly selected, the interface often displays prices at some default multiplier, so the same model shows up at twice the official price. Select the group your key belongs to before checking prices; otherwise your estimate will be systematically too high or too low.

    2. Platform Quota Units Are Not Real Currency

    Some platforms use a 1:1 conversion between RMB and quota, so the “$” on the account actually corresponds to an equal amount of RMB balance. When comparing against direct official USD quotes, you must do a currency conversion first; otherwise the comparison is completely distorted.

    3. Model Availability Is Constrained by Group

    The group affects not only price but also the range of available models. Production scripts should explicitly declare the target model and group, and handle errors like “model unavailable” as a fallback, to avoid a task failing midway through a batch run.

    A Practical Checklist for Cost Governance

    1. Set the group first, then talk about optimization: write the key-to-group mapping into your configuration to avoid bill drift caused by switching on the fly.
    2. Monitor the four token categories: pay special attention to the share of cache reads; a share that is too low indicates an unstable prefix or sessions being rebuilt frequently.
    3. Compress context: merging small questions, cleaning up irrelevant files, and switching long documents to on-demand retrieval can lower both input and output costs at the same time.
    4. Control agentic rounds: set a maximum number of rounds and a timeout for tool calls to prevent loop-style inference from amplifying consumption.
    5. Establish a reconciliation basis: use “official-rate estimate × multiplier” for local estimation, compare it periodically against the bill, and investigate usage statistics only when the gap widens.
    6. Abstract the access layer: add an adapter between business code and the model channel, making model names, groups, and unit prices configurable for easier migration and load testing.

    Conclusion

    The capability of an AI coding tool comes from the combination of “model inference + tool execution + context engineering,” while bill differences come almost entirely from the single multiplier of the group. By separating metering from pricing, estimating locally with a unified formula, and combining it with cache hit rate and round control, you can turn cost from “a surprise after the fact” into “something calculable in advance.” For more complete engineering implementation, you can build observability and quota systems on top of general capabilities such as container platforms, log services, and monitoring and alerting offered by Baidu AI Cloud.