cocodot
← Back to guides
Local card declined for overseas AI? cocodot: one card + one key
Saving MoneyUpdated 2026-08

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.

TL;DR: The fastest way to reduce LLM API costs is to stop sending every request to your most capable model. Most team bills are driven by a handful of habits: routine work such as classification, extraction and short rewrites running on a flagship; answers far longer than anyone reads; context that grows with every turn; and retries nobody counts. Fix them in order of evidence, not intuition. First, log tokens per request by feature so you know where the money goes. Second, route by difficulty: a small, fast model for bulk chores, a mid-tier model as the default for daily work, and the top tier only when the mid tier has failed on a specific case. Third, cap output with max_tokens and ask for shorter, structured answers. Fourth, keep repeated prompt prefixes identical so caching can apply. Fifth, count retries and failed attempts as part of cost. Every lever can be tested on your own data in a day, and none needs a new framework. Routing is only safe when you score quality on the same examples before and after, so keep a small evaluation set and a one-line rollback. cocodot's gateway puts Claude, GPT, Gemini, Qwen, GLM and Kimi models behind one OpenAI-compatible key, so switching tiers is a change to the model string.

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 seeLikely causeLever to try first
Short, repetitive tasks billed at flagship ratesOne default model for every featureRoute bulk chores to a small model; re-score accuracy on your evaluation set
Output tokens much larger than needed on simple tasksNo max_tokens, open-ended instructionsCap output, ask for a fixed format, drop explanations nobody reads
Input tokens climb with every turn of a conversationThe whole history is resent on each callSummarise or drop old turns; retrieve only the relevant chunks
The same long system prompt on every call, no cache readsThe prefix changes slightly between callsFreeze the prefix byte for byte and put variable content last
Spend rises but delivered results do notRetries, timeouts and agent loops are not countedTrack attempts per task; cap retries and agent steps
A reasoning model bills heavily for short answersHidden reasoning tokens add to usageUse reasoning only where it changes the result; set a token budget

FAQ

How can I reduce my LLM API costs without losing quality?

Measure first, then change one feature at a time. Log tokens per request by feature, move bulk tasks to a smaller model, cap output with max_tokens and keep repeated prompt prefixes identical so caching applies. Before each change, score the old and new setup on the same set of real inputs and only keep changes that hold the accepted rate you decided in advance.

What is model routing, and do I need a router library?

Model routing is choosing a model per task rather than one model for the whole application. You can start with a simple table that maps each feature to a model string, defaulting to a mid-tier model and escalating to the top tier only when a case has failed. Automatic routers that classify each prompt are an optimisation for later, once you have evaluation data showing where the boundaries are.

Should I optimise input tokens or output tokens first?

Whichever side costs more in your own log. Multiply each side's token count by its current rate for the model you use and compare. Chat history, retrieval and long documents make input dominant; long answers and code generation make output dominant. Optimising the smaller side first is the usual way teams spend a week and see no change on the bill.

Does prompt caching always save money?

No. It saves money only when a long prefix is identical across calls and is read back several times within the cache lifetime. On Claude models cache writes cost more than plain input, so a prefix written once and never reused costs more than not caching. Check the cache-read fields in each response's usage object to confirm hits are happening.

How much can model routing save?

It depends entirely on your task mix, so be wary of any fixed percentage. Estimate it from your own log: take the share of calls a smaller model passed on your evaluation set, multiply by the rate difference between the two models, and subtract the cost of extra attempts on the inputs it failed. That gives a number you can defend.

Is it cheaper to call the official API directly?

Sometimes, and you should check rather than assume. For heavily cached, long-running agent workloads, going direct is usually the cheaper option. A gateway such as cocodot is most useful when output-heavy or uncached work dominates, when you want several model families behind one key, or when your local card cannot pay an official console.

About cocodot

cocodot is a payment and AI access service for developers and cross-border teams in mainland China. It provides US-BIN virtual cards issued by a licensed institution — used to pay for overseas subscriptions and ad accounts — and an OpenAI-compatible AI API gateway for calling Claude, GPT and Gemini from within mainland China. Both share one wallet, funded by Alipay / WeChat Pay, USDT / USDC and accounted in USD. Fees are listed on the pricing page.

Service scope, pricing and limits →
OpenAI-compatible API, pay in RMBGet API access