How to Calculate LLM Token Costs and Reduce Them in Practice

    This article breaks down why the cost of a single LLM request cannot be answered with a simple per-token price, and shows how to model it as a calculable formula based on input tokens, output tokens, cache hits, and model tier. It covers the four most common cost amplifiers, two cost-reduction paths (self-hosted inference and structured token governance), how to build an internal price reference table, and a practical implementation order for logging, attribution, optimization, and budget alerts.

    1. The Starting Point: Why “Cost per Token” Has No One-Line Answer

    When teams first budget for an AI coding tool or a general LLM capability, they usually ask the same question: how much does one request cost? The question is hard to answer because cost is not driven by the number of calls. It is driven by input length, output length, whether the context is resent every turn, whether a cache is hit, and which capability tier of model you select. For the same feature, a different prompt structure can change the cost by several times.

    A more rigorous approach is to treat cost as a calculable model rather than memorizing a unit price. The discussion below uses generic billing semantics: input tokens and output tokens are priced separately, and some scenarios apply a discount to the cached portion of the input.

    2. The Cost Model: Breaking the Bill into Calculable Variables

    The cost of a single request can be written as:

    1. cost per request = input tokens × input price + output tokens × output price
    2. daily cost = Σ(cost per request) = requests × avg input length × input price
    3. + requests × avg output length × output price

    The variable most often underestimated here is the average input length. In AI coding and conversational applications, the input is rarely just the user’s message. It also includes system instructions, tool definitions, repository retrieval snippets, conversation history, and multi-turn patch content. The real input length is often more than ten times the text the user actually sees.

    An illustrative estimation function (prices are placeholders and must be replaced with your actual bill):

    1. def estimate_cost(reqs, in_tok, out_tok, p_in, p_out, cache_ratio=0.0):
    2. billable_in = in_tok * (1 - cache_ratio)
    3. return reqs * (billable_in * p_in + out_tok * p_out)

    3. Where Cost Leaks: Four High-Frequency Amplifiers

    The first is repeated context. If a multi-turn conversation resends the full history every turn, cost grows roughly with the square of the number of turns. The second is oversized retrieval snippets: stuffing an entire file into the context instead of only the relevant function. The third is redundant output: the model restating code or explaining obvious things, while the output price is usually higher than the input price. The fourth is model tier mismatch: using the strongest model for simple tasks such as formatting and completion.

    4. Cost-Reduction Path 1: Self-Hosted Local Inference

    Running inference on your own hardware changes the marginal cost from pay-as-you-go to a one-time hardware investment plus electricity. This fits scenarios with high call volume, stable workloads, and data that must stay inside the internal network. Engineering recommendations: choose a model whose parameter count matches your VRAM, use quantization to reduce VRAM usage, and wrap the interface in a unified inference service so that upper-layer applications do not need to know where the model comes from.

    1. application layer → unified inference gateway → (local inference instance | cloud pay-as-you-go instance)

    The gateway handles routing and rate limiting, and it is the anchor point for all later optimization strategies.

    5. Cost-Reduction Path 2: Structured Token Governance

    1. Cache reuse: cache stable prefixes such as system instructions and long-document summaries; the hit portion is billed at a discount.
    2. Context trimming: retrieve first, then summarize, keeping only function signatures and key snippets.
    3. Output constraints: state explicitly “output only the changed code, no explanation” to significantly compress output length.
    4. Model tiering: route completion and formatting to small models, and architecture design and troubleshooting to large models.
    5. Batching and async: merge non-real-time tasks into single submissions to avoid peak hours and improve throughput.

    6. Building Your Own Price Reference Table

    Because cloud vendors and model providers keep adjusting prices, the most reliable approach is to maintain an internal reference table with fields such as: model tier, input price, output price, cache policy, context limit, applicable task type, and measured average input and output length. Review it once a month and backfill the average lengths with real request logs. Your budget accuracy will be far higher than if you rely on any static leaderboard.

    7. A Practical Implementation Order

    Step one: add instrumentation to log the input and output tokens and latency of every request. Step two: do attribution to find the call sources with the largest share. Step three: optimize in the order of caching, trimming, tiering, and localization, watching the bill change after each step. Step four: set budget alerts and quotas to prevent runaway loops of calls. Platforms such as Baidu AI Cloud typically provide general capabilities like monitoring alerts and logging services, which can support the instrumentation and alerting needs described above.

    8. Conclusion

    Token cost is not a unit-price problem; it is an engineering problem. Only by writing cost as a formula, making the call chain observable, and splitting optimization into verifiable small steps can you achieve a stable balance between quality and budget.