LLM API Selection: Evaluating Costs Beyond Unit Price
Selecting the right LLM API requires looking beyond the price per token. This article explores how to build a comprehensive cost model that accounts for token usage, call frequency, and task success rates. It covers key factors influencing effective costs, strategies for establishing an evaluation benchmark, and common pitfalls in model selection, providing a practical engineering approach to optimizing your LLM expenditures.
1. Why Lower Unit Prices Do Not Always Mean Lower Costs
LLM service providers typically charge based on the unit price per million tokens for input and output. When unit prices drop, many teams assume total costs will decrease accordingly, but this is not always true. The unit cost is only one factor in the final bill. Actual expenditure is determined by three components: how many tokens each call consumes, the average number of calls required to complete a task, and whether the result passes validation on the first attempt.
Consider a simplified example: a new model version is 30% cheaper per token than the old one, but its reasoning process is longer, producing twice as many output tokens for the same task. The cost per call has not actually decreased. Conversely, if a new model is more stable with structured outputs, reducing the retry rate from 15% to 2%, the effective cost will drop significantly even if the unit price remains unchanged. Therefore, model selection should shift focus from “price per call” to “price per successful task.”
2. Understanding Billing Units: Input, Output, and Context
Tokens are the basic unit LLMs use to process text. Because tokenization methods differ for Chinese and English, the token count for the same text can vary across models. Therefore, you cannot estimate costs directly by character count; you must rely on the actual usage fields returned by the API response.
Billing typically includes the following types of usage:
- Input tokens: Includes system instructions, conversation history, retrieved reference materials, and user questions. The longer the context, the larger the input portion.
- Output tokens: The answers generated by the model. The output unit price is usually higher than the input price, making verbose answers more expensive than expected.
- Cache-related usage: Some services support caching and reusing repeated prefix content. The billing method when cache hits occur may differ. Whether this applies depends on the specific rules of the service provider, so refer to the official documentation.
- Reasoning-related usage: Some models generate internal reasoning tokens. Whether these tokens are billed and how they are billed must be verified separately during evaluation.
In engineering, you should log input tokens, output tokens, model version, and call latency simultaneously; otherwise, post-hoc root cause analysis becomes difficult.
3. Building a Total Cost Model
When evaluating costs, you can use the following framework:
Cost per call = (Input token count / 1,000,000) Input unit price + (Output token count / 1,000,000) Output unit price
Expected cost per task = Cost per call * Average number of calls per task
Effective cost (Cost per successful task) = Expected cost per task / Task success rate
Here, the average number of calls includes retries, tool call rounds, and multi-step reasoning splits. The task success rate is determined by business acceptance criteria, not by the model’s own self-evaluation. This model compares price, usage, and quality under a single metric, avoiding the bias caused by looking solely at unit price.
4. Key Factors Affecting Effective Cost
In real-world projects, the following factors have the greatest impact on cost:
(1) Context length. Many applications send the entire conversation history or large documents to the model, causing input tokens to grow linearly with turns. Common practices include summarizing and compressing historical conversations, retaining only fragments relevant to the current question, and limiting the number of retrieved items returned.
(2) Output length. Explicitly specifying word limits or structural templates in the prompt can significantly reduce unnecessary output. For classification or extraction tasks, requiring the model to return only JSON fields is usually more token-efficient than requesting free text, and easier for programs to parse.
(3) Retries and failure handling. When the output format is invalid, times out, or content fails to meet requirements, the system usually retries the call. A higher retry rate means a higher effective cost. Common methods to reduce retries include constraining the output format, performing validation on the application side, and building a regression set for failed samples.
(4) Model selection and routing. Not all requests need the most powerful model. Tasks can be tiered by difficulty: simple classifications or rewrites go to smaller models, while complex reasoning and long document analysis go to larger models. The routing rules themselves need to be validated with an evaluation set to avoid quality degradation from misrouting.
(5) Batching and asynchronous processing. For tasks that do not require real-time responses, such as offline summarization or data cleaning, batch or asynchronous APIs can be used. Providers often have different billing or rate-limiting policies for these, so the decision to use them should align with the business’s latency requirements.
5. Establishing an Evaluation Benchmark
Comparing prices alone cannot yield a conclusion; you must compare both quality and cost on the same set of tasks. We recommend building an evaluation benchmark using the following steps:
Step 1: Collect samples. Extract representative requests from production logs, covering common scenarios and edge cases. A starting batch of 100 to 300 samples is usually sufficient. Samples must be desensitized and must not contain sensitive personal information.
Step 2: Define acceptance criteria. Write explicit judgment rules for each type of task, such as whether the fields are complete, whether the facts align with the reference materials, and whether the format can be parsed by a program. Automate the checks wherever possible, and use manual spot-checks for cases that cannot be automated.
Step 3: Fix runtime conditions. Run candidate models using the same prompts, samples, and parameters, and record the usage, latency, and results for each call.
Step 4: Calculate metrics. Track the success rate, average input/output tokens, average call count, average latency, and calculate the cost per successful task using the formulas above.
Step 5: Make a decision. Among the candidates that meet the quality threshold, choose the one with the lowest effective cost. If two solutions have similar costs, prioritize latency, stability, and migration cost.
6. Sample Code
The following example demonstrates how to calculate effective cost based on usage logs. The pricing parameters are placeholders; actual values should be based on the official pricing of the service provider.
from dataclasses import dataclass@dataclassclass CallRecord:input_tokens: intoutput_tokens: intsuccess: booldef cost_per_call(rec: CallRecord, price_in: float, price_out: float) -> float:# Price is per million tokens; currency unit is unified by the callerreturn (rec.input_tokens / 1_000_000) * price_in + (rec.output_tokens / 1_000_000) * price_outdef effective_cost(records: list[CallRecord], price_in: float, price_out: float) -> float:total_cost = sum(cost_per_call(r, price_in, price_out) for r in records)success_count = sum(1 for r in records if r.success)if success_count == 0:return float("inf")# Total cost divided by the number of successful tasks equals the average cost per successful taskreturn total_cost / success_count# Compare two candidate solutions (prices are placeholders)logs_a = [CallRecord(1200, 400, True), CallRecord(1100, 350, False), CallRecord(1150, 380, True)]logs_b = [CallRecord(1500, 250, True), CallRecord(1400, 240, True), CallRecord(1450, 260, True)]cost_a = effective_cost(logs_a, price_in=2.0, price_out=8.0)cost_b = effective_cost(logs_b, price_in=3.0, price_out=6.0)print(f"Solution A cost per successful task: {cost_a:.6f}")print(f"Solution B cost per successful task: {cost_b:.6f}")
The key point of this code is the statistical methodology: failed calls also incur charges, so they must be included in the total expenditure before dividing by the number of successful tasks. Counting only the costs of successful requests will systematically underestimate the actual cost.
7. Common Pitfalls
- Pitfall 1: Looking only at the input unit price. The output unit price is typically higher, and the output length is heavily influenced by the model’s style.
- Pitfall 2: Using model self-evaluation to judge quality. Models are often overly optimistic about their own outputs. Acceptance should rely on programmatic validation or independent human standards.
- Pitfall 3: Drawing conclusions from a small sample. A few dozen samples have high variance, especially when edge cases are underrepresented, leading to incorrect conclusions.
- Pitfall 4: Ignoring migration costs. Switching models may require adjusting prompts, rewriting parsing logic, and redoing regression testing. These labor costs should be factored into the overall evaluation.
- Pitfall 5: Assuming a one-time evaluation is permanently valid. Model version updates and changes in business data will alter the results. Regular re-testing is recommended, and the evaluation script should be integrated into continuous integration.
8. Implementation Recommendations
We recommend that teams proceed in the following order. First, build a logging system to ensure every call’s usage and results are traceable. Second, establish a small-scale evaluation set and fix the acceptance criteria. Third, use the effective cost formula to compare candidates and select the lowest cost option that meets the quality threshold. Finally, set up monitoring metrics, such as daily average effective cost, retry rate, and average output length, with alerts triggered for anomalies.
In summary, model selection is a continuous engineering process. Unit price is only the starting point; what truly determines expenditure is the actual resources consumed per successful task. By connecting the cost model, evaluation benchmark, and monitoring, teams can quickly determine whether switching to a new version is worthwhile during model iterations.
