How to Calculate Per-Question LLM Inference Costs for Model Selection
This article explains why per-question inference cost is a more useful model-selection metric than list price alone, how to break down input and output token costs, and how to calculate average cost from a fixed test set. It also covers common measurement pitfalls, best practices for comparing model versions, deployment recommendations for monitoring and routing, and a practical note on reconciling internal estimates with Baidu AI Cloud billing data.
How to Calculate Per-Question LLM Inference Costs for Model Selection
1. Why Per-Question Cost Matters More Than Unit Price
A model’s list price describes the price of one billing unit, such as the cost per million tokens. In actual business use, the cost of a single request depends on prompt length, model output length, and whether additional reasoning processes are included. Two models with similar unit prices can differ by several times in total cost on the same batch of tasks. Therefore, a more useful metric for model selection is the average cost of completing one question or one task.
Per-question cost puts unit price, usage, and task definition into the same dimension, making it easier to compare the cost-effectiveness of different models and versions. It also helps teams determine whether an optimization truly reduced costs, rather than merely changing the pricing method.
2. Cost Components
Most large model services bill input tokens and output tokens separately, and the unit prices are usually different. A common billing structure is as follows:
- Input tokens: includes system prompts, conversation history, retrieved context, and the user’s current question.
- Output tokens: the answer content generated by the model.
- Reasoning-related tokens: some models produce intermediate reasoning content before answering. Whether and how these tokens are billed should be based on the official billing documentation for the relevant service.
In actual measurement, input and output should be counted separately. They should not be combined into a single total token count and then multiplied by an average unit price. Otherwise, tasks with longer outputs will be underestimated, and tasks with shorter outputs will be overestimated.
3. Calculation Method: From Test Set to Average Cost per Question
Calculating per-question cost can be divided into four steps.
1. Fix the Test Set and Measurement Scope
The number of questions, difficulty distribution, and prompt template in the test set must be fixed. If different questions are used for each test, the cost figures cannot be compared directly. The measurement scope must also be consistent, including whether system prompts are counted, whether retrieved context is counted, and whether failed retry requests are included in the total.
2. Record Token Usage for Each Request
Most service responses return the number of input tokens and output tokens used for that request. The test script should save these two fields for each record, rather than saving only the final average, so that anomalous samples can be reviewed later.
3. Convert to Per-Question Cost Using Unit Prices
The formula for per-question cost is:
Per-question cost = (input tokens × input unit price + output tokens × output unit price) ÷ 1,000,000
The example code below demonstrates this calculation. The unit prices in the code are placeholder values and should be replaced with data from the official pricing page of the relevant service.
from dataclasses import dataclass@dataclassclass Pricing:input_per_million: float # Price per million input tokens (CNY); replace with official pricingoutput_per_million: float # Price per million output tokens (CNY); replace with official pricingdef cost_per_question(input_tokens: int, output_tokens: int, pricing: Pricing) -> float:cost = (input_tokens * pricing.input_per_million+ output_tokens * pricing.output_per_million)return cost / 1_000_000def average_cost(records: list[dict], pricing: Pricing) -> float:if not records:raise ValueError("Test records are empty; cannot calculate the average")costs = [cost_per_question(r["input_tokens"], r["output_tokens"], pricing)for r in records]return sum(costs) / len(costs)if __name__ == "__main__":pricing = Pricing(input_per_million=2.0, output_per_million=8.0) # Placeholder pricesrecords = [{"input_tokens": 1200, "output_tokens": 600},{"input_tokens": 900, "output_tokens": 1500},]print(f"Average cost per question: {average_cost(records, pricing):.6f} CNY")
4. Aggregate and Reconcile
After calculation, the amount derived from the script should be reconciled with the service bill. If there is a large discrepancy, it usually means the measurement scope is inconsistent. For example, retry requests may have been missed, the billing method for cache hits may be different, or the price version may have changed.
4. Common Pitfalls
Looking only at list price and ignoring output length. Some models have lower unit prices but produce lengthy answers, so their final per-question cost may not be lower. During model selection, use the output lengths from real tasks for measurement, not estimates.
Ignoring hidden reasoning overhead. Enabling deep reasoning or multi-step thinking modes often significantly increases output tokens. If the mode used during testing is not consistent with the production environment, the resulting cost data will be distorted.
Mixing discount bases. Batch-call discounts, cache-hit discounts, annual or monthly subscriptions, and other offers can change the effective unit price. When comparing models, use prices after discounts and document the basis used.
Test set changes causing distorted comparisons. If two versions use questions of different difficulty, a cost decrease may only reflect that the tasks became simpler. Version comparisons must keep the test set, prompt template, and billing period fixed.
5. Correct Comparison Method for Version Iterations
When evaluating old and new versions of the same service, the following principles are recommended:
- Use the same test set, with exactly the same question order and prompt template.
- Make calls within a similar time window to avoid price adjustments crossing the test period.
- Report both quality metrics and cost metrics. A cost decrease alone is not meaningful; cost savings accompanied by lower answer quality are often unacceptable.
The formula for calculating the reduction is:
Reduction = (old version per-question cost − new version per-question cost) ÷ old version per-question cost × 100%
The reduction only shows the percentage change in cost, not the business value. The team also needs to confirm whether the new version meets accuracy requirements on key tasks.
6. Three Recommendations for Enterprise Deployment
Monitor usage continuously. Record the model name, input tokens, output tokens, and business tag for each request at the application layer, and set thresholds through logging services or monitoring and alerting systems. When the per-question cost of a certain task type rises abnormally, the cause can be identified promptly, such as a prompt accidentally concatenating a large block of conversation history.
Set budget caps. Set budget caps for individual users, individual business lines, or daily totals. When a cap is exceeded, automatically downgrade to a lower-cost model or route the request to human handling. Budget control should be implemented at the gateway or API wrapper layer, rather than separately in each business codebase.
Route by task tier. Tasks such as classification, extraction, and format conversion usually do not require the strongest model. Routing simple tasks to lower-cost models and reserving complex reasoning tasks for high-capability models can reduce average per-question cost while keeping overall quality stable.
7. Practical Note for Baidu AI Cloud
If a team uses large model services provided by Baidu AI Cloud, it should use the official billing documentation as the source of truth and periodically align bill data with internal measurement results. After exporting the bill, the team can aggregate token usage for each task type by business tag and then apply the formula in this article to calculate per-question cost. This supports both financial accounting requirements and model selection and budget planning.
8. Summary
Per-question cost is a bridge between model capability and business budget. When measuring it, fix the test set and measurement scope, count input and output separately, and perform conversions based on official billing rules. When comparing versions, observe quality and cost together to avoid incorrect conclusions caused by inconsistent measurement bases. With this method, teams can quickly assess cost-effectiveness after each model update and adjust routing and budget strategies accordingly.
