LLM API costs are easier to control when every request can be explained. This guide shows how to build a repeatable cost model for input tokens, output tokens, cached context, retries, tools, and batch workloads—then use it to decide whether caching, batching, model routing, or prompt changes will lower spend without weakening application quality.
Overview
An LLM API bill is rarely determined by model choice alone. Usage volume, prompt size, generated output, failed requests, tool calls, retrieval context, and traffic shape all affect the total. A low per-token rate can still produce a large bill if an application resends a long system prompt on every turn or retries requests without an idempotency strategy.
The most reliable approach is to separate cost into measurable components:
- Input tokens: instructions, conversation history, retrieved passages, user content, and tool results sent to the model.
- Output tokens: text, structured data, or tool-call arguments generated by the model.
- Cached input tokens: eligible repeated context processed under a provider's caching rules.
- Retries: additional attempts caused by timeouts, rate limits, malformed output, or application errors.
- Tool-related charges: external API calls, search, code execution, storage, or other services invoked around the model request.
- Batch or asynchronous work: requests submitted for delayed completion under the provider's batch terms.
Cost optimization should be evaluated with quality, latency, and reliability together. A cheaper model that increases retries or human review may not reduce the true cost of the workflow. For production measurement, pair this worksheet with an LLM observability process that records tokens, latency, errors, model, prompt version, and outcome.
Pricing reference to maintain
Provider pricing changes frequently, and plans may distinguish between standard, cached, batch, and priority processing. Do not copy a rate into production code without checking the provider's current documentation. Maintain a small pricing register with the date it was verified:
| Field | Record for each model or service |
|---|---|
| Standard input | Price per billing unit, usually a token quantity defined by the provider |
| Standard output | Price per billing unit for generated tokens |
| Cached input | Eligibility, minimum prefix or token requirement, retention, and read/write treatment |
| Batch | Discount or separate rate, supported endpoints, submission limits, and completion window |
| Tools | Per-call, per-result, compute, search, storage, or third-party API charges |
| Limits | Rate limits, context limits, maximum batch size, and retry guidance |
How to estimate
Use a monthly worksheet rather than a single average request. Start with request volume, then calculate each token category separately.
- Estimate monthly requests. Use observed production volume when available. Otherwise, multiply active users by expected requests per user and include scheduled or background jobs.
- Measure or estimate tokens. Track average and high-percentile input and output tokens separately. Averages can hide long conversations and large retrieval results.
- Apply the applicable rates. Convert the provider's displayed units into a consistent worksheet unit. If a provider quotes a rate per one million tokens, divide token volume by one million before multiplying by the rate.
- Add retries explicitly. If the expected retry rate is 4%, multiply planned requests by 1.04, or model failed request categories separately when their prompts differ.
- Add tools and surrounding infrastructure. Include search, databases, embeddings, queues, storage, observability, and any external API charges that are triggered by the request.
- Compare scenarios. Keep a baseline and change one variable at a time: shorter context, a different model, caching, batching, or fewer retries.
A copyable worksheet can use these fields:
monthly_requests = interactive_requests + scheduled_requests
billable_attempts = monthly_requests * (1 + retry_rate)
input_cost = input_tokens / billing_unit * input_rate
output_cost = output_tokens / billing_unit * output_rate
cached_input_cost = cached_tokens / billing_unit * cached_rate
retry_cost = retry_attempts * average_cost_per_retry
tool_cost = tool_calls * cost_per_tool_call
monthly_total = input_cost + output_cost + cached_input_cost + retry_cost + tool_cost + fixed_costsFor a request with multiple stages, calculate each stage independently. A retrieval step may send a rewritten query, retrieved passages, and a final answer prompt; treating those as one average can hide the largest contributor.
Inputs and assumptions
Prompt caching
Caching is most useful when a substantial prefix repeats across many requests, such as a stable system prompt, policy text, schema, or shared reference material. Verify the provider's minimum cached length, exact prefix-matching rules, retention period, cache creation or write treatment, and whether cached reads use a different rate. A changing timestamp, request identifier, or user-specific text placed near the beginning of the prompt can prevent reuse.
Estimate the benefit with:
uncached_input = repeated_prefix + variable_context
cached_input_savings = eligible_repeated_tokens * (standard_input_rate - cached_input_rate) / billing_unitCaching does not automatically reduce output cost, tool charges, or the cost of content that cannot be reused. It may also be unsuitable when prompts are rarely repeated or when retention requirements conflict with the data being cached.
Batch processing
Batch processing can suit offline classification, document enrichment, evaluation runs, indexing, and other work that does not need an immediate response. Record the provider's current batch discount, supported models, input format, failure behavior, cancellation rules, and completion window before estimating savings.
Batch work may increase elapsed time and complicate partial-result handling. It is usually a poor fit for interactive chat, urgent moderation decisions, or workflows that require a user to wait. Model batch economics separately from interactive economics; do not assume the same retry or completion behavior.
Model routing
Routing assigns simple tasks to a lower-cost model and reserves a more capable model for requests that need it. Define the routing rule in observable terms—for example, task type, context length, required structured-output complexity, or evaluation score. Then track escalation rate, retries, review rate, and user outcomes. A routing policy should be versioned like a prompt and tested against a fixed evaluation set; see this LLM evaluation guide for a suitable measurement framework.
Quality and reliability assumptions
Cost projections should include the cost of bad outputs. Track validation failures, regenerated responses, human review, support cases, and downstream API failures. Structured output validation and bounded retries can be more economical than accepting malformed data; the implementation patterns in structured output prompts are useful here.
Worked examples
Consider a hypothetical monthly workload of 100,000 requests. The application sends 1,200 input tokens and receives 300 output tokens per request. Assume a 3% retry rate. These figures are illustrative inputs, not provider benchmarks or prices.
First calculate volume:
- Billable attempts: 100,000 × 1.03 = 103,000 attempts.
- Input tokens: 103,000 × 1,200 = 123.6 million tokens.
- Output tokens: 103,000 × 300 = 30.9 million tokens.
Apply the current provider rates in your worksheet:
baseline = (123.6m / billing_unit * input_rate)
+ (30.9m / billing_unit * output_rate)
+ tool_charges
+ fixed_costsNow suppose 700 of the 1,200 input tokens are a stable eligible prefix, and the remaining 500 are variable. If the cache is actually reused for 80% of attempts, cached tokens equal 103,000 × 700 × 0.80. Recalculate the input portion as standard-rate variable tokens plus cached-rate eligible tokens. Include any cache write or creation treatment specified by the provider. The savings is the baseline input cost minus the new input cost, not the total bill.
For an offline workload, compare a second scenario using batch processing. Keep token volume constant and replace the standard input and output rates with the verified batch rates. Then add operational costs for queueing, monitoring, failed records, and a possible second submission. The comparison is valid only if the completion delay is acceptable and the batch endpoint supports the model and features your workflow uses.
Finally, compare model routing. If 70% of requests can meet the required evaluation score on a lower-cost model and 30% remain on the original model, calculate both segments separately. Add the cost of escalations, retries, and quality review. Never estimate routing savings from headline token rates alone.
When to recalculate
Revisit the worksheet whenever a provider changes a model price, cached-token rule, retention period, batch discount, supported feature, context limit, or billing unit. Also recalculate after changing a system prompt, retrieval configuration, conversation-memory policy, output schema, retry logic, or tool set. These changes can alter token volume even when request counts remain stable.
For routine operations, review costs during each monthly budget cycle and compare projected spend with actual usage by model, endpoint, tenant, and feature. Set alerts for sudden changes in input tokens, output length, retry rate, cache-hit rate, and tool calls. A rising retry rate can erase the benefit of a cheaper model; a falling cache-hit rate can make a previously useful cache uneconomical.
Use this action checklist:
- Export the latest token and request counts.
- Verify every rate against the provider's current pricing and feature documentation.
- Recalculate baseline, caching, batching, and routing scenarios separately.
- Check latency, quality, validation failures, and tool-related costs alongside dollars.
- Record assumptions, pricing verification date, and owner of the worksheet.
- Run a controlled test before changing the production model or retry policy.
Cost optimization is a measurement loop, not a one-time model selection. Keep the worksheet, observability data, prompt versions, and evaluation results connected so that a lower invoice does not conceal slower responses, weaker answers, or less reliable automation. For prompt and context changes, the related guides on context window management and prompt versioning provide practical controls.