Optimizing LLM Inference Costs: From Per-Token Pricing to Per-Task Cost
Model pricing per million input and output tokens doesn't reflect what your business actually spends. This article explains why cost per successful task is the metric that matters, breaks down the four variables that drive it, and shows how to build a reproducible evaluation method—complete with a sample cost-calculation function. It also covers incremental delivery for agent-style tasks, scenario-specific model selection, engineering strategies such as tiered routing and token budgets, and the risks to watch for when optimizing LLM inference costs.
Why Cost Per Task Matters
Model services are typically priced per million input tokens and per million output tokens. These unit prices are the sticker price of a model—not the actual cost of your business workload. A single task often involves multiple rounds of calls, data returned from tools, retries after failures, and human review, all of which change the final bill.
A more useful metric for model selection is “average cost per completed task”:
Cost per task = Total spend ÷ Number of successfully completed tasks
Total spend includes the input and output token fees for all calls, including failed ones. Looking only at unit price while ignoring success rate makes it easy to underestimate real spending.
Four Variables That Affect Cost Per Task
1. Input Context Length
The number of input tokens directly determines the base cost of each call. System prompts, conversation history, and retrieved document chunks all count as input. The longer the context, the more expensive—and slower—each call becomes. Common optimizations include:
- Keep only history relevant to the current step, and periodically compress it with summaries;
- Filter and deduplicate retrieval results before concatenating them into the prompt;
- Place stable, unchanging instructions at the prefix so you can take advantage of server-side caching.
2. Output Length and Reasoning Depth
Output tokens usually cost more per unit than input tokens. Some models support different reasoning effort levels; the higher the level, the more intermediate reasoning the model generates before answering, and the more output tokens it consumes. Whether a high level is needed should depend on task difficulty—not on defaulting everything to the maximum setting.
3. Model Activation Pattern
Many large-scale models use sparsely activated architectures. The total parameter count represents knowledge capacity, while the number of parameters actually activated during each forward pass is what correlates with compute cost. Two models with the same total parameters can therefore have very different per-inference costs. When evaluating, focus on the inference metrics published by the vendor and on your own benchmark results—not just parameter scale.
4. Failed Retries and Human Rework
Failed calls still incur charges. Malformed tool-call arguments, outputs that fail structured validation, or code that won’t compile all trigger retries. If humans need to substantially rework the results, that hidden cost should also be included. Improving the first-pass success rate often reduces total cost more effectively than chasing a lower unit price.
Building a Reproducible Evaluation Method
Taking promotional numbers at face value is risky—test set selection, scoring criteria, and runtime environment all affect conclusions. A reliable evaluation should meet these requirements:
- Fixed test set: covers typical real-world tasks and edge cases, with enough samples to support statistical judgment;
- Fixed scoring criteria: define clear pass conditions for each task and use automated assertions wherever possible to reduce subjectivity;
- Complete metric logging: record input tokens, output tokens, latency, retry counts, and the final pass/fail outcome;
- Average over multiple runs: model outputs are stochastic, so a single run is not representative;
- Version tracking: record the model version, prompt version, and parameter configuration so results can be reproduced.
Here is a sample function for computing cost per successful task. It assumes each record contains input tokens, output tokens, and a pass flag:
def cost_per_successful_task(records, price_in, price_out):"""records: list of call records, each with input_tokens, output_tokens, passedprice_in: price per million input tokensprice_out: price per million output tokens"""total_cost = 0.0for r in records:total_cost += r["input_tokens"] * price_in / 1_000_000total_cost += r["output_tokens"] * price_out / 1_000_000passed = sum(1 for r in records if r["passed"])if passed == 0:return float("inf")return total_cost / passed
Because the denominator is the number of successful tasks, the cost of failed calls is fully accounted for. When comparing two approaches, use the same record format and the same set of test tasks.
Incremental Delivery for Agent-Style Tasks
Agent-style applications typically execute multiple steps—retrieving information, calling tools, generating files, and self-checking. If results are delivered only after the entire pipeline finishes, users can’t spot directional drift early, and rework costs rise significantly.
Incremental delivery is a safer approach:
- Break the task into checkpoints, each producing a usable intermediate result;
- Allow users to confirm or adjust direction at key milestones, creating a human-in-the-loop workflow;
- Log token consumption at each checkpoint so clearly off-track execution paths can be stopped early.
This reduces wasted computation and aligns cost more closely with business value.
Model Selection by Scenario
Accuracy and traceability requirements vary widely across industries, so selection should be scenario-specific:
- Scientific research and financial analysis: conclusions need cited sources—combine retrieval-augmented generation (RAG) with programmatic verification of numerical results;
- Legal and compliance text: completeness of clauses is critical—use structured extraction followed by human spot checks;
- Frontend and application development: generated output can be automatically validated through compilation, unit tests, and rendered screenshots;
- Industrial and operations scenarios: results often need to integrate with existing monitoring data—set confidence thresholds and route low-confidence outputs to human review.
Engineering Strategies for Production
At the architecture level, several strategies can lower cost per task:
- Tiered routing: send simple classification or format-conversion tasks to lightweight models, reserving large models for complex reasoning;
- Result caching: reuse historical results for identical or highly similar requests, with a sensible expiration policy;
- Token budgets: set input and output limits per task; terminate early and return partial results when limits are exceeded;
- Batch processing: merge non-real-time requests to reduce call overhead and queueing delays;
- Monitoring and alerting: continuously track cost per task, pass rate, and latency, and alert when metrics deviate.
When building such services on Baidu AI Cloud, you can combine the container platform for elastic scaling, object storage for intermediate files, the logging service for detailed call records, and monitoring and alerting to observe cost and quality trends. These are general-purpose cloud infrastructure capabilities; combined with the strategies above, they form a complete cost governance loop.
Risks and Caveats
- Promotional benchmarks should be independently reproduced, with particular attention to how test tasks are defined and scored;
- Model pricing, free quotas, and billing rules may change, so budgets should include headroom;
- Currency conversion affects cross-region comparisons—use a single billing currency consistently;
- If test samples don’t match the real workload distribution, conclusions lose much of their value;
- Cost optimization must not compromise security and compliance—sensitive data handling must meet the applicable governance requirements.
In summary, the key to evaluating the economics of LLM applications is shifting the focus from “unit price” to “cost per task,” and finding the balance between quality, speed, and cost through reproducible testing and continuous engineering optimization.
