Lowering LLM costs does not require choosing the cheapest model for every request. A more reliable approach is to measure token use, set explicit budgets, remove unnecessary context, cache repeatable work, batch compatible requests, and route each task to a model tier that meets its quality requirements. This guide provides a repeatable cost-optimization workflow, calculation formulas, practical assumptions, and a checklist for revisiting the numbers as pricing, traffic, and model capabilities change.
Overview
LLM application cost is usually driven by four variables: request volume, input tokens, output tokens, and the price of the selected model or service tier. Secondary factors can include cached-input rates, tool calls, embeddings, reranking, storage, retries, and infrastructure around the model. The first step in prompt cost optimization is to separate these costs rather than treating every request as one indistinguishable unit.
A useful monthly estimate is:
Monthly model cost = request volume × [(average input tokens × input price) + (average output tokens × output price)]
Apply the price units used by the provider. If rates are quoted per million tokens, divide the token counts by 1,000,000 before multiplying. Keep separate records for each model, because a blended average can hide an expensive route or an unexpectedly verbose workflow.
Cost reduction should be evaluated alongside quality, latency, reliability, and safety. A smaller prompt that causes more retries may cost more overall. A less expensive model that produces invalid structured output may also increase review and recovery work. The objective is not simply fewer tokens; it is the lowest dependable cost for an acceptable result.
For production prompt engineering, pair cost measurements with an evaluation set. The LLM evaluation frameworks guide explains how to test accuracy, safety, and consistency while changing prompts or models.
How to estimate
1. Measure the baseline
Collect at least several days of representative request data, or use a carefully selected sample if the application is new. Record:
- Requests per day and per month
- Input tokens, including system instructions, user content, retrieved context, and tool results
- Output tokens, including hidden or intermediate fields if they are billed
- Model or route used
- Retries, validation failures, and timeouts
- Latency and a quality score from an evaluation set or human review
Calculate averages and percentiles where possible. Average token use is useful for budgeting, but a high-token tail can determine whether requests exceed context limits or create billing surprises.
2. Set input and output budgets
Define a maximum useful size for each request type. An input budget can cover the system prompt, conversation history, retrieved documents, and tool output. An output budget should reflect the actual task rather than the model's maximum allowance.
For example, a classification endpoint may need a short label and a confidence explanation, while a report-generation endpoint may need a longer response. Use separate budgets instead of one global limit. Enforce them in code, and log when a request is truncated or rejected so that budget pressure does not silently reduce quality.
3. Model the savings from each change
Estimate one optimization at a time. If a shorter prompt reduces average input tokens by 20 percent, apply that change only to the input portion of the formula. If routing moves 70 percent of requests to a lower-cost model, calculate the two routes separately. This makes the estimate auditable and prevents optimistic assumptions from stacking without evidence.
4. Test quality before rollout
Use a fixed test set with expected outcomes, structured-output validation, safety cases, and difficult examples. Compare the baseline and proposed configuration on quality, failure rate, latency, and cost per successful result. Prompt optimization is successful only when the savings survive real workload conditions.
Inputs and assumptions
A cost worksheet should make its assumptions visible. The following fields are enough for a useful first version:
| Input | What to record | Why it matters |
|---|---|---|
| Monthly requests | Expected traffic, including peak and retry behavior | Determines total consumption |
| Input tokens | Average and high-percentile tokens by request type | Reveals prompt and context costs |
| Output tokens | Average, maximum, and stop conditions | Controls response cost and latency |
| Route mix | Percentage of requests sent to each model | Supports model-routing estimates |
| Cache eligibility | Share of repeated or stable content | Identifies possible cache savings |
| Failure rate | Retries, invalid outputs, and fallbacks | Captures hidden request volume |
Separate stable context from variable context. Stable context may include a system prompt, policy instructions, a schema, or a frequently reused document. Variable context includes the current user request, recent conversation turns, and newly retrieved passages. Stable content is a candidate for provider-supported prompt caching or application-level caching, but implementation details, eligibility, retention, and billing treatment vary. Verify those terms before using them in a forecast.
Application-level caching is most reliable for deterministic or acceptably stable operations, such as repeated summaries of an unchanged document, normalized metadata, or a classification result keyed by content hash and prompt version. Include the model identifier, prompt version, relevant configuration, and source-content hash in the cache key. Do not cache responses where user permissions, time-sensitive data, or safety context could change the correct answer.
Batching can reduce overhead for independent jobs such as document classification or nightly extraction. It may not suit interactive requests because it can increase waiting time. Measure cost per completed item, not only cost per API call. For sensitive workflows, review how batching affects isolation, logging, and error handling.
Worked examples
Example 1: Shortening a retrieval prompt
Suppose a support assistant receives 100,000 requests per month. Each request currently includes 6,000 input tokens and produces 500 output tokens. A prompt revision, document deduplication step, and tighter retrieval limit reduce input usage to 4,000 tokens while leaving output unchanged.
Using symbolic prices, the baseline is:
100,000 × [(6,000 × input rate) + (500 × output rate)]
The revised estimate is:
100,000 × [(4,000 × input rate) + (500 × output rate)]
The input portion falls by one-third. The total reduction will be smaller than one-third if output costs are a large share of the total, which is why input and output tokens should be optimized separately. Before deployment, test whether the shorter retrieval context changes answer accuracy or increases abstentions.
Example 2: Routing by task difficulty
Consider a workflow with three request types: intent classification, routine drafting, and complex analysis. Classification may require a compact response and can often be tested against a smaller model. Routine drafting may use a mid-tier model, while complex analysis can remain on a more capable model.
Create a route table with the request share, token profile, model rate, quality threshold, and fallback rule. Then calculate each route independently:
Total cost = cost of classification route + cost of drafting route + cost of analysis route + fallback cost
Do not route by user label alone. Use observable signals such as task type, required output schema, context length, language, or a first-pass confidence check. A fallback should be explicit: define when the application retries, escalates, or asks the user for clarification. Validate every route with the same evaluation framework so that savings are not purchased through inconsistent behavior.
Example 3: Caching repeated document work
If users repeatedly ask questions about an unchanged document, first consider caching a document-level summary or extracted structure rather than caching every final answer. Store the source hash and prompt version with the derived artifact. When either changes, invalidate the entry. This can reduce repeated processing while preserving the ability to answer new questions from the current document.
For broader context-management techniques, see the guide to LLM context window management. For deployment controls, use the LLM application deployment checklist.
When to recalculate
Recalculate the budget whenever a pricing input, workload assumption, or quality requirement changes. In practice, review it on these triggers:
- A provider changes input, output, cached-input, batch, or tool-use pricing.
- A model is replaced, deprecated, updated, or assigned a different route.
- Traffic, average context length, or output length changes materially.
- A new retrieval source, tool, agent step, or safety check adds tokens or requests.
- Retries, fallbacks, or validation failures increase.
- An evaluation shows that a cheaper model or shorter prompt no longer meets the quality threshold.
- The application expands into new languages, document types, or compliance requirements.
Keep a versioned cost sheet with the date, provider assumptions, token samples, route mix, quality results, and decision owner. A practical review sequence is: measure current usage, update provider inputs, recompute each route, run the evaluation set, inspect failure and latency changes, then approve or reject the rollout. Repeat the same process before major releases rather than relying on an old estimate.
Cost-optimization checklist: instrument tokens; separate input and output costs; set request-type budgets; remove duplicate context; cap retrieval results; cache only safe, stable artifacts; batch suitable offline work; route by task requirements; validate structured outputs; count retries and fallbacks; compare cost per successful result; and document the assumptions for the next review.
For a complete production workflow, connect these calculations to prompt versioning, regression tests, tool validation, and security review. The production-ready prompt engineering workflow and tool-calling guide provide useful companion practices. Revisiting the budget after each meaningful pricing or architecture change keeps LLM costs understandable without sacrificing dependable results.