To reduce LLM API costs without losing quality, stop paying full price for tokens you send repeatedly, stop sending easy work to your most expensive model, and stop generating tokens nobody reads. In practice that means prompt caching for stable context, routing simple requests to a cheaper model, trimming context and output, and batching anything that can wait. None of it degrades output if you run a fixed evaluation set before and after each change. That step is the one most cost-cutting exercises skip, and it is why they sometimes go wrong.
The arithmetic behind every bill is simple. You pay for input tokens, output tokens and, on reasoning models, the hidden thinking tokens, which are billed as output. Output tokens usually cost several times more per token than input. Agents multiply all of this: a ten-step loop that re-sends its full transcript at every step pays for the early messages ten times over. Once you see a bill in those terms, the levers become obvious.
Find out where the tokens actually go
You cannot optimise a single monthly invoice. The first thing to check is whether every API call is tagged with the feature that made it, the model used, and the input, output and cached token counts the provider returns in each response. Push those fields into whatever you already use for logs or metrics, and after a week you will have a cost-per-feature breakdown that usually surprises people.
The culprits tend to be mundane. A system prompt that started at 300 tokens has grown to 4,000 because every bug fix added another paragraph of instructions. A retrieval step pulls twenty chunks when the answer is always in the top three. An agent re-sends a long tool output on every turn. Schema validation fails and the code silently retries three times. A summarisation feature returns 800 words when the UI shows 150. None of these is a model problem; they are integration problems, and they are covered in more depth in our guide to LLM integration in production.
Rank features by spend, then by spend per successful outcome. A feature that costs a lot but replaces hours of manual work may be fine. A feature that costs a little but fails half the time is costing more than it appears, because every retry and every human correction is part of its real price.
The levers, roughly in order of effort
Prompt caching
Prompt caching is the closest thing to free money in LLM cost optimisation. Providers store the processed prefix of a prompt for a short window, and later requests that start with the identical prefix are billed at a steep discount for that portion. Anthropic exposes this explicitly through cache breakpoints, as described in its prompt caching documentation; OpenAI applies it automatically to sufficiently long prompts, as set out in its prompt caching guide.
The engineering work is ordering. Put everything stable first: system instructions, tool definitions, few-shot examples, reference documents. Put everything that varies last: the user message, the retrieved chunks, the current date. The most common way teams break caching is by inserting a timestamp or a request ID at the top of the system prompt, which makes every prefix unique. Reordering tool definitions between calls does the same. Check the cached-token field in your responses; if it reads zero on a feature you expected to cache, something near the top of the prompt is changing.
Caching has limits. Cache lifetimes are measured in minutes, so a feature called a few times a day gains little, and on some providers writing to the cache costs slightly more than a normal request. It pays most on high-traffic features with long, stable prefixes, which is exactly where most of the spend usually sits.
Model routing
Most production traffic does not need the strongest model available. Extracting fields from an invoice, classifying a support ticket or rewriting a sentence are well within the reach of small, cheap models. Model routing sends each request to the cheapest model that can handle it reliably.
There are two workable patterns. Static routing assigns models by task: extraction and classification go to a small model, multi-step reasoning and long-form drafting go to a large one. It is predictable and easy to debug. Cascade routing tries the cheap model first, validates the result against a schema or business rules, and escalates to the larger model only when validation fails or confidence is low. Cascades save more, but they need a validator you trust, otherwise you are simply accepting worse answers more cheaply.
The failure mode to watch is the tail. A small model may match the large one on 95% of cases and fail quietly on the awkward 5%, which are often the cases that matter most to customers. Routing decisions should be driven by evaluation results on real data, not by benchmark tables. In agent systems the same logic applies per role: a planner may justify a frontier model while the workers that summarise tool outputs do not, which is one of the trade-offs discussed in single agent vs multi-agent systems.
Cut input tokens
Retrieval is usually the biggest input lever. Tune the number of chunks, add a reranker, and deduplicate overlapping passages before they reach the prompt. If you are stuffing whole documents into context because retrieval felt unreliable, fix retrieval; it is cheaper in the long run than paying for the whole document on every call. Our piece on RAG vs fine-tuning covers when each approach earns its keep.
For conversations and agent loops, summarise or truncate history rather than replaying it verbatim. Strip HTML, boilerplate footers and base64 blobs from tool outputs before feeding them back. Trim tool schemas: long descriptions on twenty tools that are rarely used add up on every single request.
Cap output tokens
Because output is priced higher, verbosity is expensive. Ask for structured JSON rather than prose where a machine will consume the result, set sensible maximum output limits, and tell the model the target length explicitly. On reasoning models, use the lowest reasoning effort setting that passes your evals; thinking tokens are invisible in the response but very visible on the invoice.
Batch anything that can wait
Nightly enrichment, bulk classification, backfills and report generation rarely need an answer within seconds. Both OpenAI and Anthropic offer batch interfaces that accept large job files, return results within a stated window of up to 24 hours, and charge substantially less per token than synchronous calls; OpenAI documents the details in its Batch API guide. Moving an overnight workload to batch is often a one-day change with no quality impact at all, since the model and prompt are unchanged.
Do not call the model at all
The cheapest token is the one never sent. If a request can be answered by a lookup, a regular expression or a rule, answer it that way and keep the model for genuine ambiguity. Exact-match response caching helps for repeated identical queries, such as the same product question asked by many users. We describe how to split work between deterministic logic and models in combining LLM output with rule-based decisions.
Comparing the levers
Not every lever suits every workload. This is how they stack up on the dimensions that matter when you are deciding what to try first.
| Lever | Effort | Quality risk | Best suited to |
|---|---|---|---|
| Prompt caching | Low: reorder prompts | None | High-traffic features with long, stable system prompts or documents |
| Batch API | Low to medium: async job handling | None | Overnight, bulk and backfill work with no latency requirement |
| Output caps and structured output | Low | Low, if limits are tested | Features consumed by code, or with verbose responses |
| Input trimming and retrieval tuning | Medium | Medium: missing context hurts accuracy | RAG features and agent loops with growing history |
| Static model routing | Medium | Medium: needs per-task evals | Mixed workloads with clearly separable task types |
| Cascade routing | High: needs a reliable validator | Medium to high on edge cases | High-volume tasks with checkable outputs |
| Rules and response caching | Medium | Low for deterministic cases | Repetitive queries and structured decisions |
The pattern is clear: the zero-risk levers are also the cheapest to implement, so they go first. Routing and aggressive trimming come later, once you have the measurement in place to catch regressions.
Hold quality fixed with an evaluation set
Every cost change is a quality experiment, and it should be treated as one. Before touching anything, build a golden set of real inputs, somewhere between 50 and 200 cases per feature is a practical start, with expected outputs or scoring criteria. Include the awkward cases deliberately: long documents, ambiguous requests, inputs in Irish or other languages your users send, malformed data. Run the set on the current configuration to get a baseline, then rerun it after each change and compare.
Score what the business cares about, not what is easy to measure. For extraction that is field-level accuracy; for drafting it may be a rubric graded by a stronger model and spot-checked by a person. Change one lever at a time so you know which change caused a regression. For higher-stakes features, shadow the new configuration against live traffic for a few days before switching. Our guide to AI agent evaluation goes through the mechanics.
Alongside evals, put hard guardrails on spend. Set per-feature and per-tenant budgets, cap the number of steps an agent may take, and alert on sudden jumps in tokens per request. A runaway loop is one of the few ways an LLM bill can multiply overnight, and a step cap prevents it at no cost to quality.
When the API is the wrong shape for the workload
Past a certain volume of steady, predictable traffic, the question shifts from optimising API usage to whether some workloads belong on your own hardware or a dedicated endpoint. Open-weight models running locally make sense for high-volume, narrow tasks such as classification or embedding, and when data residency rules make external calls awkward. They bring their own costs: hardware, operations, monitoring and model updates. The trade-offs are laid out in self-hosted LLM vs API. For a small-scale view of what that looks like, we run agents alongside local inference in our own lab, described in Inside the D3X Home Lab: Proxmox, DGX Spark and AI Agents. For most businesses, though, the API levers above recover a meaningful share of spend long before self-hosting becomes the right answer.
This week: tag every call and price your top three features
You do not need a project to start. A few hours of work this week gives you the data every later decision depends on.
- Add a feature tag to every LLM call and log model, input tokens, cached tokens and output tokens from the response.
- After five working days, rank features by total spend and pick the top three.
- For each, check whether the cached-token count is above zero and whether a timestamp or variable sits near the top of the prompt.
- Pull 50 real inputs for the most expensive feature and save them as the first version of your evaluation set.
With that in hand, prompt caching and batching changes can usually ship the following week with no quality risk, and you will know exactly what routing could save before you attempt it.
D3X Solutions LABS is an AI engineering studio in Ireland that builds and tunes production LLM systems. When we look at an LLM bill, we start by instrumenting calls per feature, building an evaluation set from real traffic, and then applying caching, routing, trimming and batching in order of risk, with before-and-after numbers for each change. If you want a second pair of eyes on where your token spend is going and which levers are safe for your workloads, book a free 30-minute call and bring your last month of usage data.
Frequently Asked Questions
What is the quickest way to reduce LLM API costs?
Prompt caching and batch processing are usually the quickest wins because they do not change the model or the prompt content, so quality is unaffected. Caching requires reordering prompts so stable content comes first, and batching suits any workload that can wait hours for results. Both can often ship within days.
Does prompt caching affect output quality?
No. Caching only changes how the provider bills and processes the identical prefix of your prompt; the model sees the same input and produces equivalent output. The only risk is that it fails to apply, which you can detect by checking the cached-token count in API responses.
What is model routing for LLMs?
Model routing sends each request to the cheapest model capable of handling it, rather than using one large model for everything. It can be static, assigning models by task type, or a cascade, where a small model tries first and the request escalates if validation fails. Routing decisions should be based on evaluations of your own data, not public benchmarks.
Why are output tokens more expensive than input tokens?
Generating tokens is computationally heavier than reading them, so providers price output several times higher per token. Reasoning models also bill their hidden thinking tokens as output. That is why capping response length and using structured output often saves more than trimming the prompt.
How do I know if cutting costs has hurt quality?
Build a fixed evaluation set of real inputs with expected outputs or scoring criteria, run it before any change to get a baseline, and rerun it after each change. Change one thing at a time and include difficult edge cases deliberately. For high-stakes features, shadow the new configuration on live traffic before switching.
Is self-hosting an LLM cheaper than using an API?
It can be for high, steady volumes of narrow tasks, but hardware, operations, monitoring and model updates add real cost. Most businesses recover significant spend through caching, routing and batching on the API first. Self-hosting becomes compelling mainly when volume is predictable or data residency rules make external calls difficult.
Want this working in your business?
D3X Solutions LABS builds AI agents and automation that pay back fast. Book a free 30-minute call and we will look at where AI would pay back first in your workflow.
Get in touch






