Lowering LLM API costs does not require making every prompt shorter or moving every workload to the least expensive model. This guide gives you a repeatable method for measuring token use, comparing model and request choices, reducing duplicated context, and protecting response quality with tests and spending controls.
Overview
LLM cost management starts with a simple principle: optimise the complete workflow, not just the prompt. An apparently cheap request can become expensive when it includes a large system prompt, repeated documents, unnecessary conversation history, long generated answers, retries, and validation calls. Conversely, a more capable model may be the economical choice for a difficult task if it reduces retries or manual review.
The most useful baseline is cost per successful task. Track the number of requests, input tokens, output tokens, retries, failed validations, and user-visible outcomes. This is more informative than looking only at the provider invoice or the average cost of an individual API call.
Five levers usually provide the clearest starting points:
- Measure: record input and output tokens by workflow, model, route, and environment.
- Remove waste: shorten repeated instructions, trim irrelevant history, and retrieve only useful context.
- Match the model to the task: reserve more capable models for cases that genuinely need them.
- Reuse work: cache stable prompts, retrieval results, or completed responses where freshness allows.
- Control demand: set budgets, rate limits, output limits, and alerts before usage grows unexpectedly.
These measures should be evaluated against a quality set. For example, use representative questions and check factual accuracy, schema validity, completeness, latency, and refusal or escalation behaviour. Token optimisation that increases correction work is not a real saving.
How to estimate LLM API costs
Use the pricing inputs published for the specific model, endpoint, and billing mode you are evaluating. Because providers can change prices, context limits, caching rules, and batch options, keep these values in configuration rather than hard-coding them into application logic.
A basic estimate is:
Estimated cost = (input tokens ÷ billing unit × input rate) + (output tokens ÷ billing unit × output rate)
If a provider uses separate rates for cached input, uncached input, batch processing, or other request types, calculate each category separately. For a workflow, extend the formula:
Monthly cost = requests × cost per request × (1 + retry rate) + fixed platform costs
This is only a planning model. A production estimate should also account for:
- different prompt lengths across user segments;
- the distribution of short, average, and unusually large requests;
- tool calls, retrieval steps, moderation or validation calls, and summarisation passes;
- cache hit and miss rates;
- batch eligibility and the effect of delayed processing;
- failed requests, retries, and fallback models.
Do not rely only on an average. Calculate a typical case and a high-usage case, such as a request at the 90th or 95th percentile of token volume. This helps reveal whether a small number of oversized prompts are driving the bill.
Inputs and assumptions for a cost review
Build a small review sheet for each AI workflow. Record the following inputs:
| Input | What to record | Why it matters |
|---|---|---|
| Request volume | Daily and monthly calls | Shows the effect of traffic growth |
| Input tokens | Average and high-percentile tokens | Identifies repeated or oversized context |
| Output tokens | Average, maximum, and stop behaviour | Reveals unconstrained generation |
| Model mix | Model used for each route | Supports task-level model selection |
| Retry rate | Transport, validation, and application retries | Connects reliability with cost |
| Cache rate | Eligible requests and successful hits | Estimates the value of reusing stable work |
Separate fixed content from variable content. A long system prompt, schema, policy block, or reference document may be sent on every request even though it rarely changes. Consider whether it can be shortened, represented more consistently, retrieved only when relevant, or handled through an available caching feature. Do not remove instructions merely because they consume tokens: first test whether they prevent errors or unsafe output.
Output tokens deserve equal attention. Use clear response boundaries, structured output, a suitable maximum output limit, and concise format instructions. A JSON schema can reduce parsing ambiguity, but it should not be used to request fields the application does not need. For production validation patterns, see LLM Output Guardrails and Structured Output Prompting.
Worked examples
Example 1: reducing repeated context
Imagine a support workflow that sends the same 2,000-token policy block with every request. It receives 10,000 requests per month. Before changing the model, the team tests three alternatives: remove duplicated wording, retrieve only the relevant policy section, and use a supported caching option where the content remains stable.
The team records the input-token reduction, cache hit rate, answer accuracy, escalation rate, and latency. It then applies the provider's current input rates to both the original and revised token totals. The saving is not the percentage of text removed; it is the difference in billable input tokens after accounting for cache misses and any additional retrieval calls.
Example 2: controlling output length
A code-review workflow asks for a full explanation, a list of findings, suggested patches, and a final summary. Many users need only structured findings and a short rationale. The team creates a concise structured output prompt and sets a reasonable output ceiling. It compares the old and new versions on a fixed evaluation set.
If the revised workflow uses fewer output tokens without reducing valid findings or increasing follow-up requests, its cost per successful review improves. If the shorter response causes developers to ask for explanations in a second call, the apparent saving may disappear. Measure the complete interaction rather than the first response alone.
Example 3: routing by task difficulty
Classify requests into simple, moderate, and complex categories using criteria that can be tested, such as required context, reasoning depth, or output constraints. Route simple transformations and extraction tasks to a suitable lower-cost model, while retaining a more capable model for cases that fail confidence or validation checks.
Run both routes against the same test cases before rollout. Track successful completion, retries, human corrections, latency, and cost. A fallback route should be included in the estimate, because an inexpensive first attempt is not economical if it frequently triggers a second call.
Token optimisation techniques that preserve quality
- Trim conversation history: summarise resolved turns and retain only decisions, constraints, and open questions.
- Retrieve selectively: use focused chunks and metadata filters instead of attaching an entire knowledge base.
- Use prompt templates: keep instructions consistent and remove duplicated examples or contradictory wording.
- Apply few-shot examples carefully: include examples that cover real edge cases, not a large collection of near-duplicates.
- Cache stable work: cache safely reusable results, retrieval outputs, or fixed context only when freshness and privacy requirements permit.
- Batch suitable jobs: group asynchronous classification or enrichment tasks when the workflow does not require an immediate response.
- Prevent avoidable retries: validate request construction, enforce schemas, and distinguish transient failures from bad outputs.
- Set budgets: apply per-user, per-workflow, and overall monthly limits with alerts before a hard stop is reached.
For prompt changes, use a small evaluation suite rather than intuition. The LLM evaluation guide can help structure test cases, while the AI coding prompt templates provide examples of task-specific instructions.
When to recalculate
Revisit the estimate whenever a provider changes model pricing, token accounting, context limits, caching features, batch availability, or SDK behaviour. Also recalculate after a model migration, a major prompt revision, a new retrieval source, a change in traffic mix, or a rise in retries and validation failures.
A monthly spend review is a practical minimum for an active production workflow. Use this checklist:
- Export usage by model, route, environment, and request type.
- Compare actual input and output tokens with the assumptions in your estimate.
- Identify the largest workflows and the highest-token request patterns.
- Check cache hits, retries, fallback calls, and validation failures.
- Run quality tests before approving a prompt, model, or routing change.
- Update rates and limits from the relevant provider documentation.
- Record the new baseline, owner, date, and next review trigger.
The most sustainable approach is to make cost a visible engineering metric alongside quality, latency, and reliability. Measure first, change one lever at a time, and keep an evaluation set for every important workflow. That process reduces LLM API costs without treating response quality as an afterthought.