Cutting an LLM API bill comes down to sending fewer tokens, paying less for the tokens you do send, and capping what a mistake can cost. Ten tactics cover almost everything, and three of them together (reusing a stable prompt prefix, capping output and routing easy work to a cheaper model) took 62% off a worked example below.
Where does LLM API money actually go?
A request costs its input tokens at the input rate plus its output tokens at the output rate, and on most models the output rate is several times higher. On this gateway the formula is written out in the cost-control guide: input tokens times the input rate, plus output tokens times the output rate, with cached input at the cached rate and reasoning tokens counted as output. Nothing hides behind it. The billing documentation shows the same arithmetic, and every request lands on the usage page with its tokens and cost.
The worked example in this post is a support bot that answers questions from a policy handbook. It makes 200,000 calls a month. Each call sends 6,000 input tokens (the handbook, the instructions and a few turns of chat) and gets back 700 tokens. We priced it at $2.00 per million input tokens, $10.00 per million output tokens and $0.20 per million cached input tokens, which are real published figures: Fireworks lists Kimi K3.1 Pro at exactly those three rates on its pricing page. The numbers are an illustration, not a quote for any model on our list.
Do the sum for one call. Input is 6,000 times $2 per million, or $0.012. Output is 700 times $10 per million, or $0.007. The call costs $0.019, and input is 63% of it even though output is five times more expensive per token. That is the pattern in most chat and document apps: the prompt is long, the answer is short, and the prompt is resent every time. A writing tool that generates a 2,000-token article from a 100-token prompt would flip the split. Know which of the two you are before you optimise, because the tactics below attack different halves.
| Part of a call | Tokens | Rate per 1M | Cost per call | Share of the call |
|---|---|---|---|---|
| Input (handbook, instructions, history) | 6,000 | $2.00 | $0.012 | 63% |
| Output (the answer) | 700 | $10.00 | $0.007 | 37% |
| Total per call | 6,700 | $0.019 | 100% | |
| Total per month | $3,800 | at 200,000 calls |
Which 10 tactics reduce the bill, and what do they cost you?
The table lists all ten with the honest trade-off. Effects marked “published” come from a provider page we link in the section; the others depend on your traffic, and we say so instead of inventing a percentage.
| # | Tactic | Typical effect | What it costs you |
|---|---|---|---|
| 1 | Measure by key | Finds the real cost driver | A key per app, ten minutes |
| 2 | Smallest model that passes | Often the largest single saving | A small test set |
| 3 | Cap the output | Cuts output tokens directly | Answers may be cut short |
| 4 | Send less history | Cuts input on every turn | Older context is lost |
| 5 | Reuse the prefix (caching) | Published: 50% to 98% off cached input | A stable prompt layout |
| 6 | Batch what can wait | Published: 50% off | Up to 24 hours of delay, no streaming |
| 7 | Turn reasoning down | Fewer output tokens | Weaker answers on hard tasks |
| 8 | Route by difficulty | Cheap model takes the easy share | A routing rule to maintain |
| 9 | Ceiling on every key | Caps the worst case | A key stops when it hits the limit |
| 10 | Count fees and duplicate attempts | Avoids paying twice | Reading some fine print |
Tactic 1: how do you measure before you change anything?
You measure by giving each app or environment its own key and reading the usage page for a week. The page lists every request with its time, key, model, input, output and cached tokens, cost and duration, and exports to CSV, as the routing documentation describes. Failed requests leave a record too, with the error in place of a cost.
Two numbers matter. The first is the input-to-output split of your median request, which tells you which half of the bill to attack. The second is the cost of your worst 1% of requests, because one agent that loops or one user who pastes a book can cost more than a thousand normal calls. If you have never looked, expect a surprise. Spreading apps across keys takes a few minutes and makes every later step measurable. The guide to estimating a monthly LLM bill and the cost calculator turn the token counts into a monthly figure before you spend anything.
Tactic 2: why choose the smallest model that passes your test?
Because model price is the biggest lever, and the price gap between a small and a large model is often an order of magnitude. On Together’s and Fireworks’ pages, GLM 5.3 is $1.40 input and $4.40 output per million tokens, while GLM 5.3 Flash is $0.15 and $0.50. That is roughly nine times cheaper per token for the smaller one, on both sides of the call. The Together pricing page and the Fireworks page list both, read on 26 November 2026.
The catch is that a cheap model only saves money if it passes your task. Write 30 to 50 real prompts with the answers you would accept, run them against the small model first, and move up a size only for the cases that fail. This takes an afternoon and beats any rule of thumb. Our model comparison and the cheap open model price guide show per-million rates, and the guide to choosing a model for coding agents applies the same test to code.
Development is the cheapest place to start. The 47 ids ending in :free share 100 requests and 3,000,000 tokens a day per account, so you can write prompts, build the test set and debug the integration without spending a cent. Keep the model id in an environment variable, as the code sample further down does, and the switch to a priced id is one line. The free models list has every id, and the chat lets you try a prompt before writing code (the guide to the browser chat shows how it shares the allowance with the API). Free ids work with a $0 balance, so this stage needs no top-up. We do not recommend a free id for production traffic: the free tier comparison explains why.
Tactic 3: how do you cap the output?
Set max_tokens on every request, and tell the model how long the answer should be. Without a cap a model may write until its own maximum, and you pay for every token. A line such as “Answer in at most three sentences” in the system prompt is, in the words of our own cost-control page, the cheapest optimisation there is.
Pick the cap from data, not instinct. Look at the 95th percentile answer length in your usage export and set the cap a little above it. Too low and answers end mid-sentence, which you will notice in testing and can fix by raising it; too high and the cap does nothing. In the worked example a cap plus a brevity instruction trimmed 25% of output tokens, worth about $350 a month, which is the smallest of the three savings. Output caps matter more when the output rate is high or the answers are long. They also protect you: a capped call has a known worst case.
One more reason is specific to this gateway. Before a request runs it reserves an estimate of its cost, and the errors page notes that a lower max_tokens lowers the reservation. A small balance can refuse a request with a large cap while accepting the same request with a small one.
Tactic 4: why send less history?
Because in a chat the whole conversation is billed again on every turn, so cost per turn grows with the length of the chat. A ten-turn conversation pays for turn one ten times. Our cost-control guide says it in one line: drop old turns, summarise them, and remove images once they have been discussed.
Three practical rules help. Keep the last few turns verbatim and replace everything older with a short summary written once. Drop tool outputs after the model has used them, since a 3,000-token search result rarely matters five turns later. And do not resend a document the model has already summarised unless the next question needs the exact wording. The code sample below keeps the last six messages. It is crude, and a summary step is better, but even crude trimming beats an unbounded history.
There is a quality side to this too. A shorter, cleaner context often gives better answers, because the model is not hunting for the relevant line in 40,000 tokens of earlier chat. If an agent is your biggest spender, the coding agent key guide covers how agents resend history and how to cap them.
Tactic 5: how does prompt caching cut the input bill?
Prompt caching lets the provider reuse its work when many requests start with the same text, and it bills the reused part at a much lower cached rate. It is the biggest saving in the worked example, and the one most people leave on the table because their prompt layout defeats it.
The published numbers are large. OpenAI’s prompt caching guide says reused tokens are billed at the reduced cached-input rate, discounted up to 95%. For its GPT-5.6 and later models a cache write costs 1.25 times the normal input rate and a read costs 0.1 times, and OpenAI works out that one write plus nine full reads costs 2.15 times a prefix’s normal cost, against 10 times without caching. Fireworks says on its pricing page that cached input is billed at half price or less with no write fee, and lists DeepSeek V4.1 Flash cached input at $0.006 against $0.30 for normal input. Anthropic describes the same idea for Claude in its prompt caching documentation.
What published cached or batch rates take off the price
- Batch mode (OpenAI, Fireworks)50% offboth pages say 50% off input and output
- Fireworks cached input, default50% or more off"half price or less", no write fee
- OpenAI cached read, newer models90% off0.1 times the input rate; 95% off on some models
- GLM 5.3 cached input81% off$0.26 against $1.40 per million
- DeepSeek V4.1 Flash cached input98% off$0.006 against $0.30 per million
To get hits, three rules from our prompt caching guide matter. Put what stays the same first (instructions, documents, tool definitions, examples) and what changes last (the user’s question). Keep that prefix byte for byte identical, with no timestamps or request ids at the top. And send related requests close together, because caches expire after a few idle minutes. On this gateway the reply’s usage.prompt_tokens_details.cached_tokens shows what was reused, and the guide includes a script that runs the same long prefix three times and prints the hit ratio.
A side benefit is fewer rate-limit errors. Anthropic’s rate limit page says its default input-token limits count only uncached input, and Groq’s limits page says cached tokens do not count towards its rate limits. If you are hitting 429s on a long-prompt workload, caching helps twice. Our 429 guide covers the rest.
Tactic 6: when does batch pricing make sense?
Batch pricing makes sense for work nobody is waiting for: evaluations, classification of a backlog, summaries of an archive. OpenAI’s Batch API guide says batches get a 50% discount against synchronous calls, higher rate limits and a 24-hour completion window. Fireworks lists a Batch mode at 50% off input and output on its pricing page, and a Spot mode at 50% off Standard on best-effort capacity where, in its words, throughput can drop to zero, so you retry or fall back.
Here is where we are weaker. The gateway does not offer a batch endpoint, and OpenAI’s flow starts with uploading a file, which the gateway’s Files endpoint does not support (it answers 501). If a big, slow job is your largest cost, run that job directly with the provider’s batch mode and keep the gateway for interactive traffic. That split is common, and a nightly job at half price is worth the second account. For the interactive side, the savings come from the other tactics.
You can still get part of the benefit without a batch API: run non-urgent work through a cheaper model, at a fixed concurrency of about eight as our rate limits guide suggests, and schedule it for when your interactive traffic is quiet.
Tactic 7: should you turn reasoning down?
Often yes. On reasoning models, thinking tokens are billed as output, so a long chain of thought can cost more than the visible answer. Our cost formula counts reasoning tokens as output, and the reasoning guide explains how to lower the effort. For routine work, reasoning_effort: "low" often answers as well with far fewer output tokens, as the cost-control page says.
The test is the same as for model size: run your 30 to 50 prompts at low effort and at the default, and compare. Keep high effort for the requests where low fails, which is where a router (next tactic) helps. Reasoning models are also the usual cause of long silent gaps before the first token, so stream them, as our streaming guide explains, and set a client timeout of a few minutes.
Tactic 8: how do you route by difficulty?
You send the easy share of traffic to a cheap model and keep the expensive one for the requests that need it. The calculator below uses two inputs for this: the share of requests a cheaper model can take, and that model’s price as a percentage of your main one. With 40% of traffic moved to a model at 10% of the price, routing alone cuts the bill by 36%.
Two routing tools exist on this gateway, and it helps to know what each is for. Fallback is for failure: when the provider fails before answering, the gateway retries the named model up to twice, and if it is still failing, fallback rules, presets and automatic routing move the request to another similar model (the free lane also retries a failing :free call on another model by itself). You can name up to three fallback ids yourself in X-Fallback-Models, an X-Fallback-From header on the reply says which model failed, and only the attempt that answers is billed. Virtual models and rules are closer to cost routing: in the console you can define a name for a chain of up to three models and add rules that pick a chain from request metadata, and the ids auto, auto:cheap and auto:best choose a chain from the catalogue. The routing documentation has the details. We would start simpler: a rule in your own code that sends short, well-formed requests to the small model and anything else to the large one, then measure the failure rate on your test set.
Be careful with the fallback header as a cost tool. It protects uptime, and a fallback that is more expensive than the primary raises the bill exactly when the primary is down. Choose fallbacks of similar or lower price, and read the uptime and fallbacks guide before wiring a chain. Because a different model can answer, run the six checks for verifying the model on any route you depend on, and note that cheap LLM API reseller risks shows why a low price alone proves nothing about what is served.
What do the savings add up to?
In the worked example, three tactics stack: caching, an output cap and routing. The calculator reproduces the sums with fields you can change. Defaults are the example above, with 70% of the input being a stable prefix and 80% of that prefix served from cache.
Savings stack calculator
- Baseline per month
- $3,800.00
- After caching
- $2,590.40
- After caching and an output cap
- $2,240.40
- After routing the easy share too
- $1,433.86
- Saved per month
- $2,366.14
It ignores cache write fees (Claude and OpenAI's newer models charge 1.25 times the input rate to write a cache entry; Fireworks charges none), retries, and the quality cost of a cheaper model. Nothing is sent anywhere.
With the defaults the bill falls from $3,800 to $1,434, a saving of about $2,366 or 62%. The chart splits that saving by tactic.
Where the monthly saving comes from (worked example)
- Prompt caching$1,210
- Routing the easy 40%$807
- Output cap and brevity$350
Treat the result as a ceiling for a single app, not a promise. A 40% easy share assumes your cheaper model passes those requests, and an 80% cache hit rate assumes steady traffic. The point of the exercise is the order of magnitude, and the fact that the three tactics multiply instead of adding.
Tactic 9: why put a ceiling on every key?
Because the most expensive mistake is not a bad price, it is a loop. An agent that retries a failing tool call, a cron job that runs twice, a leaked key: each can burn a month’s budget in an hour. A ceiling does not lower your average cost, it lowers your worst case, and the worst case is what hurts.
The gateway gives you layers, all in the cost-control guide. A spend limit per key stops that key when it is used up and leaves your balance and other keys alone. An expiry date handles temporary access. A model list stops a typo from switching an app to an expensive model. A spend limit per end user caps each of your own customers if one key serves them all. Above the keys, an account spend cap per day, week or month refuses paid models with a 429 once reached (free models still answer), and the request that crosses the cap still finishes, so the total can end slightly above it. Pair that with a low-balance alert so the first warning is an email, not a refused request.
Prepaid credit is a ceiling in itself, since you can never be charged more than you have added, but a 403 in the middle of a production day is a poor way to find the edge. The post on prepaid LLM API credits covers how reservations and balances behave.
Tactic 10: how do you avoid paying fees and duplicate attempts?
You read the fee line before you pick a gateway, and you stop your own code from paying twice. Both are quiet leaks.
On fees: OpenRouter’s FAQ says it passes through provider prices with no markup on inference but charges a 5.5% fee ($0.80 minimum) when you buy credits, and 5% for crypto. On a $10 purchase the $0.80 minimum is 8%. Here, credit is added by email from $1, there is no processing fee, and the amount you add is the amount you receive, which the pricing page shows. Fee structures change, and the fee comparison and the OpenRouter comparison are dated and sourced. If you are moving from another gateway, the migration guide covers the swap, seven gateways compared lines up the alternatives, and self-hosting LiteLLM against a hosted gateway shows the cost of running your own proxy.
On duplicate attempts, two patterns cost real money. The first is the timed-out request: the model may have finished and been billed even though your client never saw the answer, so retrying blindly pays twice. Our errors page says exactly this, and an abandoned request is billed for the tokens produced before it stopped. The second is stacked retry loops: the official SDKs already retry 429s and 5xx errors twice, so wrapping a five-attempt loop around them can turn one failure into fifteen requests. Raise max_retries instead of adding a second loop.
Which tactics should you do first?
Do them in this order: measure, cap, trim, cache, route, batch, ceiling. The diagram puts cheap and reversible steps first and the ones that need engineering later.
An order of attack
Which tactics have you applied?
0 of 10 applied
Start with measurement
Make a key per app and read a week of usage. Everything else depends on knowing where the tokens go.
Where does the gateway help, and where does it not?
If you are new to the idea, the explainer on what an LLM gateway is shows where these controls sit. Ours helps with the first mile of every tactic: one key per app, spend limits, a usage record per request, cached tokens shown in the reply, retries, fallback and routing rules, and free ids for development. It does not give you a batch endpoint, it does not cache Claude traffic sent through chat completions, and it does not control the model providers behind it. Prices on the models page are what you pay, and some listings are marked unavailable when no working route exists, which is a reminder to check the list before you commit a model id to production.
We would rather you checked than trusted. The transparency page lists what we monitor and what we cannot see, the honest review of One AI API Key says what you get and what you do not, and the 12-point provider checklist is a neutral way to compare us with anyone else. Once a key is created and usage is consumed we do not give money back, so read the money-back terms of any provider before you add credit; if a key does not work, write to somdutt777@gmail.com. On privacy, what you send is not stored by default and we keep counts, never content, as the guide to what a gateway sees and stores explains. Whatever you choose, run the worked example with your own numbers first.
A small code sample
The sample below puts tactics 3, 4 and 5 into one call and prints what the provider reported. It starts on a free id, so running it costs nothing, and reads the key from the ONEAIAPIKEY_API_KEY environment variable. Swap the MODEL variable and the RATES line for a priced model when you are ready. The quickstart shows the first call, and the guide to switching an OpenAI SDK app to a different base URL covers the same change in Node.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.oneaiapikey.com/v1", api_key=os.environ["ONEAIAPIKEY_API_KEY"])
MODEL = os.environ.get("MODEL", "z-ai-glm-5.3:free") # develop on a free id, set a priced id in production
POLICY = open("policy.md").read() # long and stable: keep it FIRST so the provider can cache it
def trim(history, keep=6):
"""Send only the last `keep` messages. Summarise older turns first if they still matter."""
return history[-keep:]
def ask(question, history):
reply = client.chat.completions.create(
model=MODEL,
max_tokens=300, # cap the output at the longest answer you would accept
messages=[
{"role": "system", "content": POLICY + "\nAnswer in at most three sentences."},
*trim(history),
{"role": "user", "content": question}, # the part that changes goes LAST
],
)
u = reply.usage
cached = (u.prompt_tokens_details.cached_tokens if u.prompt_tokens_details else 0) or 0
print(f"input={u.prompt_tokens} cached={cached} output={u.completion_tokens}")
return reply.choices[0].message.content
# What one call cost, from the rates you pay (USD per 1M tokens). prompt_tokens already includes the cached part.
RATES = {"input": 2.00, "cached": 0.20, "output": 10.00}
def cost(u, cached):
return ((u.prompt_tokens - cached) * RATES["input"] + cached * RATES["cached"] + u.completion_tokens * RATES["output"]) / 1e6Run it twice in a row with the same policy.md. On a model that caches automatically, the second call should show a non-zero cached count, once the prefix passes about 1,024 tokens. If it stays at zero, something at the top of your prompt is changing between calls. A timestamp is the usual culprit.
What would we do first on a new bill?
If a bill landed on our desk tomorrow, we would spend the first hour on three things. Split spend by key to find the app that matters. Pull ten of its most expensive requests and read them, because the pattern (a pasted file, a looping tool call, a history that never shrinks) is usually obvious. Then fix the pattern with the cheapest tactic that addresses it: a cap, a trim, a prefix reorder or a ceiling. Model swaps and routing come after, because they need evidence, and the evidence takes longer to collect.
If you are not on the gateway yet, the quickest way to test any of this is the free lane: 47 models, 100 requests and 3,000,000 tokens a day shared across them, plus $10 of sign-up credit for priced models, with no card. When you outgrow it, the pricing page shows how credit is added, and the billing page shows your balance and history.
Try the tactics on a free key first
$10 sign-up credit, 47 free models sharing 100 requests and 3,000,000 tokens a day, no card.
Frequently asked questions
What is the fastest way to reduce LLM API costs?
max_tokens and ask for shorter output. The usage page shows tokens per request, so you can see which one applies before changing anything.How much does prompt caching save?
Does prompt caching work through this gateway?
cached_tokens in the reply tells you what was reused. On Claude models, cache_control markers are only carried on the Anthropic /v1/messages endpoint: through /v1/chat/completions the gateway does not pass them on and the whole prompt bills at the input rate. The Anthropic Messages guide shows the right endpoint.