How to Calculate LLM API Costs: From Unit Price to Effective Cost per Task
Comparing LLM providers by input and output unit prices alone is not enough to determine which option is truly cheaper. This article explains how to evaluate LLM costs at three levels—listed price, per-request cost, and effective cost per completed task—covering token metering, tiered context pricing, cache billing, per-request accounting, and cost monitoring. It includes a worked numerical example and practical strategies for reducing spend without sacrificing output quality.
1. Define the Problem First: A Low Price Does Not Mean Low Cost
When comparing LLM API costs, the most intuitive approach is to put input and output unit prices into a table and sort them from low to high. This works for an initial screening, but it cannot answer the question “which option is actually more cost-effective.”
Actual spending depends not only on unit price, but also on:
- How much input content each request carries;
- How much output the model generates on average;
- Whether there are context-length pricing tiers;
- Whether caches are hit, and how caching is billed;
- Whether failed requests are retried;
- How many calls a single task requires;
- Whether the generated results need manual correction.
Cost evaluation therefore needs to distinguish three levels:
Level one is the listed price—the unit price in the pricing table. Level two is the request cost—the actual fee generated by a single call. Level three is the task cost—the total expense of completing one deliverable business outcome.
For developers and enterprise users, what really needs optimizing is the third level, not chasing the lowest listed price in isolation.
2. Unify the Measurement Basis Before Comparing
2.1 Tokens Are Not Word Counts
A token is the basic unit a model uses to process text, but there is no fixed conversion ratio between tokens and Chinese characters or English words.
The same passage can produce different token counts under different tokenizers. Code, tables, special symbols, and long numeric strings may also exhibit different tokenization behavior.
For formal accounting, prioritize the usage fields returned by the service or verifiable billing data. Estimating tokens from word counts is only suitable for rough budgeting and should not be used as a settlement basis.
2.2 Clarify the Price Unit
Pricing tables may use units such as “per 1K tokens” or “per 1M tokens.” If units are not unified, order-of-magnitude errors can easily occur.
It is recommended to standardize internal accounting on “per million tokens” and record usage as integer token counts. For example:
- 509.8K tokens means 509,800 tokens under the decimal convention;
- 8.125K tokens means 8,125 tokens;
- 1 million tokens means 1,000,000 tokens.
Also confirm whether prices include taxes, whether limited-time discounts apply, and the applicable region, service mode, model version, and effective date. Prices under different conditions cannot be mixed directly.
2.3 Input and Output Must Be Calculated Separately
In the simplest pay-as-you-go model:
Cost per request = input tokens ÷ 1,000,000 × input unit price + output tokens ÷ 1,000,000 × output unit price.
Many services charge more for output than for input. So even if output volume is small, output cost cannot be ignored.
For long-form generation, multi-turn analysis, and automated tasks, variation in output length can become a major source of budget fluctuation. Redundant output should be controlled while preserving task quality—necessary conclusions should not be mechanically cut.
3. The Key to Tiered Pricing: The Billing Unit Is Usually a Single Request
Context-length tiers are the most error-prone part of cost estimation.
Suppose a pricing rule divides tiers by the input length of a single request. Then a billing period that accumulates 509,800 input tokens in total does not mean every request should be billed at the highest tier.
That usage might come from:
- 100 short requests;
- 10 medium-length requests;
- A mix of a few long requests and many short ones.
The total input volume is the same, but the applicable tiers—and the final cost—can differ.
The correct accounting process is:
- Obtain the billable usage of each individual request;
- Identify the tier each request falls into according to the rules;
- Apply the corresponding input and output unit prices;
- Calculate the cost of each request;
- Sum all requests within the billing period.
Two different tier mechanisms must also be distinguished:
Whole-request pricing: once a request reaches a certain length bracket, all of its usage is billed under that bracket’s rules.
Progressive (segmented) pricing: usage in each bracket is billed at the corresponding price for that bracket.
These two must not be confused. In addition, some rules determine the tier based on input length, while others may use a different context definition—always refer to the actual billing documentation.
If a request exceeds the maximum allowed context, you cannot simply apply the highest-tier price. First determine whether the request will be rejected, or whether it needs to be split or truncated.
4. Cache Billing: Understand Field Relationships Before Estimating Savings
Caching is typically used to reuse repeated context, such as fixed instructions, shared reference material, and stable business background. But “enabling cache” does not automatically mean “costs will definitely decrease.”
4.1 Common Cache-Related Billing Items
Different services adopt different designs. Common categories include:
- Regular input fees;
- Cache-hit read fees;
- Cache creation or write fees;
- Cache storage or retention fees.
Not every service includes all of these. Some handle caching automatically, while others require explicit configuration; some charge separately for cache creation, while others fold the related usage into other billing items.
Therefore, you cannot infer that all services follow the same rules based on how one service behaves.
4.2 The Biggest Risk Is Double Counting
If a usage record contains both “total input” and “cache hits,” you must first confirm: is the cache-hit volume already included in the total input?
If it is, you should split the usage into regular input and cached reads before calculating, rather than adding the two figures directly.
Cache writes raise a similar issue. You cannot add a write field to the total just because it appears in the records; nor can you assume, without confirmation, that writes are completely free.
It is recommended to document every billing field, recording at least:
- The meaning of the field;
- Whether it is included in another total field;
- The applicable unit price;
- The corresponding request or cache operation;
- Whether it participates in context-tier determination.
4.3 Cache Savings Depend on Reuse Behavior
Whether caching pays off depends mainly on the length of the repeated prefix, the number of hits, the time-to-live, and the associated charges.
If a long context is used only once, caching may yield no benefit. If the same prefix is reused at high frequency, low-priced cached reads can significantly reduce spending.
The relationship can be evaluated as:
Net cache benefit = cost without caching − total cost with caching.
Here, “total cost” should include the actual creation, read, and retention costs—not just a comparison between the regular input price and the cache read price.
5. A Worked Example with Hypothetical Data
The following prices are used only to illustrate the calculation method and do not represent any real service’s current pricing.
Assume that under a given pricing plan, all relevant requests have been confirmed to use these prices:
| Billing item | Hypothetical unit price |
|---|---|
| Regular input | 2.5 per 1M tokens |
| Output | 10 per 1M tokens |
Usage for a billing period:
- Total input: 509,800 tokens;
- Total output: 8,125 tokens.
Assume there is no caching, batch discount, or other fee requiring separate handling.
Input cost:
509,800 ÷ 1,000,000 × 2.5 = 1.2745.
Output cost:
8,125 ÷ 1,000,000 × 10 = 0.08125.
Total:
1.2745 + 0.08125 = 1.35575, displayed as approximately 1.36.
Aggregated usage can be used here only because all relevant requests are confirmed to share the same unit price. If requests fall into different tiers, each must be calculated individually before summing.
Similarly, if there were a record of “cache writes: 467,300 tokens,” that number alone would not be enough to determine the final cost. You would also need to know whether it overlaps with the total input, whether it is billed separately, and at what price.
This illustrates an important principle of cost estimation: when billing relationships are incomplete, explicitly list the missing conditions rather than presenting a deceptively precise total.
6. From Request Cost to Effective Cost per Task
A cheap-per-call option that requires multiple retries to produce a usable result may end up being more expensive.
A more business-meaningful metric is:
Effective cost per task = total relevant spending in the period ÷ number of successfully completed tasks.
Total relevant spending can be calculated in layers depending on the analysis goal:
- Direct model fees;
- Retry, error-correction, and auxiliary call costs;
- Supporting resource costs such as retrieval, storage, and logging;
- Manual review and editing costs.
If you are only analyzing the model bill, state that scope clearly and do not label the result as the full business cost.
“Success” also needs a clear definition. For example:
- Whether structured output passes field validation;
- Whether generated content meets factual and formatting requirements;
- Whether automated processing actually completes the intended steps;
- Whether the answer meets business acceptance criteria.
When comparing options, use the same representative set of tasks, the same acceptance criteria, and reasonably similar context and output constraints. Otherwise, a lower cost may simply reflect processing less content or delivering lower quality.
7. Build a Verifiable Billing and Monitoring System
Whether a dashboard looks polished affects the user experience, but it cannot replace the completeness of billing data. When selecting a provider, what matters more is whether you can export detailed records, trace anomalies, and reconcile bills.
It is recommended to log the following per request:
| Category | Recommended fields |
|---|---|
| Request identity | Request ID, associated task ID |
| Timing | Call time, latency, billing period |
| Service info | Model version, service mode, price version |
| Usage | Input, output, and cache-related usage |
| Outcome | Success status, error type, retry count |
| Cost | Applicable tier, unit price, estimated cost |
| Business attribution | Project, environment, task type |
To protect privacy, there is no need to store full prompts and responses just for cost accounting. Most cost analysis can rely on usage data, tags, and necessary de-identified metadata.
Beyond daily total spend, monitoring should include cost per task, retry rate, the share of long-context requests, cache hit rates, and anomalous usage. Rising total costs may come from business growth or from a runaway retry loop—each requires a different response.
8. How to Reduce Costs Without Sacrificing Necessary Quality
8.1 Eliminate Wasted Input First
Avoid resending the full conversation history every turn. Summarize long-running sessions, keep only the parts of reference material relevant to the current question, and remove duplicate content promptly.
However, compression must not destroy critical constraints. Missing necessary context and having to redo work can offset the input savings.
8.2 Match Capability to Task Difficulty
Format conversion, simple classification, and complex reasoning do not necessarily require the same model capability. Tasks can be routed in tiers based on risk and difficulty, with appropriate validation and escalation mechanisms.
Whether a tiered strategy works should be verified with real tasks, not judged by listed model prices alone.
8.3 Control Retry Amplification
Set bounded retries with backoff for transient failures. For parameter errors or content-length violations, fix the request first instead of repeating meaningless calls.
Retry requests should also be linked back to the original task. Otherwise, the bill only shows an increased call count without revealing the root cause.
8.4 Validate Budgets with a Small-Scale Pilot
Before launch, run a pilot with samples covering short text, long contexts, multi-turn interactions, and failure recovery.
Look beyond average cost to high-cost requests and the range of variation. Averages alone tend to underestimate the budget pressure from a few oversized requests, runaway loops, or concentrated peak traffic.
Conclusion: What Matters Is Controllable Delivery Cost, Not the Lowest Listed Price
There is no absolute, context-free ranking of LLM pricing. A reliable method is to first unify the measurement basis, then confirm tier and caching rules, account for costs per request, and finally evaluate effective cost per task together with success rate, latency, stability, and the degree of human intervention.
The option truly worth choosing is not merely the cheapest on the pricing page, but the one that—while meeting quality requirements—keeps costs explainable, predictable, and verifiable, and can be continuously optimized as the business scales.
