How to Calculate LLM Token Costs: From Unit Price to Model Selection
This article explains how to calculate large language model (LLM) token costs, covering token billing metrics, unit conversion, and effective unit price estimation. It details cost estimation models, key factors affecting actual costs such as input-output ratios and context accumulation, and provides a framework for calculating cost per task and making informed model selection decisions.
I. Aligning the Metrics: What Does Token Billing Actually Calculate?
Tokens are the basic unit of measurement for large language models (LLMs) processing text. A token might correspond to a Chinese character, a fragment of an English word, or a punctuation mark, depending on the tokenizer. Therefore, the same text may yield a different number of tokens across different models. Directly comparing the numbers reported by two vendors is meaningless unless the metrics are aligned first.
There are three common pricing models: charging by input tokens, charging by output tokens, and subscription-based billing (monthly or volume). The first two are usage-based, where costs scale almost linearly with the number of calls. The third is a fixed expense, where the actual cost depends on how much of the quota is consumed.
Many teams treat “unit price” as the sole metric, which leads to biased judgments. Under the same unit price, longer outputs and larger contexts result in higher total costs. When evaluating costs, you must consider the unit price, token usage structure, and task success rate simultaneously.
1.1 Unit Conversion
The industry typically uses “currency units per million tokens” as a standard unit. The conversion method is as follows:
Unit Price (per million tokens) = Total Cost (currency units) ÷ Total Tokens (in millions)
If the price is given as “per thousand tokens” or “per call,” convert it to per million tokens first before making horizontal comparisons. During conversion, pay attention to currency, tax inclusion, and whether conditions like caching or batch processing discounts are included.
1.2 Effective Unit Price: Converting Fixed Costs to Usage-Based Pricing
The advantage of a subscription is fixed spending, but it does not directly provide a token unit price. To determine if it is cost-effective, you can reverse-calculate the effective unit price:
Effective Unit Price = Subscription Fee ÷ Actual Tokens Consumed in the Cycle (in millions)
This metric has three prerequisites. First, the denominator must be the actual consumption, not the theoretical limit. Second, invalid tokens generated by rate limiting, timeouts, or retries must be deducted. Third, subscriptions usually come with usage frequency limits, response latency, and availability constraints. These factors are not reflected in the unit price and need separate evaluation.
Additionally, the effective unit price is a blended price. If the unit prices for input and output differ, the effective unit price will vary with the input-output ratio, which will be explained specifically later.
II. Cost Estimation Model
2.1 Basic Formula
The cost of a single call consists of two parts: input and output:
Single Call Cost = Input Tokens × Input Unit Price + Output Tokens × Output Unit Price
If the platform offers a lower unit price for cached input, the input part should be split into “fresh input” and “cache-hit input” for calculation.
The total task cost must also be multiplied by the number of calls, factoring in retries:
Total Task Cost = Single Call Cost × Number of Calls × (1 + Retry Rate)
2.2 Python Example
The following code implements the above formulas. The prices used are example numbers and do not represent actual quotes; replace them with values from your bill or official price list when using.
from dataclasses import dataclass@dataclassclass Price:input_per_m: float # Price per million input tokens (currency units)output_per_m: float # Price per million output tokens (currency units)cached_input_per_m: float | None = None # Price per million cached input tokens (currency units)def estimate_call_cost(price: Price,input_tokens: int,output_tokens: int,cached_tokens: int = 0,) -> float:"""Estimates the cost of a single call, returning the value in currency units."""if not 0 <= cached_tokens <= input_tokens:raise ValueError("cached_tokens must be between 0 and input_tokens")cached_price = (price.cached_input_per_mif price.cached_input_per_m is not Noneelse price.input_per_m)fresh_tokens = input_tokens - cached_tokenscost = (fresh_tokens * price.input_per_m+ cached_tokens * cached_price+ output_tokens * price.output_per_m)return cost / 1_000_000def effective_price_per_m(subscription_fee: float, consumed_tokens: int) -> float:"""Calculates the effective unit price based on subscription fee and actual consumption (currency units/million tokens)."""if consumed_tokens <= 0:raise ValueError("consumed_tokens must be greater than 0")return subscription_fee / (consumed_tokens / 1_000_000)if __name__ == "__main__":# Example prices, used only to demonstrate the calculation processprice = Price(input_per_m=10.0, output_per_m=40.0, cached_input_per_m=1.0)cost = estimate_call_cost(price,input_tokens=3000,output_tokens=800,cached_tokens=2000,)print(f"Single call cost is approximately {cost:.4f} currency units") # Output: Single call cost is approximately 0.0440 currency units
2.3 Weighted Calculation of Blended Price
When the input and output unit prices differ, comparing two solutions using a single price can be misleading. A more reasonable approach is to weight by the actual token structure:
Blended Price = (Input Tokens × Input Unit Price + Output Tokens × Output Unit Price) ÷ Total Tokens
For a solution costing 10 currency units per million tokens, if the output proportion is high, the actual cost will rise significantly. Therefore, during model selection, first use historical logs to calculate the input-output ratio, then use this ratio to compute the blended price.
III. Key Factors Affecting Actual Costs
3.1 Input-Output Ratio
Output tokens typically have a higher unit price than input tokens and take longer to generate. Tasks like summarization, rewriting, and classification have shorter outputs, keeping costs under control. Long-form generation, code generation, and step-by-step reasoning tasks have longer outputs, amplifying costs quickly. When evaluating, calculate the input-output ratio separately based on task type.
3.2 Context Accumulation in Multi-Turn Conversations
In multi-turn dialogues, each round resends historical messages as input. If each round adds about 500 tokens, the input for the nth round is approximately 500 × n tokens, and the cumulative input grows nearly quadratically with the number of turns. This means splitting the same Q&A content into a long session versus a short session can result in vastly different costs.
Control methods include periodically compressing history, retaining only the context relevant to the current question, placing stable system instructions in a cacheable prefix, and promptly starting a new session after the conversation ends.
3.3 Retries, Failures, and Timeouts
When a request fails, times out, or returns a non-compliant format, the client often retries automatically. Tokens generated during retries are often billed but yield no business value. You should record the reason for each retry and the extra tokens consumed, and incorporate the retry rate into your cost model. If the retry rate consistently exceeds 5%, it usually indicates issues with prompt or parameter design that need prioritized troubleshooting.
3.4 Batch Processing and Asynchronous Calls
For tasks that do not require real-time responses, such as offline labeling, batch summarization, and data cleaning, batch or asynchronous APIs can be used. Some platforms offer discounts for these calls, but specific rules depend on platform documentation. Even without price discounts, merging requests can reduce header overhead and concurrency control costs, making rate limiting easier to manage.
3.5 Output Length Constraints
Clearly specifying output length, format, and stop conditions in the prompt can effectively control output tokens. For example, requiring “return as a bulleted list of no more than 200 words” is easier to control cost-wise than leaving it unrestricted. Setting a reasonable max output token parameter can also prevent anomalous outputs from growing indefinitely.
IV. From Unit Price to Cost Per Task
4.1 Defining Tasks and Success Criteria
The object of cost evaluation should be business tasks, not single API calls. For example, “generate a risk summary for a contract,” “generate unit tests for a code snippet,” or “answer a customer service inquiry.” Each task type needs clear success criteria, such as correct format, complete key fields, passing code tests, or no need for manual modification after review.
4.2 Calculating Cost Per Task
Cost Per Task = Total Cost ÷ Number of Successfully Completed Tasks
This metric factors failure costs into the numerator and quality into the denominator. A solution with a lower unit price but a 60% success rate may have a higher cost per task than a solution with a higher unit price but a 90% success rate. This is why looking only at the unit price often leads to wrong choices.
4.3 Establishing a Benchmark Sample Set
It is recommended to extract a representative batch of samples from real business scenarios, covering common cases and edge cases, usually between 100 and 300 items. Run the same batch of samples for each candidate solution and record the following data: average input and output tokens, success rate, average latency, retry count, and manual modification time. This data allows solution comparisons to be based on the same benchmark.
V. Model Selection Decision Framework
When selecting a model, set thresholds first, then make comparisons. Compliance and data processing requirements are hard thresholds; if not met, the solution is directly eliminated. Quality floor is the second threshold; solutions with a success rate below the business acceptable level do not participate in cost comparison. After meeting the first two, compare cost per task, latency, and stability.
| Dimension | Focus Area | Measurement Method |
|---|---|---|
| Compliance | Data storage location, retention period, use for training | Contract terms and security review |
| Quality | Task pass rate, format accuracy rate | Automated evaluation plus sampling manual review |
| Unit Cost | Cost per task, blended price | Billing data and telemetry logs |
| Latency | P95 response time, time to first token | Monitoring platform metrics |
| Stability | Error rate, rate limit frequency, availability | Request logs and alert records |
The weight of each dimension should be determined by the business. Real-time conversations for end-users prioritize latency, offline batch processing prioritizes unit cost, and code generation scenarios prioritize quality.
VI. Usage Monitoring and Budget Control
6.1 Telemetry Fields
For each model call, it is recommended to record the following fields: request time, business scenario ID, model ID, input tokens, output tokens, cache-hit tokens, retry count, duration, success status, and estimated cost. Once the fields are standardized, you can perform aggregate analysis by scenario, user, or version.
6.2 Budget Guard Example
from dataclasses import dataclass, field@dataclassclass BudgetGuard:daily_limit: float # Daily budget limit (currency units)alert_ratio: float = 0.8 # Issues an alert when this ratio of the budget is reachedspent: float = field(default=0.0) # Amount spent today (currency units)def record(self, cost: float) -> None:"""Records a call cost and prompts when the threshold is exceeded."""self.spent += costif self.spent >= self.daily_limit:raise RuntimeError(f"Daily cost has reached {self.spent:.2f} currency units, exceeding the budget limit of {self.daily_limit:.2f} currency units")if self.spent >= self.daily_limit * self.alert_ratio:print(f"Warning: Daily cost has reached {self.spent:.2f} currency units, approaching the budget limit")guard = BudgetGuard(daily_limit=500.0)
