LLM API Cost Optimization: Measuring Cost per Task and Tiered Model Selection
This article presents a practical framework for treating LLM usage cost as a measurable, manageable quantity rather than a guess based on list prices. It shows how to build an explainable linear cost model from real call logs, fit per-million-token coefficients through least squares, and use a credit pool to estimate how many tokens each capability tier can support. It then explains how capability tiers, output pricing, and cache hit rates drive cost differences, how to raise cache hit rates, and how to design tiered routing so high-capability models handle planning and review while lighter models handle high-volume execution. You will also find engineering guidance on context compression, retry strategy, streaming, and monitoring metrics, along with common pitfalls and a four-step rollout path.
1. From “Model Capability Comparison” to “Cost per Unit of Task”
In scenarios such as intelligent coding, intelligent customer service, knowledge Q&A, agent workflows, content generation, and data analysis, developers usually prioritize output quality. But enterprise applications must answer a more practical question: how much does each completed, effective task actually cost?
LLM call cost is not determined by the token count of a single request alone. A real task often spans a system prompt, conversation history, tool descriptions, retrieved snippets, user input, model output, failed retries, and long-context compression. If you only compare the surface unit price of a model, you easily underestimate the true consumption of complex tasks. In long-document processing, code generation, multi-turn dialogue, and tool-calling scenarios, factors such as input, output, cache hits, and failed retries all significantly affect the final credit consumption.
A more sensible approach is therefore not to simply ask “which model is cheaper,” but to establish a cost-governance methodology of “measure — fit — select — monitor.” By reverse-engineering credit consumption coefficients for each capability tier from real call records, you can estimate budgets more accurately, design task routing, and find a balance among quality, latency, and cost.
2. Building an Explainable Cost Model
2.1 Base Assumptions and Cache Definition
Assume that for a given call the total input tokens are I, output tokens are O, cache-hit tokens are C, and the final credit consumption is P. The cache definition must be stated clearly: C is the portion of the total input tokens that hits the cache, and the input that does not hit the cache is I' = I - C.
Ignoring short-term fluctuations and special billing rules, we can build the following linear model:
P = a × (I - C) / 1000000 + b × O / 1000000 + c × C / 1000000 + e
where:
a: the credit coefficient per million non-cached input tokens;b: the credit coefficient per million output tokens;c: the credit coefficient per million cache-hit tokens;e: fixed overhead, billing error, or the influence of factors not captured by the model;- the units of
a,b, andcare all “credits / million tokens.”
If the input field in the call logs is already “non-cached input,” the formula can be written as:
P = a × I' / 1000000 + b × O / 1000000 + c × C / 1000000 + e
The purpose here is to avoid double-counting or missing the cache-hit portion. As long as you know the input/output ratio of a task, the cache hit rate, and the size of the credit pool, you can estimate how many tasks can be supported over a given period.
2.2 Fitting Method and Sample Requirements
In practice, collect call records within a time window and organize each call as: non-cached input in millions of tokens, output in millions of tokens, and cache-hit in millions of tokens, each paired with the recorded credit consumption. Then use least squares to fit the coefficients a, b, c, and the intercept e for each tier.
Sample code:
import numpy as np# Each row represents one call:# [uncached input million tokens, output million tokens, cache-hit million tokens]X_raw = np.array([[0.120, 0.020, 0.000],[0.040, 0.030, 0.010],[0.150, 0.010, 0.050],[0.060, 0.015, 0.020],[0.180, 0.080, 0.120],[0.150, 0.050, 0.000],[0.100, 0.100, 0.150],[0.060, 0.025, 0.030],])# Credit consumption corresponding to each cally = np.array([1810, 1670, 2150, 1330, 5890, 3250, 6350, 1830])# Add an intercept column for e in the formulaX = np.column_stack([X_raw, np.ones(len(X_raw))])coeff = np.linalg.lstsq(X, y, rcond=None)[0]print("Coefficients for uncached input, output, cache-hit, intercept:", coeff)
This code outputs 4 coefficients, corresponding to the uncached-input coefficient, the output coefficient, the cache-hit coefficient, and the intercept.
Note especially that you cannot fit a production model directly from a small amount of illustrative data. The samples should at least cover different input/output lengths, whether retries occurred, whether tools were called, whether long-context truncation happened, different task types, and so on. When the sample size is sufficient, the variables are not severely collinear, and unobserved factors are small, the goodness of fit R² may approach 1; otherwise, the residuals will reveal missing variables. For example:
- failed retries;
- tool calls;
- long-context truncation;
- billing differences across entry points;
- dynamic discounts or phased adjustments;
- a minimum billing unit for some requests;
- a cache mechanism that does not hit consistently.
2.3 The Impact of Input/Output Ratio and Cache Hit Rate
Many developers overlook output cost. Input can usually be reduced through caching, compression, retrieval augmentation, and context reuse, whereas output is often hard to reuse and, in many scenarios, costs more per unit. For tasks such as code generation, structured output, long-form writing, and reasoning chains, output length clearly affects total cost.
If the average input is I_avg, the average output is O_avg, and the input cache hit rate is h, then the average credit consumption can be expressed as:
P_avg = a × I_avg × (1 - h) + c × I_avg × h + b × O_avg
If we further express it in terms of total token proportions, assuming input accounts for 80%, output for 20%, and the total tokens are T, then:
P_avg = T × [0.8 × ((1 - h) × a + h × c) + 0.2 × b]
If we focus only on the average credit cost per million total tokens, we can simplify to:
p_avg = 0.8 × ((1 - h) × a + h × c) + 0.2 × b
For example, when input accounts for 80%, output for 20%, and the cache hit rate is h = 0.5, the input-side cost becomes:
Input-side cost = 0.5 × a + 0.5 × c
If the cache-hit coefficient c is clearly lower than the non-cached input coefficient a, then raising the cache hit rate significantly dilutes input cost. Therefore, long-context applications should not look only at “input length,” but also at whether the input is stable, reusable, and recognizable by the cache mechanism.
3. Capability Tiers and Output Pricing Drive the Cost Differences
After fitting from real measurements, a common conclusion is that the credit consumption of models across capability tiers can differ by an order of magnitude or more. High-capability tiers are usually stronger at complex reasoning, long-context planning, code generation quality, and tool-calling stability, but their input and output coefficients are typically higher. Lightweight tiers have lower unit costs and are better suited to high-frequency, short-input, verifiable, and fault-tolerant tasks.
The key here is not “cheaper models are always better,” but layering according to task attributes. The following tier perspective helps:
| Tier | Suitable tasks | Characteristics |
|---|---|---|
| High capability | Planning, review, complex reasoning, critical decisions | High quality, but higher credit consumption per unit |
| Medium capability | Medium-complexity reasoning, code understanding, summarization | A balance of quality and cost |
| Execution | Most business-logic implementation, templated generation, tool calls | Suited to stably executing well-defined tasks |
| Lightweight | Classification, extraction, formatting, batch rewriting, simple Q&A | Low cost and low latency, but may fail on complex tasks |
If you mistakenly assign a lightweight model to a highly complex task, it can lead to poor output quality, format errors, and broken logic, which in turn triggers retries, manual review, and even rework. All told, the cost per unit task ends up higher. Therefore, the core of cost optimization is not “the lowest cost per token,” but “the lowest cost per effective task.”
4. Reverse-Engineering Available Tokens from a Credit Pool: How to Estimate Budget?
Once you have the input coefficient, output coefficient, and cache-hit coefficient for each tier, you can further estimate how many tokens a fixed credit pool can support. Assume the weekly credit pool is E, input accounts for 80%, output for 20%, the cache hit rate is h, and fixed overhead e is ignored. Then the available total tokens can be approximated as:
Available tokens ≈ E / [0.8 × ((1 - h) × a + h × c) + 0.2 × b] × 1000000
where a, b, and c are all credits per million tokens. If cache hits are not considered for now, i.e., h = 0, the formula becomes:
Available tokens ≈ E / (0.8 × a + 0.2 × b) × 1000000
For clarity, we can use illustrative coefficients. Note that the numbers below are only for demonstrating the calculation method and do not represent any specific platform or official billing rules:
| Tier | Input coefficient a (credits/million tokens) | Output coefficient b (credits/million tokens) |
|---|---|---|
| High capability | 80000 | 400000 |
| Medium capability | 32000 | 112000 |
| Execution | 4000 | 8000 |
| Lightweight | 2000 | 2000 |
Calculated with 600,000 weekly credits, 80% input and 20% output, and no cache hits considered:
| Tier | Total tokens supported by 600,000 weekly credits |
|---|---|
| High capability | ~4.17 million tokens |
| Medium capability | ~12.5 million tokens |
| Execution | ~125 million tokens |
| Lightweight | ~300 million tokens |
These numbers vividly illustrate how tier differences affect quota consumption. A high-capability tier delivers higher quality per task, but supports noticeably fewer tasks under the same credit pool; a lightweight tier is suited to high-frequency simple tasks, but if used for complex tasks, it may generate extra rework costs.
In real projects, a more robust approach is not to compute only the average, but to compute a weighted cost by task distribution:
Total cost = Σ[number of tasks of a type × (uncached input tokens × a + output tokens × b + cache-hit tokens × c)] / 1000000 + fixed overhead
If some tasks are called infrequently but consume a lot per call, they also need to be factored into the budget, to avoid long-tail tasks draining the credit pool.
5. How to Improve Cache Hit Rate?
In LLM applications, much of the input is highly repetitive—for example, system prompts, tool definitions, knowledge-base snippets, code-repository context, few-shot examples, fixed templates, and permission rules. If these remain stable across requests, a cache mechanism can reduce the cost of repeated input.
In engineering terms, you can improve the cache hit rate in several ways:
- Separate the system prompt from dynamic user input, and keep the system prompt stable.
- Place tool descriptions, function definitions, and fixed rules in a stable prefix.
- Avoid inserting dynamic variables such as timestamps, session IDs, or random identifiers into the stable prefix.
- Apply a stable ordering to retrieval results to reduce irrelevant variation.
- Summarize and compress multi-turn dialogue rather than appending history indefinitely.
- Segment long documents into structured sections, and preferentially reuse stable segments.
- Monitor the cache hit rate, rather than looking only at average credit consumption.
Cache hits not only reduce cost but may also reduce latency. Especially in scenarios such as intelligent coding, code Q&A, and enterprise knowledge-base assistants, the longer the stable system prompt and fixed context, the more evident the value of caching. However, if the context changes frequently, the cache may fail to hit consistently. In that case, prioritize optimizing the prompt structure rather than simply increasing context length.
6. Tiered Calling Strategy: High-Capability Models Think, Lower Tiers Execute
The core of cost optimization is not “using cheap models for everything” nor “using high-capability models for everything,” but establishing task routing. You can layer scheduling by task complexity, output length, quality requirements, and cost of failure.
6.1 Task Classification
Tasks can be grouped into four categories:
- Planning and review: requires global understanding, solution design, risk flagging, and final quality gatekeeping;
- Complex reasoning: involves multi-step logic, code refactoring, tricky problem diagnosis, and structured analysis;
- Primary execution: completes coding, generation, conversion, completion, and API integration from clear instructions;
- Batch simple tasks: classification, labeling, format conversion, extraction, and simple Q&A.
Different tasks demand different model capabilities. Planning and review require stronger global understanding and risk identification, while batch simple tasks care more about throughput, stability, and low cost.
6.2 Routing Rules
Routing logic can be abstracted into rules or configuration:
def choose_tier(task):if task.need_global_plan or task.need_final_review:return "high"if task.logic_steps >= 4 or task.ambiguity == "high":return "medium"if task.batchable and task.output_length < 512:return "light"return "execution"
This code is only illustrative and does not depend on any specific interface. In practice, it is advisable to make routing policies configurable, to facilitate gradual rollout, rollback, and continuous optimization.
6.3 Balancing Quality and Cost
For high-risk tasks—such as payments, permissions, data deletion, production releases, and compliance review—use a high-capability tier for review. Even at a higher cost, this reduces the probability of incidents. For low-risk, high-throughput tasks—such as log classification, content summarization, and simple label extraction—prefer the lightweight tier.
For medium-complexity tasks, a combined strategy can be used:
- the execution tier generates the result first;
- the lightweight tier performs format validation or an initial screen;
- the high-capability tier conducts spot checks or reviews at key checkpoints.
This combination controls cost on most tasks while retaining quality assurance on critical paths.
7. Engineering Optimization: Context, Retry, Streaming, and Monitoring
7.1 Context Compression
Long context is not always necessary. You can use retrieval augmentation, summarization, and hierarchical memory to send only the content most relevant to the current task to the model. For code scenarios, prioritize retrieving relevant files, functions, interface definitions, and call relationships, rather than stuffing the entire repository into the input. For knowledge Q&A, reduce irrelevant context through retrieval ordering and snippet deduplication.
7.2 Retry Strategy
If model output is unstable, blind retries amplify cost. Set a retry limit, and on failure switch to a higher tier or a stricter prompt template. Retry logs should record the reason—for example, format errors, tool-call failures, timeouts, incomplete content, or missing fields. Classifying and aggregating these helps determine whether the problem stems from model capability, prompt design, or input data quality.
7.3 Streaming Output and User Experience
Streaming output can improve the interactive experience, but it does not inherently reduce total credit consumption. It is better suited to long-form generation, code generation, and interactive dialogue. If a task needs structured results, streaming output still requires subsequent parsing and validation, and that validation cost should also be counted.
7.4 Monitoring Metrics
It is recommended to establish the following metrics:
| Metric | Definition | Purpose |
|---|---|---|
| Average credit consumption per task | Credits / valid task count | Judge whether overall cost is controllable |
| Input, output, and cache-hit proportions | Token distribution | Understand cost structure |
| Cache hit rate | Cache-hit tokens / total input tokens | Judge whether caching is effective |
| Failure rate | Failed requests / total requests | Judge quality risk |
| Retry rate | Retried requests / total requests | Judge wasted consumption |
| Cost per valid output | Credits / valid output tokens | Judge real value |
| Peak-hour credit burn rate | Credits / hour | Judge budget risk |
| Cost distribution by task type | Aggregated by task label | Support routing optimization |
Only by placing credit consumption, call volume, and success rate on the same dashboard can you truly judge whether model selection is effective. Otherwise, it is easy to fall into the trap of “each call looks cheap, yet the overall budget runs out quickly.”
8. Common Pitfalls and Corrections
Looking only at the per-token price of a single call. The real consumption of complex tasks comes from long context, multiple retries, and high output—you cannot look only at the surface unit price.
Ignoring caching. Long system prompts and stable prefixes, if not leveraged through caching, significantly amplify cost.
Using high-capability models everywhere. If a task is inherently simple, the quality gain from a high-capability model is limited, but the cost may multiply.
Using lightweight models everywhere. If a cheap model has a high failure rate, it leads to retries, manual rework, and user complaints, so the total cost is actually higher.
No task classification. Using one strategy for all tasks makes the budget uncontrollable and prevents quality assurance for high-risk tasks.
Not monitoring credit changes. Only discovering that the quota is exhausted after adjusting rules means the optimization window has often already been missed.
The correction is: first build a cost model, then design routing based on the task distribution, then continuously calibrate with monitoring. Cost governance is not a one-time effort but a long-term engineering capability.
9. Implementation Roadmap
You can roll it out in four steps:
Step 1 — Instrumentation and collection. Record, for each call, the total input tokens, non-cached input, output, cache hits, latency, task type, and final credit change.
Step 2 — Fitting and validation. Use regression methods to estimate the coefficients for each tier, and check whether the residuals are acceptable. If the residuals are large, add variables such as failed retries, tool calls, and long context.
Step 3 — Gradual routing. First test the tiered strategy in low traffic, comparing success rate, latency, and credit consumption. Focus on whether the proportion of high-capability calls drops and whether the lightweight model’s failure rate rises.
Step 4 — Continuous governance. Adjust tier boundaries based on task proportions, quality changes, and quota consumption speed. If a certain task type frequently triggers the high-capability model, re-evaluate the task design, prompt templates, or input quality.
10. Conclusion
Reducing cost in LLM applications is not simply about “picking a cheap model,” but about establishing a task-centric cost-governance methodology. Through measured fitting, you can turn vague credit consumption into a computable cost function; through cache hits, context compression, and retry control, you can lower the cost per task; and through tiered selection, you can let high-capability models focus on planning and review while lower tiers handle batch execution.
The ultimate goal is a stable balance among quality, latency, and budget. For a development team, the truly valuable capability is not knowing how much cheaper a given model is today, but being able to keep costs controllable, quality stable, and calling strategies adjustable when billing rules change, task structures shift, and business scales up.
One more caveat: reverse-engineering from personal measurements can only reflect call behavior under a specific time and a specific set of rules; it does not constitute an official price list and may become invalid as billing policies change. Engineering teams should retain configurable, observable, and rollback-capable capabilities to adapt to future changes.
