LLM cost optimization is usually less about choosing the cheapest model and more about controlling what your application sends, repeats, retrieves, and generates. This guide gives you a repeatable method for estimating token costs, finding waste, and reducing AI API spending without weakening answer quality. It includes practical formulas, a token-budget worksheet, model-routing guidance, and worked examples you can revisit after pricing or usage changes.
Overview
Every LLM request has a cost profile. The main variables are input tokens, output tokens, request volume, model rates, and any provider-specific features such as cached input, batch processing, tool calls, or retrieval. A useful optimization process makes those variables visible before changing prompts or models.
The first mistake to avoid is treating token count as the only measure of quality. Removing context indiscriminately can increase retries, incorrect answers, human review, or support work. The goal is not the smallest prompt; it is the lowest total cost for an acceptable outcome.
For an AI chatbot, agent workflow, or other LLM application, track at least these measures:
- Cost per request: the estimated model and tool cost for one completed interaction.
- Cost per successful task: total spend divided by responses that meet your acceptance criteria.
- Input and output tokens: separated by model and request type.
- Retry rate: repeated calls caused by timeouts, invalid structured output, tool errors, or quality failures.
- Quality indicators: task accuracy, citation validity, structured-output success, latency, or human review results.
Cost optimization belongs alongside prompt engineering, evaluation, and deployment rather than after them. Before changing production behavior, use a small evaluation set to confirm that a cheaper prompt or model still performs the required task. The LLM evaluation and prompt testing workflow is a useful companion for that step.
How to estimate
Start with a request-level formula. If a provider charges separately for input and output, use:
Cost per request = (input tokens ÷ 1,000,000 × input rate) + (output tokens ÷ 1,000,000 × output rate)
Then estimate a period:
Monthly cost = cost per request × requests per month
For a more realistic estimate, divide requests into categories instead of using one average. For example, a customer-support application may have short classification calls, normal answer calls, and long escalation calls. Calculate each category separately, then add the totals:
Total monthly cost = (short-call cost × short-call volume) + (answer-call cost × answer-call volume) + (escalation-call cost × escalation-call volume)
Build a worksheet with one row per model and request type. A practical comparison table looks like this:
| Input | What to record | Why it matters |
|---|---|---|
| Provider and model | Model identifier and deployment | Rates and capabilities differ by model |
| Input tokens | Average and high-percentile prompt size | Long context can dominate spend |
| Output tokens | Average and maximum completion size | Verbose responses increase cost and latency |
| Request volume | Daily or monthly calls by workflow | Small inefficiencies compound at scale |
| Special pricing category | Cached, batch, or standard processing | Eligibility and rates may differ |
| Quality result | Pass rate, retry rate, or review rate | Prevents false savings from lower quality |
Do not hard-code provider rates into an evergreen calculator. Store them as editable inputs and verify the provider's current pricing page before making a budget decision. Context limits, caching terms, batch availability, and model names can change. A pricing calculator is only as reliable as its latest inputs.
Inputs and assumptions
Measure the full prompt, not just the user message
In production, input tokens may include system instructions, conversation history, retrieved documents, tool definitions, examples, metadata, and the current user message. Log these components separately where possible. This shows whether the main source of growth is chat history, RAG context, a large system prompt, or a tool schema.
A useful token budget is:
Request budget = fixed instructions + conversation history + retrieved context + tool definitions + user input
Assign a target and a hard ceiling to each component. For example, a retrieval step can select the most relevant passages and discard duplicate or low-value content before the final model call. This is often safer than shortening the system prompt blindly.
Separate quality-critical context from repeated context
Mark each prompt component as essential, conditional, or optional. Essential content might define output rules or safety boundaries. Conditional content might be included only for a particular intent. Optional content may be useful in a few edge cases but not in every request.
Repeated content deserves special attention. If the same long instructions are sent on every request, investigate provider-supported prompt caching or application-level caching. Confirm how cached tokens are billed and how changes invalidate the cache before including the feature in your estimate.
Model routing and output control
Use a capable model where the task requires it, but route predictable subtasks to an appropriate lower-cost option when evaluation shows equivalent results. Classification, extraction, deduplication, and simple formatting may not need the same model as complex reasoning or difficult synthesis.
Output limits are another direct control. Specify the required format, maximum length, and stopping condition. A structured response with a concise schema can cost less than a prose response that later needs another model call for parsing. Avoid asking for hidden reasoning or unnecessary explanations; request only the fields your application uses.
Account for retries and downstream costs
If 10 percent of requests require a second call, your effective cost is higher than the first-pass estimate. Include retries, fallback models, moderation or classification calls, embedding requests, reranking, and tool execution where they are part of the workflow. For agents, count each model turn rather than treating one user interaction as one API request.
Worked examples
Example 1: reducing repeated context
Assume an application makes 20,000 monthly requests. Each request contains 2,400 input tokens and produces 500 output tokens. For a planning exercise, use illustrative rates of 0.80 currency units per million input tokens and 3.00 currency units per million output tokens. These are worksheet assumptions, not current provider prices.
The estimated monthly input volume is 48 million tokens, and output volume is 10 million tokens. The estimated cost is therefore:
- Input: 48 × 0.80 = 38.40 currency units
- Output: 10 × 3.00 = 30.00 currency units
- Total: 68.40 currency units before retries and other services
Suppose prompt analysis shows that 900 input tokens are repeated reference material that can be replaced with a short identifier and a cached or selectively retrieved context block. The revised input is 1,500 tokens per request, reducing monthly input volume to 30 million tokens. At the same illustrative rate, input cost falls to 24.00 currency units, while output cost remains 30.00. The estimated total becomes 54.00 currency units.
Before shipping the change, compare answer accuracy, citation or source use, escalation rate, and retries on a fixed test set. The saving is real only if the workflow does not create enough failures to offset it.
Example 2: controlling output length
Assume another workflow makes 8,000 calls per month. Its average output is 1,200 tokens because the prompt asks for a detailed explanation, although the application displays only a summary and three action fields. A revised prompt requests those fields in a compact schema and sets an appropriate output limit. If the average output falls to 450 tokens, output usage is reduced by 62.5 percent.
That percentage is a usage change, not a guaranteed monetary saving. Apply it to the output portion of your current estimate, then check whether structured-output failures, follow-up questions, or user dissatisfaction increase. This is why cost per successful task is a better decision metric than raw tokens alone.
Example 3: routing simple tasks
Suppose a support assistant's monthly calls are split between intent classification, article retrieval, and final answer generation. Measure each stage independently. If classification consumes a small prompt and has a stable evaluation result on a less expensive model, route that stage separately while keeping the final answer model unchanged. This avoids a risky full migration and makes the saving attributable to one controlled change.
For broader model decisions, use a capability-and-cost matrix rather than price alone. The LLM model selection framework can help organize quality, latency, context, integration, and cost requirements.
When to recalculate
Recalculate your LLM budget whenever a pricing input, traffic pattern, or prompt architecture changes. At minimum, review it during each monthly cost review and after any material model or workflow update.
- Provider changes: Recheck input, output, cached, batch, and tool-related rates, along with context limits and model availability.
- Prompt changes: Measure token counts after adding instructions, examples, conversation memory, or tool definitions.
- Traffic changes: Update request volume, peak usage, agent turns, and retry assumptions.
- Quality changes: Recalculate when pass rates, escalations, hallucinations, or structured-output errors move.
- Architecture changes: Include new RAG retrieval, embedding, reranking, moderation, caching, or fallback calls.
- Model migrations: Run the same evaluation set and compare cost per successful task, not just the listed token rate.
Use this practical review sequence:
- Export recent usage by model, workflow, input tokens, output tokens, and retry status.
- Calculate average and high-percentile token counts for each request type.
- Update provider rates and feature assumptions from current documentation.
- Identify the largest repeated context, longest outputs, and highest-retry workflows.
- Make one controlled change, such as trimming retrieval context, routing classification, or tightening output format.
- Run regression tests and compare quality, latency, retries, and cost per successful task.
- Record the new assumptions and set a date for the next review.
Small, measured changes are safer than an untested rewrite of every prompt. Keep the worksheet, evaluation results, and production measurements together so your team can explain why costs changed and quickly recalculate after the next pricing or usage shift.