Estimating LLM Token Usage and Cost: A Practical Method
Large language model services are typically billed by token usage, and costs grow linearly with traffic. This article explains how to systematically estimate token consumption and cost by unifying input/output pricing into a blended unit price, weighting it across multiple model tiers, converting daily usage into monthly costs, and validating estimates against real logs. It includes a worked example, a Python script, common sources of error, and actionable strategies for cost reduction through monitoring, tiered routing, and input/output control.
1. Why You Need Systematic Token Usage Estimation
LLM services are usually billed by token, and costs grow linearly with call volume. Many teams can only see the total bill but cannot tell which model, which type of request, or which part of the business the cost comes from. Without a breakdown, budgets rely on guesswork, and a sudden spike in traffic often leads to runaway costs.
The value of systematic estimation is that it decomposes total cost into several independently observable variables:
- Total tokens consumed per day;
- The share of tokens handled by each model;
- The unit price of input and output tokens respectively;
- The actual input-to-output token ratio.
As long as these variables are observable, you can identify the cause of any cost change and adjust accordingly.
2. Basic Concepts: Input Tokens, Output Tokens, and Billing Units
A token is the smallest unit of text processed by a model. A token may correspond to a fragment of an English word, a Chinese character, or a punctuation mark—exact segmentation depends on the tokenizer implementation. The same text may therefore produce different token counts on different models, so when comparing across models, always use the token count returned by the corresponding model.
Most platforms bill two categories of tokens separately:
- Input tokens (prompt tokens): system instructions, conversation history, retrieved context, and user questions contained in the request;
- Output tokens (completion tokens): the response content generated by the model.
Pricing is usually quoted as “price per million tokens.” Input and output are priced separately, and output tokens are typically more expensive than input tokens because generation requires sequential computation for each token, consuming more resources.
3. Unifying Prices Under Asymmetric Input/Output Pricing
Because input and output prices differ, comparing the sticker prices of two models is meaningless. You first need to merge them into a single comparable blended unit price. The common approach is to assume an input-to-output ratio and compute a weighted average price.
Let P_in be the input price, P_out the output price, and r_in : r_out the token ratio of input to output. The blended price is:
Blended price = (P_in × r_in + P_out × r_out) / (r_in + r_out)
This ratio should be derived from real logs. For Q&A-style workloads, input usually far exceeds output—the ratio may reach 5:1 or higher. For code generation or long-form writing, the output share rises noticeably. The larger the deviation in your ratio assumption, the larger the estimation error, so recalibrate periodically using actual logs.
Some platforms also price cached input tokens differently. In that case, calculate the cache-hit portion separately rather than mixing it with regular input at the same unit price.
4. Weighted Average Price Across Multiple Models
Enterprises typically run high-, mid-, and low-tier models in parallel: complex tasks go to high-end models, routine tasks to mid-tier models, and simple classification or extraction tasks to lightweight models. The overall unit price should be weighted by each model’s token share:
Overall price = Σ (model share × blended price of that model)
The following example uses hypothetical numbers to demonstrate the calculation. These figures are for illustration only and do not represent pricing from any actual platform.
| Model tier | Input price (per million tokens) | Output price (per million tokens) | Blended price (3:1) | Token share |
|---|---|---|---|---|
| High-end | 10 | 30 | 15.00 | 40% |
| Mid-tier | 3 | 9 | 4.50 | 35% |
| Lightweight | 0.5 | 1.5 | 0.75 | 25% |
Weighted calculation:
- High-end: 15.00 × 40% = 6.000
- Mid-tier: 4.50 × 35% = 1.575
- Lightweight: 0.75 × 25% = 0.188
The overall weighted price is approximately 7.76 per million tokens.
This result shows that the high-end model accounts for only 40% of tokens but contributes roughly 77% of the weighted cost. Therefore, the first lever for cost optimization is usually reducing the share of high-end model usage—not compressing all requests indiscriminately.
5. Converting Daily Usage into Monthly Cost
With the weighted unit price, you can convert usage into cost using this pipeline:
- Measure average daily total tokens (input plus output combined, or tracked separately and priced separately);
- Multiply by the weighted unit price to get daily cost;
- Multiply by the number of days to get monthly cost;
- Add a buffer to absorb traffic peaks and holiday fluctuations.
6. Example Code
The following script implements the calculation flow described above and is suitable for running periodically in a monitoring system.
from dataclasses import dataclass@dataclassclass ModelTier:name: strinput_price: float # Price per million input tokensoutput_price: float # Price per million output tokensshare: float # Token share, between 0 and 1def blended_price(input_price: float, output_price: float,ratio_in: float = 3, ratio_out: float = 1) -> float:"""Compute the blended unit price based on the input/output ratio, per million tokens."""total = ratio_in + ratio_outreturn (input_price * ratio_in + output_price * ratio_out) / totaldef monthly_cost(tiers: list[ModelTier], daily_tokens_million: float,days: int = 30) -> dict:"""tiers: list of model tiers; shares must sum to 1daily_tokens_million: average daily total tokens, in millions"""share_sum = sum(t.share for t in tiers)if abs(share_sum - 1.0) > 1e-6:raise ValueError(f"Shares must sum to 1, current sum is {share_sum}")weighted_unit = 0.0detail = {}for t in tiers:unit = blended_price(t.input_price, t.output_price)contribution = unit * t.shareweighted_unit += contributiondetail[t.name] = round(contribution, 4)daily_cost = weighted_unit * daily_tokens_millionreturn {"weighted unit price (per million tokens)": round(weighted_unit, 4),"daily cost": round(daily_cost, 2),"monthly cost": round(daily_cost * days, 2),"per-tier contribution to unit price": detail,}if __name__ == "__main__":tiers = [ModelTier("high-end", input_price=10, output_price=30, share=0.40),ModelTier("mid-tier", input_price=3, output_price=9, share=0.35),ModelTier("lightweight", input_price=0.5, output_price=1.5, share=0.25),]result = monthly_cost(tiers, daily_tokens_million=200)for k, v in result.items():print(k, v)
Running the script yields a weighted unit price of 7.7625 per million tokens. At 200 million tokens per day, the daily cost is about 1,552.5 and the monthly cost about 46,575 in the currency unit used for pricing.
7. Sources of Error and How to Calibrate
Estimates often deviate from actual bills. The main sources are:
- Ratio assumption error: a fixed input/output ratio may fluctuate significantly in real workloads. The fix is to track the true daily ratio from logs and replace the assumption.
- Tokenization differences: different models count tokens differently, so the same text may consume different amounts on two models. Use the usage fields returned by the platform rather than rough local character-count estimates.
- Caching and retries: failed retries, interrupted streaming, and cache hits all change the actual billed amount. Logs should distinguish first attempts from retries.
- Price changes: platform pricing may change. Keep unit prices in a configuration file instead of hardcoding them.
The basic calibration routine: compare the platform bill against the script’s estimate weekly. If the deviation exceeds roughly 5%, check whether the ratio assumption or request classification has drifted.
8. Putting It into Practice: Monitoring, Alerting, and Cost Reduction
The real value of estimation is guiding day-to-day operations. Consider landing it in three areas:
1. Usage observability
At the application layer, log the model name, input tokens, output tokens, business-line tag, and latency for every request. Write these to a logging service or time-series database, and set thresholds on your monitoring and alerting platform—for example, notify the owner when daily cost exceeds 120% of budget.
2. Tiered routing
Route requests to different model tiers based on task complexity. A common pattern is to use a lightweight model first for intent recognition or format validation, invoking the high-end model only when deep reasoning is required. This directly reduces the share of high-priced tokens and typically has a bigger cost impact than trimming prompts.
3. Input and output control
- Streamline system prompts and drop conversation history irrelevant to the current task;
- Deduplicate and truncate retrieved content, keeping only relevant chunks;
- Use explicit output length constraints and structured output formats to reduce unnecessary generation;
- Enable caching for highly repetitive requests, and confirm the platform’s cache pricing rules.
Validate savings with real data. After each change, run the same estimation script to compare the weighted unit price and daily cost before and after, confirming the change actually works.
9. Summary
LLM cost accounting boils down to three steps: unify input and output prices into a blended unit price, weight it by each model’s token share to get the overall unit price, then multiply by real usage to get cost. The method itself is simple—the key is continuously collecting real usage and ratio data, and making unit prices and shares configurable, calibratable parameters. On that foundation, tiered routing and input/output control are the most direct levers for cutting costs.
