How to Reduce LLM API Costs: Model Routing, Output Caps and the Levers That Actually Move the Bill (2026)
Route by task difficulty, cap output, trim context and count retries. A measurable LLM cost optimization plan you can test on your own logs.
1. Find where the money goes before you optimise anything
Cost work fails when it starts from a hunch. Before changing a single model, add three fields to every request your application sends: the feature that made the call, the model, and the input and output token counts returned in the response's usage object. A week of that data answers the questions that matter. Which feature produces most of the spend? Is that spend input-heavy (long prompts, long documents, long chat history) or output-heavy (long answers, long code)? How many calls does one user action trigger? Teams that do this usually find the bill is concentrated in two or three features, and that the expensive part is not where they assumed. Rule of thumb: optimise the feature with the largest tokens × rate product first, and ignore everything under a few percent of the total. Keep the raw log, not just a dashboard total, because you will need it later to prove that a change saved money without breaking anything.
2. Route by difficulty: three tiers and one default
Model routing means choosing the model per task instead of per application. You do not need a router library to start; a lookup table from feature name to model string is enough. Sort your tasks into three tiers. Tier 1, bulk chores: classification, tagging, field extraction from structured text, language detection, short summaries. Small, fast models (Haiku-class, Flash-class, Luna-class) are designed for this. Tier 2, daily work: drafting, coding, refactoring, standard reasoning, customer replies. A mid-tier model (Sonnet-class or a comparable GPT or open-weight model) should be your default. Tier 3, hard cases: cross-file changes, long multi-step agent runs, problems the mid tier has already failed. Reserve the top tier (Opus-class or the provider's most capable model) for these. The discipline that makes routing pay is simple: default to tier 2 and escalate only with a reason you can write down — "tier 2 failed on this input" counts, "this feels important" does not. Also route down deliberately: when a tier 1 model can do a task at the same accepted quality, the higher tier is pure overhead.
3. Prove a downgrade is safe with a small evaluation set
The risk of routing is silent quality loss: the cheaper model is wrong more often, and nobody notices until a customer does. Prevent that with a fixed evaluation set before each change. Pull 50 to 200 real inputs from your logs for the feature you want to move, including awkward ones. Write down what a correct output looks like: the fields that must be present, the facts that must be right, the format that must parse. Run the current model and the candidate on the same set and score both with the same rules, ideally automatically (a JSON schema check, an exact-match field, a unit test for code). Move the feature only if the candidate's accepted rate is within a margin you chose in advance, and keep the old model string behind a flag so rollback is one change. Then compare cost per accepted output, not cost per call: a cheaper model that needs a second attempt on a third of inputs may not be cheaper at all. The method in /hub/team-ai-api-cost-per-task shows how to turn those numbers into a budget.
No overseas card needed: cocodot's OpenAI-compatible API — switch your base_url to call the models on sale.
Top up via Alipay / WeChat Pay, USDT / USDC · billed per token · switch your base_url to connect
4. Output is the lever people forget
Many cost guides focus on shortening prompts, but for chat, drafting and code generation the output side is often where the money is. Check your log: if output tokens per call are large relative to what the user actually uses, you are paying for text nobody reads. Three changes help immediately. Set max_tokens on every call, sized to the longest legitimate answer for that feature, not left at the maximum. Ask for the shape you need: "return JSON with these four keys" or "answer in at most three sentences" produces shorter, more predictable output than "explain". Remove decorative requests such as restating the question, adding a summary of the summary, or listing caveats on every answer. For code, ask for a diff or only the changed function instead of the whole file. One caution: a cap that is too tight truncates real answers, which triggers a retry and costs more than it saved. Look at the finish reason in each response; if a noticeable share ends because of the length limit, raise the cap for that feature rather than lowering quality elsewhere.
5. Context discipline: stop resending the whole conversation
Chat applications are stateless at the API level: every turn sends the entire history again, so the input cost of a long conversation grows with every message. The same thing happens in agents that append each tool result to the prompt. Keep context in proportion to the task. Window the history: keep the last few turns verbatim and replace older ones with a short running summary written by a tier 1 model. Retrieve instead of pasting: for documents and knowledge bases, send the few passages that match the question rather than the whole file. Trim tool output: an agent rarely needs a full web page or a 2,000-line log; extract the relevant lines before they enter the prompt. Drop images and attachments after the turn that needed them. These changes also reduce the chance of hitting context limits, which fail the request outright (see /hub/context-length-exceeded-fix). A useful check: for your most expensive feature, compare average input tokens on the first turn with the tenth. If the tenth is many times larger and answers are no better, history is costing you money.
6. Prompt caching: what it rewards and what breaks it
Prompt caching lets a provider reuse the processed form of a prompt prefix it has seen recently, and bill those tokens at a reduced cached-input rate. It rewards one thing: a long prefix that is identical, byte for byte, across calls. Put stable content first (system instructions, tool definitions, a reference document) and variable content last (the user's message, retrieved passages, the current date). The usual reasons caching does nothing: a timestamp or request ID inside the system prompt, tool definitions serialised in a different order, a user name injected near the top, or calls spaced further apart than the cache lifetime. Minimum cacheable lengths, lifetimes and whether caching is automatic or explicit differ by provider, so read the current caching docs for the model you use and check the usage object for cache-read tokens rather than assuming. On cocodot: cache hits at half the input price; Claude cache writes at 1.25x the input price (2x for the portion written to the 1-hour cache), the same structure as the official pricing. Because writes on Claude cost more than plain input, caching only pays when a prefix is actually read back several times.
7. Retries, loops and reasoning budgets: costs that hide inside usage
Some spend never shows up as a feature in a product review. Retries: a client that retries every timeout three times can quietly triple the cost of a slow request, and a request that was sent may still be billed even if your client gave up waiting. Use exponential backoff, cap attempts, and log every attempt under the same task ID so cost per task includes them (/hub/api-429-rate-limit-concurrency-china covers backoff for rate limits). Agent loops: an agent that cannot finish keeps calling the model. Set a maximum number of steps and a token budget per run, and stop with a clear error when either is reached; /hub/api-relay-runaway-risk explains why a hard ceiling matters on prepaid balances. Reasoning models: models that think before answering generate hidden reasoning tokens that add to usage even when the visible answer is short. Read the provider's usage fields to see how they are reported and billed, and use reasoning settings only on features where a scored comparison shows they change the result. Duplicate calls: the same question asked by many users can often be answered from your own application cache before it reaches the model at all.
8. A monthly review, and where a gateway fits
Cost control is a habit, not a project. Once a month, spend fifteen minutes on the request log grouped by feature and model, and ask four questions: which tier 3 calls could have stayed on tier 2; did tier 1 chores drift up to tier 2 when someone changed a default; which feature's tokens per call grew; and which key's usage jumped without a matching product change. Keep separate API keys per environment or service so an unexplained jump points somewhere specific. Routing is easiest when trying another model costs one line. cocodot's gateway serves Claude, GPT, Gemini, Qwen, GLM and Kimi models behind one OpenAI-compatible base URL and key, so a tier change or an A/B test is a change to the model string, and usage is billed per token from a prepaid balance. Omitting model uses Claude Sonnet 5 by default. Trial credit is limited to budget models; top up to use all models, including the default Claude Sonnet 5. Listed Claude / GPT / Gemini rates are at or below the official list price; check the pricing page for each model's current rate. Be honest about the trade-off: for workloads dominated by heavily cached, long-running agent sessions, calling the official API directly is usually the cheaper route. A gateway helps most on output-heavy work, uncached input, and when paying an official console with a locally issued card is the obstacle.
What you see in the usage log → likely cause → lever to try first
| What you see | Likely cause | Lever to try first |
|---|---|---|
| Short, repetitive tasks billed at flagship rates | One default model for every feature | Route bulk chores to a small model; re-score accuracy on your evaluation set |
| Output tokens much larger than needed on simple tasks | No max_tokens, open-ended instructions | Cap output, ask for a fixed format, drop explanations nobody reads |
| Input tokens climb with every turn of a conversation | The whole history is resent on each call | Summarise or drop old turns; retrieve only the relevant chunks |
| The same long system prompt on every call, no cache reads | The prefix changes slightly between calls | Freeze the prefix byte for byte and put variable content last |
| Spend rises but delivered results do not | Retries, timeouts and agent loops are not counted | Track attempts per task; cap retries and agent steps |
| A reasoning model bills heavily for short answers | Hidden reasoning tokens add to usage | Use reasoning only where it changes the result; set a token budget |