Token Cost Accounting for LLMs: A Cost Modeling Approach for Multi-Model Routing

    This article explores how to accurately account for and optimize Token costs when working with Large Language Models (LLMs). It breaks down billing dimensions such as input, output, and cache-hit tokens, and introduces a linear regression method to reverse-engineer consumption coefficients from actual usage logs. Additionally, it covers capacity planning based on quotas, a multi-tier model routing strategy for cost optimization, engineering-level cost reduction techniques, and continuous monitoring practices.

    1. Why Token Cost Accounting is Necessary

    Large Language Model (LLM) API calls are typically metered by Token. For the same type of task, input length, output length, and whether a cache is hit can cause the final cost to differ by several times. Many teams only focus on the unit price of the model, ignoring the actual consumption structure, which often leads to budget overruns.

    Cost accounting must answer three questions: what components make up the cost of each call type; how much business volume the current quota can support; and to what extent costs can be compressed without degrading result quality. The answers to these three questions dictate model selection and call strategy design.

    2. Breaking Down Billing Dimensions

    Common billing structures usually include the following categories:

    • Input Tokens: System prompts, user input, retrieved context, and historical conversations. The longer the input, the more consumed per call.
    • Output Tokens: Content generated by the model. The generation process requires decoding token-by-token, so the output unit price is usually higher than the input unit price. Controlling output length is often the most effective way to reduce costs.
    • Cache Hit Tokens: When the request prefix matches a historical request and the server can reuse the previously computed intermediate results, this part of the input is billed at a lower unit price.
    • Periodic Quota: Quotas are issued by time windows (e.g., fixed hours or weekly) and may be represented as unified metering credits rather than direct monetary amounts.

    By understanding these four dimensions, each call can be formulated as a consumption function composed of various sub-items, rather than just looking at a single total price.

    3. Reverse-Engineering Consumption Coefficients from Usage Logs

    The publicly available price lists from service providers may not exactly correspond to the actual credits deducted from your account. In such cases, you can use your own usage logs to reverse-engineer the consumption coefficients. The method is as follows:

    3.1 Data Collection

    Record three data points per request or statistical period: the number of Input Tokens, the number of Output Tokens, the number of Cache Hit Tokens, and the credits deducted during the same period. The finer the statistical period and the larger the sample size, the more reliable the fitting results.

    3.2 Establishing a Linear Model

    Assume that the deducted credits have an approximate linear relationship with the three types of token counts, i.e.:

    Credits ≈ a × Input Tokens + b × Output Tokens + c × Cache Hit Tokens

    Where a, b, and c are the consumption coefficients for the three token types. By arranging multiple samples into a matrix form, you can solve it using the least squares method.

    3.3 Pseudocode for Solving

    1. Input: Sample matrix X (n rows × 3 columns), each row is [Input Token count, Output Token count, Cache Hit Token count]
    2. Input: Observed credit vector y (n rows × 1 column)
    3. 1. Construct normal equations: A = Xᵀ·X, b = Xᵀ·y
    4. 2. Check if A is nearly singular. If the three columns are linearly dependent, it means the ratio of input, output, and cache in the samples is almost constant. In this case, supplement with request samples of different structures before continuing.
    5. 3. Solve A·β = b to get β = [a, b, c]
    6. 4. Calculate predicted values ŷ = X·β
    7. 5. Calculate coefficient of determination R² = 1 − Σ(y − ŷ)² / Σ(y − ȳ)²
    8. 6. Perform holdout validation using new time period data not involved in fitting, and compare prediction errors

    3.4 Interpreting Results with Caution

    An R² close to 1 only indicates that the model can explain the existing samples; it does not prove it is the actual billing rule. The following situations can cause artificially high fitting results:

    • The sample size is far less than the number of parameters, making the model prone to overfitting.
    • Different request types are highly similar in structure, leading to strong correlations between variables.
    • Non-linear rules exist in billing, such as minimum deductions, rounding, or concurrency discounts, which linear models cannot express.

    Therefore, the fitting results should be treated as estimates and calibrated regularly with new data. If the billing rules change, re-fitting is required.

    4. Converting Quotas into Usable Capacity

    Once the consumption coefficients are obtained, you can estimate the business volume that a quota can support. Let the quota in a time window be Q, the input unit price be p_in, and the output unit price be p_out (in credits per 1,000 tokens). If the input accounts for a proportion r of the total tokens, the total number of tokens that can be processed is:

    T = Q ÷ (r × p_in + (1 − r) × p_out)

    The following example uses hypothetical unit prices (Input 1, Output 5) solely to illustrate the impact of ratio changes and does not represent any actual billing data. The quota Q is set to 60,000.

    Input Ratio r Output Ratio Average Credits per Token Processable Tokens (Approx.)
    80% 20% 1.8 33,000,000
    50% 50% 3.0 20,000,000
    20% 80% 4.2 14,300,000

    The results show that with the same quota, increasing the output ratio from 20% to 80% reduces the number of processable tokens by more than half. Therefore, during business design, you must first estimate the input-output ratio before deciding on capacity planning. If the system can heavily hit the cache, cache tokens must also be incorporated into the formula separately.

    5. Allocating Model Tiers by Task Complexity

    The core idea of cost control is: let high-capability, high-priced models handle a small number of critical judgments, while low-priced, fast models handle large volumes of repetitive executions. Below is a common four-tier division:

    5.1 Planning and Review Layer

    Responsible for task decomposition, plan review, and final quality control. These calls are infrequent but require long context, and the quality of judgment directly impacts all subsequent steps.

    5.2 Reasoning Layer

    Responsible for multi-step deduction, complex logic analysis, and large-scale code modifications. The call volume is medium, with high requirements for accuracy.

    5.3 Execution Layer

    Responsible for modifying content per clear instructions, generating boilerplate code, format conversion, and field completion. Instructions are clear, and output structures are fixed, making it suitable for lightweight models.

    5.4 Batch Processing Layer

    Responsible for simple tasks like classification, extraction, and labeling. It has the highest volume, can be executed concurrently, and is most sensitive to single-call costs.

    5.5 Routing Implementation

    Routing logic should be explicit and testable. The following pseudocode demonstrates the basic structure for dispatching models by task type, including an escalation mechanism:

    1. tier_mapping = {
    2. "plan": "Large Model",
    3. "reason": "Medium Model",
    4. "execute": "Small Model",
    5. "batch": "Micro Model"
    6. }
    7. function select_model(task_type, consecutive_failures):
    8. tier = tier_mapping.get(task_type, default="Small Model")
    9. if consecutive_failures >= 2:
    10. tier = upgrade_one_level(tier)
    11. return tier

    The significance of the escalation mechanism is that after a lightweight model fails, the system can automatically hand the task over to a more capable tier without manual intervention. However, the number of escalations needs an upper limit; otherwise, failed tasks will continuously consume high-priced quotas.

    5.6 Total Cost Estimation Method

    The overall cost can be calculated separately by tier and then summed:

    Total Cost = Σ (Tier call count × Average consumption per call for that tier)

    The average consumption per call for each tier can be directly calculated using the consumption coefficients fitted in Section 3. This way, the benefits of tiered division can be expressed in numbers rather than judged by feel.

    6. Engineering-Level Cost Reduction Strategies

    In addition to model tiering, the following strategies are notably effective in practice:

    • Stabilize Prefixes to Increase Cache Hits: Place system prompts, fixed specifications, and long documents at the very beginning of the request, keeping them byte-for-byte consistent. Place variable content at the end.
    • Pass Context On-Demand: Only include fragments relevant to the current step in the prompt; do not pass entire databases. The recall quantity in the retrieval phase should be configurable.
    • Constrain Output Format: Require the model to return structured results, such as JSON with fixed fields, and limit the maximum output length. Output tokens are often the primary source of cost.
    • Merge Small Requests: Combine multiple structurally similar small tasks into a single call to reduce repeated system prompt overhead. The merged results require reliable splitting logic.
    • Set a Retry Budget: Set a maximum number of retries and a single-task cost cap for each task. Infinite retries can amplify a single failure into continuous consumption.

    7. Monitoring and Calibration

    Cost governance requires a continuously running observation system. It is recommended to at least achieve the following:

    1. Multi-dimensional Statistics: By model, task type, caller, and date, track the counts of input, output, and cache-hit tokens, as well as the actual deducted credits.
    2. Set Baselines and Alerts: Establish baselines for unit task costs and notify the responsible personnel when thresholds are exceeded.