How to Calculate LLM Token Costs: Breaking Down Subscription vs. Pay-As-You-Go
This article explains how to calculate and manage LLM token costs across different pricing models. It covers basic price conversion formulas, the differences between subscription and pay-as-you-go billing, factors affecting comprehensive costs, and engineering best practices to reduce token consumption. It also provides principles for model selection and a practical checklist for cost optimization.
1. Why Focus on Price Per Million Tokens
Tokens are the basic unit of measurement for how large language models process text. Text read by the model is split into tokens, and text generated by the model is also calculated in tokens. For Chinese text, one character typically corresponds to one or two tokens, depending on the tokenizer and the content. Therefore, token consumption directly determines the cost of API calls.
Many platforms use “price per million tokens” as a unified pricing metric to facilitate comparison between different solutions. However, platform billing methods vary, including pay-as-you-go and monthly or annual subscription plans. Without unified conversion, it is difficult for teams to determine which method is more cost-effective.
2. Basic Formula for Unit Price Conversion
Regardless of the billing method used, the same formula can be applied to calculate the unit cost:
Price per million tokens = Total fee / Total tokens × 1,000,000
The key to this formula lies in the statistical scope of “Total tokens”. It is necessary to clarify whether the count includes input tokens, output tokens, or the sum of both. Some platforms bill input, output, and cache-hit tokens separately. These should be recorded separately and converted individually.
The following example illustrates the calculation method. The numbers are hypothetical and do not represent actual prices:
def cost_per_million(total_fee: float, total_tokens: int) -> float:"""Convert total fee to price per million tokens (CNY/million tokens)."""if total_tokens <= 0:raise ValueError("total_tokens must be a positive number")return total_fee / total_tokens * 1_000_000# Assume a monthly fee of CNY 200 and a consumption of 100 million tokens for the monthprint(round(cost_per_million(200, 100_000_000), 2)) # Output: 2.0
It should be noted that the “unit price” under a subscription model heavily depends on usage volume. The lower the usage, the higher the unit price. If the plan’s quota is chronically unused, the actual unit price will be significantly higher than the nominal value.
3. Subscription vs. Pay-As-You-Go Comparison
Before choosing a billing method, evaluate it from the following dimensions:
| Dimension | Subscription | Pay-As-You-Go |
|---|---|---|
| Price Stability | Depends on actual usage; fluctuates significantly | Calculated directly based on contract or official pricing; transparent |
| Suitable Scenarios | Individuals or small teams with high and stable usage | Businesses with fluctuating usage requiring precise accounting |
| Quotas & Limits | May have rate limits, concurrency limits, or usage terms constraints | Usually constrained primarily by account balance and quotas |
| Cost Control | Fixed expenses, but policies for exceeding quotas need confirmation | Costs increase linearly with request volume; budget alerts needed |
| Integration Difficulty | Need to confirm if programmatic batch calls are allowed | Generally can be integrated directly via API |
The advantage of the subscription model is that fixed expenses are easy to budget for, but the quota rules, available model scope, and service terms of the plan may change. Before using it, refer to the latest documentation from the service provider, and do not make decisions based solely on historical prices or third-party descriptions.
4. Unit Price is Not Comprehensive Cost
The price per million tokens is only part of the cost. The actual comprehensive cost is also affected by the following factors.
1. Input-to-Output Ratio. On most platforms, the unit price for output tokens is higher than for input tokens. If your business primarily involves long-text generation, the proportion of output costs will increase significantly.
2. Repetitive Context Passing. In multi-turn conversations, each request usually needs to include historical messages, causing input tokens to grow with the number of turns. The longer the conversation, the higher the cost per request.
3. Retries and Failed Requests. Retries after timeouts or format validation failures will consume tokens repeatedly. The cost of failed requests is also included in the total fee.
4. Prompt Redundancy. Repetitive instructions, overly long examples, and irrelevant background information in system prompts will be billed on every call.
The following code shows how to calculate input and output costs separately:
def request_cost(input_tokens: int, output_tokens: int,price_in: float, price_out: float) -> float:"""Calculate single request cost. price_in and price_out are in CNY/million tokens."""return (input_tokens * price_in + output_tokens * price_out) / 1_000_000# Assume input price is CNY 2/million tokens, output price is CNY 8/million tokenscost = request_cost(input_tokens=3000, output_tokens=800,price_in=2, price_out=8)print(f"Single request cost: {cost:.4f} CNY")
Through this breakdown, teams can determine whether the cost mainly comes from input or output, enabling targeted optimization.
5. Engineering Practices to Reduce Token Consumption
Cost optimization usually starts with reducing invalid tokens. The following methods are applicable in most business scenarios.
5.1 Streamline Prompts
Regularly review system prompts, delete repetitive rules, and replace long examples with brief format descriptions. Every reduction in repetitive prompt content benefits all requests.
5.2 Control Context Length
Multi-turn conversations require setting a budget for historical messages. Common practices include sliding windows and summary compression: keeping the most recent few turns of complete conversation and compressing earlier content into a summary.
def trim_history(messages: list[dict], budget: int) -> list[dict]:"""Retain history starting from the latest message until the character budget is reached.Character count is a rough estimate; production environments should use the corresponding model's tokenizer."""kept, used = [], 0for msg in reversed(messages):size = len(msg["content"])if used + size > budget:breakkept.append(msg)used += sizereturn list(reversed(kept))
5.3 Limit Output Length
Limit response length using the maximum output token parameter, and require concise answers in the prompt. For tasks like classification or extraction, asking the model to return only structured results can significantly reduce output tokens.
5.4 Cache Repetitive Requests
For requests with identical inputs, such as fixed knowledge base Q&A or common text classification, results can be cached for a period. Once a cache hit occurs, the model is no longer called, bringing the cost close to zero. The cache key should include the model version and prompt version to prevent the erroneous reuse of outdated results.
5.5 Select Models by Task Tier
Not all tasks require the most powerful model. Simple format conversions and keyword extraction can use smaller models, while complex reasoning and long document analysis can call larger models. Routing traffic through a tiering strategy can typically reduce overall costs while maintaining acceptable quality.
5.6 Batch Processing
For offline tasks, such as batch tagging or batch summarization, requests can be merged and scheduled to run during off-peak hours. Whether batch APIs are supported and their discount rules should be confirmed in the official documentation.
6. Establishing a Cost Monitoring System
Only continuous monitoring can reveal cost anomalies. It is recommended to record at least the following metrics:
- Input tokens, output tokens, and latency for each request;
- Daily consumption broken down by functional module, user, or tenant;
- Cost per unit of business volume, such as average token consumption per order or per session;
- Day-over-day and week-over-day variations, and alerts when thresholds are exceeded.
Logs and monitoring data can be written to general logging services, and budget thresholds can be set through monitoring and alerting systems. When the cost of a specific feature suddenly rises, the team can promptly check whether prompts were altered, whether context grew abnormally, or if a retry storm occurred.
7. Evaluation Principles for Model Selection
When selecting a model or service, unit price is only one evaluation criterion. It is recommended to make a comprehensive judgment in the following order:
- Quality. Build an evaluation set using your team’s own business data to compare the performance of different models on metrics like accuracy and format stability. Public leaderboards are for reference only.
- Latency and Stability. Online businesses are sensitive to first-token latency and availability. Actual stress testing is required, along with observing performance during peak hours.
- Quotas and Limits. Confirm whether concurrency, rate limits, and quota rules meet peak demands.
- Data Security and Compliance. Clarify whether data will be used for training, whether it meets industry regulatory requirements, and whether data retention and deletion are supported.
- Comprehensive Cost. Combine unit price, retry rate, average token consumption, and manual review costs to calculate the total cost per unit of business volume.
Before completing the evaluation, do not directly replace the existing solution just because the unit price is lower. The rework and user churn caused by quality degradation are often more expensive than token fees.
8. Practical Checklist
- Unify the metric to “price per million tokens” and document the calculation method;
- Track input and output tokens separately to locate the primary source of cost;
- For subscription plans, calculate actual utilization to avoid idle quotas;
- Streamline prompts and limit context and output length;
- Enable caching for repetitive requests and use smaller models for simple tasks;
- Establish cost dashboards and budget alerts by module;
- Base decisions on your own evaluation set, comprehensively assessing quality, latency, and compliance requirements.
