How LLM API Costs Are Calculated: Tiered Pricing and Token Consumption Estimation
A practical guide to estimating LLM API costs. This article explains quota-based and token-based billing, walks through a reusable cost estimation formula with example code, and covers tier selection, caching, context trimming, tiered routing, and budget alerting to keep spending predictable.
How LLM API Costs Are Calculated: Tiered Pricing and Token Consumption Estimation
Why Cost Estimation Matters
Two models with the same monthly subscription price can handle very different request volumes. A high-performance tier may only support dozens of complex tasks, while a lightweight tier can handle thousands of simple calls. Developers who look only at the subscription price tend to underestimate real costs—and often run out of quota sooner than expected after launch.
To understand cost, you first need to understand how the platform meters usage. Most LLM services use one of two billing methods: quota-based (per-request) or token-based. Each has different influencing factors and requires a different estimation approach.
Two Billing Methods
Quota-Based Billing
Quota-based billing converts your allowance into a number of usable requests. That number is not fixed—it fluctuates with task complexity, driven mainly by three factors:
- Task complexity: The longer the reasoning chain and the more steps involved, the more quota a single request consumes.
- Context length: The longer the conversation history and documents attached to each request, the more quota is used.
- Tool call count: Each external tool call typically adds extra model round trips, increasing consumption.
Because of this, quotas are usually expressed as ranges rather than exact values. For capacity planning, estimate peak consumption using the lower bound of the range and generous scenarios using the upper bound.
Token-Based Billing
Token-based billing charges by the number of text tokens in the input and output. Most services split pricing into three categories:
- Standard input: Tokens from the user request and its context.
- Cached input: Prefix tokens that hit a server-side cache, usually priced significantly below standard input.
- Output: Tokens generated by the model, usually the most expensive.
Output tokens cost more because generation is sequential—each token depends on everything before it, consuming more resources than reading input. As a result, controlling output length often saves more money than compressing input.
Within the same model family, unit prices across tiers can differ by several times. When choosing a model, factor this gap into your cost analysis and base decisions on the official price sheet and measured usage—not on model names or marketing claims.
Unit Conversion
Some platforms settle usage in internal credits, then convert to USD at a fixed exchange rate. When converting, pay attention to two things: whether the exchange rate is documented in the price sheet, and whether standard-speed and accelerated tiers are priced differently. Teams should maintain a fixed conversion table recording these parameters, so everyone estimates on the same basis.
Building a Cost Estimation Model
The core formula is:
Cost per request = (standard input tokens × standard input price+ cached input tokens × cached input price+ output tokens × output price) / 1,000,000Monthly cost = cost per request × average daily requests × 30
The following example code implements this formula. The prices shown are placeholders—replace them with the prices published by your provider.
from dataclasses import dataclass@dataclassclass ModelPrice:name: strinput_per_m: float # price per million standard input tokenscached_per_m: float # price per million cached input tokensoutput_per_m: float # price per million output tokensdef estimate_cost(price: ModelPrice, input_tokens: int,cached_tokens: int, output_tokens: int) -> float:"""Estimate the cost of a single request, in the same unit as the prices."""return (input_tokens * price.input_per_m+ cached_tokens * price.cached_per_m+ output_tokens * price.output_per_m) / 1_000_000
Usage example:
premium = ModelPrice("premium", input_per_m=10.0, cached_per_m=1.0, output_per_m=40.0)economy = ModelPrice("economy", input_per_m=2.0, cached_per_m=0.2, output_per_m=10.0)# Assume a single request: 5,000 standard input, 20,000 cached input, 1,500 outputfor p in (premium, economy):cost = estimate_cost(p, 5000, 20000, 1500)print(f"{p.name}: cost per request {cost:.4f}")
In the output, the premium tier’s per-request cost is noticeably higher than the economy tier’s. At 10,000 requests per day, that gap scales into a substantial monthly difference—which is exactly why an estimation model is valuable.
Choosing a Model Tier
Don’t make the strongest model the default. Instead, assign tiers by task type:
- High-complexity tasks: multi-step reasoning, complex code refactoring, long-document analysis. Suited to the high-performance tier, since the cost of rework from errors usually exceeds the API cost.
- Medium-complexity tasks: routine Q&A, content rewriting, structured information extraction. The mid-tier is usually sufficient.
- Low-complexity tasks: classification, keyword extraction, format conversion. Suited to the economy tier, and can be called at scale.
In practice, run a small batch of real samples through each tier, compare accuracy and per-request cost, then decide on the default model. This is more reliable than choosing by intuition, and the evaluation results can be reused in later iterations.
Engineering Practices to Reduce Costs
1. Limit Output Length
Set a maximum output token limit in the request, and explicitly ask for concise formats in the prompt, such as JSON or bullet lists. Because output tokens are the most expensive, this usually delivers the most direct savings.
2. Increase Cache Hit Rates
Place stable content—system instructions, fixed reference documents, tool descriptions—at the beginning of the prompt, and variable content, such as the user’s question, at the end. Only a consistent prefix can be reused by the cache.
3. Trim Context
In multi-turn conversations, you don’t need to carry the full history every time. Keep only the most recent turns and compress earlier content into a summary. In RAG scenarios, inject only the most relevant chunks rather than entire documents.
4. Tiered Routing
Use a low-cost model to judge request difficulty first, then route complex requests to the high-performance model. The routing logic can be simple:
def choose_tier(task_type: str, text_length: int) -> str:if task_type in {"classify", "extract", "format"}:return "economy"if task_type in {"reason", "refactor"} or text_length > 20_000:return "premium"return "mid"
Once the rules are set, periodically validate routing accuracy with sampled data to prevent simple tasks from being misrouted as complex ones—or the reverse, which would degrade quality.
5. Control Retries and Tool Calls
Failed retries are billed again. Set retry limits for retryable errors and a maximum number of tool-call rounds, so the model doesn’t get stuck in a loop of repeated calls.
Monitoring and Budget Alerts
Cost governance requires observability. After each call, log the standard input tokens, cached input tokens, output tokens, model tier, and business tags, and write them to a logging service. Based on this data, you can break down costs by business line and set alert thresholds for daily and monthly budgets.
A common pattern: send a reminder when daily spend reaches 70% of budget; automatically switch to the economy tier at 90%; pause non-critical tasks at 100%. Adjust the thresholds based on how critical the workload is.
Common Pitfalls
- Looking only at the subscription price, not per-request consumption. The relationship between quota and actual usage depends on the task mix—the same subscription can behave very differently across workloads.
- Using one model for all tasks. Most requests don’t need the strongest capabilities; defaulting everything to the high-performance tier significantly inflates costs.
- Optimizing input but ignoring output. Many teams trim their prompts but never limit generation length, even though output is often the main cost driver.
- Treating estimates as fixed values. Task lengths fluctuate, so keep a buffer and recalibrate model parameters regularly against real billing data.
Summary
Estimating LLM costs requires understanding both quota-based and token-based billing, building a reusable estimation formula, and assigning model tiers by task difficulty. Combined with output limits, caching, context trimming, tiered routing, and monitoring with alerts, you can keep spending predictable without sacrificing quality.
