Understanding LLM API Pricing: How to Calculate the True Cost of a Single Task
Evaluating LLM costs requires looking beyond unit prices. This article breaks down API billing dimensions, provides a formula and Python code to calculate single-task costs, compares subscription plans with pay-as-you-go billing, and offers practical recommendations for model selection and cost optimization.
I. Why Unit Price Alone Can Be Misleading
Model pricing is typically quoted per million tokens, with separate rates for input, output, and cache hits. While these unit prices can be compared directly, what users actually pay is the total cost of completing a specific task. For the same prompt, one model might only generate a few thousand tokens, while another might consume several times more output tokens due to a longer reasoning process. Therefore, when evaluating model prices, you need to compare unit price, per-task token consumption, and usage limits under a unified standard.
II. Breakdown of Billing Dimensions
- Input tokens: Includes system prompts, conversation history, retrieved documents, and tool responses. In multi-turn dialogues and agent scenarios, input volume accumulates with turns and is usually much larger than what the user directly sees.
- Cache hits: When a request prefix matches a previous request, the server can reuse pre-computed intermediate results, and the corresponding portion is billed at a lower unit price. The key to increasing cache hit rates is placing stable content (system prompts, tool definitions, fixed knowledge) at the beginning of the prompt and variable content at the end.
- Output tokens: Includes visible responses. Some models also generate reasoning tokens, which are typically billed at the output unit price and are easily overlooked.
- Number of calls: Agent-based workflows often split a single user request into multiple model calls, such as planning, retrieval, execution, and validation. The total cost equals the sum of the costs of each call.
III. Calculating the Cost of a Single Task
Before calculating, you need to track three metrics from real tasks: average input tokens, average output tokens, and cache hit ratio. The statistical sample should come from production traffic or a test set consistent with the live environment; data from a single demonstration is not representative. Average consumption in third-party evaluation reports can serve as a reference but needs to be adjusted based on your own business’s prompt length and task type.
Single-task cost = (Uncached input tokens × Input unit price + Cached input tokens × Cache unit price + Output tokens × Output unit price) / 1,000,000
This formula can be directly translated into code to batch-compare different solutions:
def estimate_task_cost(input_tokens, output_tokens, cache_hit_ratio,price_input, price_cache_hit, price_output):"""All unit prices are in: currency units / million tokens. Returns single-task cost (currency units)."""if not 0 <= cache_hit_ratio <= 1:raise ValueError("cache_hit_ratio must be between 0 and 1")cached = input_tokens * cache_hit_ratiouncached = input_tokens - cachedtotal = (uncached * price_input+ cached * price_cache_hit+ output_tokens * price_output)return total / 1_000_000# Example unit prices are for demonstration only and do not represent actual quotes of any service.cost = estimate_task_cost(input_tokens=200_000,output_tokens=20_000,cache_hit_ratio=0.6,price_input=10,price_cache_hit=1,price_output=40,)print(f"Estimated single-task cost: {cost:.2f} currency units") # Output: Estimated single-task cost: 1.72 currency units
In the example above, 60% of the input hits the cache, so the cache unit price significantly impacts the total cost. If the cache hit ratio drops to 0%, the cost of the same task would increase from approximately 1.72 currency units to 2.80 currency units, rising by about 60%. This demonstrates that the impact of caching strategies on cost is often greater than the difference between the listed prices of two models.
IV. Converting Subscriptions to Pay-As-You-Go
Subscription plans are typically sold as a monthly fee plus a certain usage quota. When comparing, you should convert the quota into the number of tasks that can be completed:
Number of completable tasks ≈ Plan quota / Single-task cost
Note the following during conversion:
- The measurement standard for the quota might be the number of messages, tokens, or compute credits. Different standards cannot be directly added together.
- Plans may have limits on concurrency, request rate, and single-context length. A sufficient quota does not mean it can support batch tasks.
- The pay-as-you-go price after exceeding the quota needs to be calculated separately; otherwise, the actual expenditure of heavy users will be underestimated.
- The price and usage between different plans do not correspond linearly; refer to the official rules published by each provider.
After calculating with this method, a solution with a higher unit price but lower per-task consumption might be cheaper than a solution with a lower unit price but verbose output. Selection conclusions should come from real test data, not from price lists.
V. Model Selection and Cost Optimization Recommendations
- Select models by task tier: Lightweight models can handle simple classification, information extraction, and text rewriting, while advanced models should be called for complex reasoning, code modification, and long document analysis. A routing layer can determine the call path based on task type or confidence.
- Fix prefixes: Place system prompts, tool descriptions, and examples at the very beginning of the request and keep them byte-for-byte consistent to increase cache hit rates.
- Control output: Reduce invalid output through clear output formats (e.g., a fixed JSON structure) and length limits.
- Set budget guardrails: Set daily budgets and call limits for each user and task type, and record token usage for each call to easily detect abnormal consumption.
- Establish a cost dashboard: Track the median and 95th percentile of single-task costs by functional module. A few extra-long tasks often account for the majority of expenses, and long-tail tasks require separate governance.
VI. Summary
LLM costs are jointly determined by unit price, token structure, cache efficiency, number of calls, and billing plans. When comparing different solutions, you should start from the actual consumption of a single task, perform calculations under a unified standard, and then make decisions combined with your business’s traffic scale and latency requirements.
