LLM cost optimization starts with measurement, not guesswork. This guide gives you a repeatable way to calculate token spend, compare model choices, reduce unnecessary context, and protect answer quality with evaluation and fallback rules. Because provider prices, limits, and discounts change, use the formulas and worksheets here with the current pricing data for the APIs you actually use.
Overview
The cost of an LLM application is usually driven by more than the model selected. A request can include system instructions, conversation history, retrieved documents, tool results, user input, and generated output. At scale, small inefficiencies in any of these areas become recurring infrastructure costs.
A practical LLM cost optimization process has four goals:
- Measure input and output tokens by task, model, and environment.
- Reduce avoidable context and output without weakening the user experience.
- Route each request to a model that is capable of completing that task, rather than defaulting every request to the most expensive option.
- Use quality guardrails so savings do not create more retries, escalations, corrections, or failed workflows.
The right comparison is not simply “which API has the lowest token price?” It is which configuration delivers an acceptable result at the lowest total cost per successful task. A cheaper model that requires repeated retries may cost more than a stronger model that succeeds on the first attempt.
For a broader reliability review, pair this cost analysis with prompt testing, structured output validation, and model migration checks. Cost and quality should be evaluated together.
How to estimate LLM cost per request
Start by separating input and output usage. Providers may price them differently, and some may offer separate rules for cached input, batch processing, or other request modes. Always copy the current rates and eligibility rules from the provider documentation into your worksheet before calculating a budget.
Use this basic formula:
Request cost = (input tokens ÷ 1,000,000 × input price) + (output tokens ÷ 1,000,000 × output price)
If a provider uses a different billing unit, convert the formula accordingly. For monthly spend, use:
Monthly cost = request cost × requests per month
Then add non-model costs such as embedding generation, vector storage, database queries, file processing, observability, network transfer, and application hosting. For an agent workflow, count every model call in the workflow, not just the first user-facing request.
Cost-per-task worksheet
- Task name: for example, support classification or document summarization.
- Requests per day or month.
- Average input tokens.
- Average output tokens.
- 95th-percentile input and output tokens.
- Model and request mode.
- Current input and output rates.
- Retry rate and average number of calls per successful task.
- Human review, tool, retrieval, and storage costs.
- Quality score, failure rate, and latency target.
Use averages for a baseline, but retain percentile measurements for capacity planning. Long documents, unusually large conversations, and agent loops can make a system appear inexpensive under average usage while creating costly peaks.
Inputs and assumptions
Measure tokens in production-like traffic
Token counts from a development prompt are not enough. Instrument the application at the model boundary and record token usage by task, tenant, route, model, and outcome. Avoid logging sensitive content when it is not required; usage metadata is often sufficient for cost analysis.
Track input components separately where possible: fixed instructions, user content, retrieved context, conversation history, tool output, and formatting overhead. This shows where optimization effort is likely to produce the greatest return.
Compare configurations, not just models
A useful AI API pricing comparison includes both capability and operating behavior:
| Comparison area | Questions to record | Why it affects cost |
|---|---|---|
| Input and output rates | What are the current rates for each billing category? | Determines the direct token cost. |
| Context capacity | Can the model handle the required prompt and retrieved material? | A limit can force chunking, summarization, or extra calls. |
| Quality on your tasks | Does it meet factuality, formatting, and instruction-following thresholds? | Low quality increases retries and human review. |
| Latency and rate limits | What response time and throughput does the application need? | Slow or constrained routes can require more infrastructure or parallel calls. |
| Batch or cached-input options | Does the workload qualify, and what operational delay is acceptable? | Asynchronous or repeated work may have different economics. |
| Reliability and fallback behavior | What happens when a request fails or exceeds a limit? | Fallback calls can materially change cost per successful task. |
Optimization levers and trade-offs
- Reduce prompt overhead: remove duplicated instructions, stale examples, and irrelevant policy text. The trade-off is that over-compression can weaken instruction following.
- Trim conversation history: retain task-relevant turns or maintain a rolling summary. Summarization adds a call, so use it when repeated history would cost more than the summary workflow.
- Tune retrieval: return fewer, more relevant chunks and remove duplicate passages. Less context can reduce grounding if retrieval quality is not tested.
- Limit output length: set an output ceiling appropriate to the task and request a concise schema. A strict limit can truncate valid answers.
- Route by difficulty: use a lower-cost model for classification, extraction, or simple transformations, and reserve a stronger model for ambiguous or high-impact cases. Routing errors can reduce quality.
- Cache stable work: cache repeated requests, deterministic transformations, or reusable retrieval results where freshness and privacy requirements permit. Stale data and cache-key mistakes are the main risks.
- Batch asynchronous work: group offline processing such as enrichment or backfills when latency is flexible. Queues introduce delay and require retry and concurrency controls.
- Set fallback policies: retry transient failures with bounded attempts, then choose a defined fallback or human review path. Unbounded retries are both expensive and difficult to diagnose.
Worked examples
The following example uses hypothetical rates only. It demonstrates the method, not a current pricing claim. Suppose a classification task averages 2,000 input tokens and 300 output tokens per request. Assume, for illustration, an input rate of $X per one million input tokens and an output rate of $Y per one million output tokens.
Cost per request = (2,000 ÷ 1,000,000 × $X) + (300 ÷ 1,000,000 × $Y)
If the application handles 100,000 requests per month, multiply that result by 100,000. Then measure the actual retry rate. If 8% of tasks require a second model call, the expected model-call volume is higher than the request count, and the estimate should reflect that additional usage.
Now consider a context reduction experiment. Removing duplicated instructions and irrelevant retrieved text lowers the average input from 2,000 to 1,200 tokens. Recalculate the direct input cost, then test the new prompt against a fixed evaluation set. A saving is meaningful only if accuracy, schema validity, escalation rate, and user satisfaction remain within agreed thresholds.
For model routing, divide traffic into low-risk and high-complexity categories. Estimate the cost and quality of each route separately, including fallback calls. A routing policy might send straightforward extraction to a smaller model and ambiguous cases to a more capable model. Do not judge the policy by token savings alone; compare cost per successful task and the number of human corrections.
For a RAG application, calculate the full chain: query rewriting if used, embedding generation, retrieval, the final generation call, and any answer validation or retry call. Reducing retrieved chunks may lower generation cost, but poor retrieval can cause more retries or incorrect answers. Use a retrieval test set before making the change permanent.
When to recalculate
Revisit your LLM cost model at least during each regular cloud-cost review and whenever a material input changes. Recalculate after a provider changes prices, context limits, cached-input rules, batch discounts, rate limits, or SDK behavior. Also recalculate after a prompt expansion, retrieval redesign, model replacement, traffic increase, new agent tool, or change in output format.
Use this practical checklist:
- Export recent token usage by task and model.
- Update the worksheet with the provider’s current rates and applicable request modes.
- Compare average and high-percentile token counts.
- Include retries, fallbacks, validation calls, retrieval, and other supporting costs.
- Run prompt and model evaluations before approving a cheaper configuration.
- Review cost per successful task, not only cost per API call.
- Set alerts for abnormal token growth, retry spikes, and unexpected route changes.
- Document the assumptions, date, pricing source, and quality thresholds used.
The most durable approach to reducing LLM costs is a small measurement loop: observe usage, form one optimization hypothesis, test quality, deploy with monitoring, and update the estimate. This keeps savings tied to real application behavior rather than a one-time model comparison. For related implementation work, see the batch LLM processing guide, prompt testing playbook, and LLM model migration guide.