LLM Inference Cost Optimization: From Per-Token Price to Total Cost of Ownership
Per-token pricing alone doesn't tell you what a task actually costs. This article breaks down LLM cost into its real components—input, output, cached tokens, and reasoning tokens—and introduces cost per successful task as the key metric for model selection. It covers a practical metrics framework, a reusable Python cost calculator, and engineering practices for cutting spend: cache-friendly prompt design, output length control, difficulty-based routing, retry reduction, context compression, and cost patterns specific to multi-step agents and multimodal inputs. It closes with guidance on building a business-specific evaluation set and setting up ongoing price and cost governance.
1. Why You Should Measure Cost by Task, Not by Unit Price
A model’s price per million tokens is public information, but it doesn’t equal your actual business expense. The total cost of a task is determined by three factors: the number of input and output tokens consumed, whether caching is hit, and the probability that the task ultimately succeeds.
If a model has a lower unit price but requires more inference rounds, longer outputs, or more retries, it may not actually be cheaper for completing the same task. Teams should instead track cost per successful task, the average spend required to complete one valid task. It’s calculated as:
Cost per successful task = Single task cost ÷ Task success rate
Single task cost is the sum of input cost, cached input cost, and output cost. Success rate must be measured against an evaluation set. For example, if two approaches have the same single task cost but success rates of 60% and 90% respectively, the latter’s cost per successful task is only two-thirds of the former’s.
2. Main Components of LLM Pricing
Most model services bill based on the following categories.
1. Standard input tokens. These include system prompts, conversation history, retrieved document snippets, and user queries. Longer input means higher cost.
2. Output tokens. Generated content is billed as output, typically at a higher rate than input. Controlling output length is a direct way to reduce cost.
3. Cache-hit input tokens. When a request’s prefix matches a previous request, the server can reuse already-computed intermediate results, and that portion is billed at a lower rate. Long system prompts, fixed templates, and shared reference documents are good candidates for this mechanism.
4. Reasoning-related tokens. Some models perform internal reasoning before producing an answer, and these tokens are billed as well. The more complex the task, the larger this overhead becomes.
5. Speed and quota modes. Some services offer accelerated modes that trade higher quota consumption for faster response times. Whether to enable this should be decided by comparing the latency benefit against the added cost, not enabled by default.
Understanding these components helps teams identify where cost is concentrated and target optimization accordingly.
3. A Metrics Framework for Evaluating Model Cost-Effectiveness
A single metric can mislead model selection decisions. It’s worth tracking the following five metrics together:
| Metric | Meaning | Why It Matters |
|---|---|---|
| Task pass rate | Share of outputs meeting acceptance criteria | Determines effective output volume |
| Cost per successful task | Cost divided by pass rate | Core economic metric |
| End-to-end latency | Time from request to complete result | Affects interaction experience and throughput |
| Stability | Frequency of timeouts, errors, and malformed output | Affects retry cost and operational burden |
| Output controllability | Whether format and length requirements are consistently followed | Affects post-processing cost |
The Python code below shows how to turn this calculation into a reusable function. The prices in the code are example parameters; in practice, replace them with the latest figures from your provider’s pricing page.
from dataclasses import dataclass@dataclassclass PriceTable:input_per_m: float # Price per million standard input tokensoutput_per_m: float # Price per million output tokenscached_per_m: float # Price per million cache-hit input tokensdef single_task_cost(price: PriceTable, input_tokens: int,output_tokens: int, cached_tokens: int = 0) -> float:"""Calculate the cost of a single task (unit matches the price table)."""fresh_tokens = max(input_tokens - cached_tokens, 0)cost = (fresh_tokens * price.input_per_m+ cached_tokens * price.cached_per_m+ output_tokens * price.output_per_m)return cost / 1_000_000def cost_per_success(price: PriceTable, input_tokens: int,output_tokens: int, success_rate: float,cached_tokens: int = 0) -> float:"""Calculate the cost per successful task."""if not 0 < success_rate <= 1:raise ValueError("success_rate must be in the range (0, 1]")return single_task_cost(price, input_tokens, output_tokens,cached_tokens) / success_rate# Example: hypothetical parameters, for illustration onlymodel_a = PriceTable(input_per_m=8.0, output_per_m=40.0, cached_per_m=0.4)model_b = PriceTable(input_per_m=2.0, output_per_m=10.0, cached_per_m=0.2)for name, price, rate in [("Option A", model_a, 0.95), ("Option B", model_b, 0.80)]:c = cost_per_success(price, input_tokens=6000, output_tokens=800,success_rate=rate, cached_tokens=4000)print(f"{name} cost per successful task: {c:.6f}")
The value of this code is standardizing the comparison process. Price, usage, and success rate are tracked as separate variables, so when a provider updates pricing or you re-run an evaluation, you only need to update the corresponding values to redo the comparison.
4. Engineering Practices for Reducing Cost
4.1 Design Prompt Structures That Maximize Cache Hits
Caching depends on prefix consistency. The most effective approach is to place stable content at the front of the request and variable content at the end.
- System instructions, role definitions, and output specifications go first, and must stay byte-identical across requests.
- Fixed templates, reference documents, and other long static content follow immediately after.
- Dynamic content such as user input, real-time data, and timestamps goes at the end.
If you insert a timestamp that changes on every request near the front of the prompt, caching will almost never hit. This kind of small detail often causes significant waste and is worth checking specifically in code review.
4.2 Control Output Length and Format
Output tokens are typically priced higher, so limiting generation length matters. Specific approaches include:
- Setting a reasonable maximum output length to prevent verbose explanations.
- Requiring structured output, such as JSON with fixed fields, to cut down on extraneous text.
- For classification or judgment tasks, asking the model to return a label directly instead of a full paragraph.
# Constrain output to a fixed structure for easy parsing and less wasted textprompt_template = """You are a ticket classification assistant. Output only JSON in this format:{"category": "...", "priority": "high|medium|low"}Do not output anything else.Ticket content: {ticket_text}"""
4.3 Route Requests by Task Difficulty
Not every request needs the most capable model. A routing design might follow these steps:
- Classify tasks by type (classification, extraction, rewriting, complex reasoning) into difficulty tiers.
- Route simple tasks to a lower-cost option by default, with a quality threshold set.
- Escalate to a more capable model only when the low-cost option’s output confidence is insufficient or validation fails.
This approach depends on having reliable quality validation in place. Without a validation step, there’s no trigger for escalation.
4.4 Reduce Unnecessary Retries
Retries directly amplify cost. Start by distinguishing the cause of failure:
- Input problems, such as excessive length or malformed data, should be caught before the call is made.
- Output format errors can often be fixed with tighter constraints or local parsing fixes, without a full retry.
- Server-side timeouts or rate limiting should use exponential backoff with a capped maximum number of retries.
4.5 Compress Context
In most applications, context grows as a conversation continues. Three common compression methods:
- Periodically summarize conversation history, keeping only the facts and constraints relevant to the current question.
- When retrieving documents, return only the relevant snippets rather than entire documents.
- Deduplicate repeated information so the same content doesn’t enter the context multiple times.
5. Cost Characteristics of Long Workflows and Multi-Step Agents
The cost growth of multi-step tasks often exceeds intuition. If every step resends the full history to the model, the input volume at step n is proportional to n, and the cumulative input volume across n steps approaches O(n²). Doubling the number of steps can multiply total input cost several times over.
To control this growth, consider the following measures:
- Set a maximum number of steps; beyond that threshold, escalate to human review or terminate the task.
- Truncate and summarize tool outputs, keeping only the fields needed by subsequent steps.
- Generate a state summary at the end of each stage, and have subsequent steps use the summary instead of the full log.
- Move deterministic steps (such as field validation or format conversion) into regular code instead of delegating them to the model.
6. Cost and Evaluation for Multimodal Input
Images, screenshots, and design mockups also count as tokens. In scenarios like page generation or UI replication, larger input assets mean higher cost. Consider these approaches:
- Describe the page using a structured design spec (colors, font sizes, spacing, component hierarchy) first, and attach a screenshot only when necessary.
- Crop screenshots to keep only the region relevant to the task.
- Evaluation shouldn’t rely solely on whether the generated code runs; it should also include visual regression comparison combined with human scoring to judge fidelity.
Success criteria for these tasks are often subjective, so the evaluation set needs clear scoring rubrics, such as layout consistency, acceptable color deviation, and whether font size hierarchy matches.
7. Building Your Own Evaluation Set
Public benchmark scores reflect general capability and don’t necessarily match your business needs. Teams should build an evaluation set tied to their own use case, following these steps:
- Sample 200 to 500 cases from real business data, covering common cases, edge cases, and cases prone to errors.
- Define automatically checkable acceptance rules for each sample, such as whether required fields are present, values are correct, and format is valid.
- For samples that can’t be judged automatically, arrange manual spot checks and track scoring consistency.
- For each candidate option, record pass rate, single task cost, latency, and error rate separately.
- Use cost per successful task as the primary ranking criterion, while verifying that latency and stability meet your business’s minimum requirements.
The evaluation set should be updated regularly, since business data changes and service versions and pricing change as well.
8. Price Monitoring and Cost Governance
Service pricing can change over time, whether through reductions, new modes, or quota rule changes. To keep your cost structure manageable, consider the following:
- Externalize pricing configuration. Keep unit prices in a config file or config center rather than hardcoding them in application code. When prices change, you only need to update the configuration.
- Tag usage. Track token usage by project, feature module, and user tier to pinpoint high-cost areas.
- Set budget alerts. Define daily and monthly budgets per project, trigger alerts as thresholds approach, and optionally auto-throttle.
- Review regularly. Track the monthly trend in cost per successful task, and determine whether changes stem from longer prompts, declining success rates, or routing logic no longer working as intended.
When using model services on Baidu AI Cloud, the same cost accounting methodology applies. Specific billing rules are governed by the official pricing page and documentation; confirm the latest figures before launching a project.
Conclusion
Reducing the cost of LLM applications comes down to breaking cost down to the task level. Unit price, caching, output length, retry count, and success rate together determine final spend. Teams should first build an evaluation set, then use cost per successful task to compare options, and finally optimize through cache-friendly design, tiered routing, and context compression. Conclusions reached this way are reproducible and can be adjusted quickly as pricing and model capabilities change.
