Sending each request to the smallest model that can handle it

Most AI products send every request to one model. That is simple, but it means paying flagship prices for greetings and yes-or-no questions, or accepting weak answers on the hard cases to save money. Tools that route automatically show the promise and the pitfalls: users of auto modes in coding agents report long thinking and stalled tasks until they pick a model by hand, while enterprises processing large volumes of documents look for ways to stop paying top rates for routine work.
This guide is for developers who want a router they understand. You will build one in steps: classify requests with cheap rules, send easy ones to an inexpensive or free model, validate the output, escalate when needed, and measure the result. The examples use OpenAI-compatible clients, so they work with Gemini's compatible endpoint, the keyless model on this site, or any other provider.
Frequently asked questions
What is model routing?
Choosing, per request, which model should answer it. A router looks at the request, and sometimes at a first attempt, then decides whether a small, cheap model is enough or a larger one is needed.
How does routing differ from fallback?
Fallback switches models when one fails or is unavailable. Routing chooses a model on purpose before or after a first attempt, based on difficulty. Many systems use both: routing for cost and quality, fallback for availability.
Which signals predict that a request is hard?
Length, presence of code or maths, number of explicit constraints, requests for multi-step plans and the feature the request comes from. Simple signals like these get you most of the benefit without another model call.
Should a model decide the route?
Sometimes. A small model can classify difficulty cheaply, but that adds latency to every request and can misjudge. Start with rules, and add a classifier only for traffic where rules are clearly not enough.
Why do automatic modes in tools sometimes stall?
They must guess difficulty and choose a model and thinking budget without knowing your intent. When the guess is wrong, a strong model may deliberate too long on a vague task, or a weak one may fail quietly. Explicit routing in your own code avoids that opacity.
Which is better, routing before or escalating after?
Routing before is cheaper when signals are reliable. Escalating after a failed validation catches cases the rules miss. Combining both, rules first and escalation on failure, is the most robust pattern.
Can the free endpoint be the cheap tier?
For low-stakes, short tasks it can: free-ai costs nothing but has per-IP limits, no SLA and a 32,000-token context. For production traffic at scale, a paid fast model is usually the better cheap tier.
How do I know routing saves money?
Log model, tokens, cost estimate and whether the answer was accepted for every request. Compare cost per accepted answer before and after routing on the same kind of traffic.
Step by step
- Log current traffic — Record features, input lengths, tokens and acceptance for a week so you know what easy and hard requests look like.
- Define two tiers — Choose a cheap model and a strong model and store their base URLs, keys and names in configuration.
- Write routing rules — Route by feature first, then by simple signals such as input length, code blocks and planning keywords.
- Validate and escalate — Check each cheap answer in code and retry once on the strong tier when the check fails.
- Add limits and fallback — Give each tier its own concurrency limit and switch tiers on 429 or 503 responses.
- Review weekly — Compare cost per accepted answer and escalation rate per feature, then adjust rules.
Why route at all
Request difficulty in real products is lopsided. A large share of chat messages, support tickets or document snippets are routine, and a small model answers them as well as a large one. A smaller share needs careful reasoning, long context or specialised skills. Paying the same price for both groups wastes money on the first and, if you pick a cheap model, quality on the second.
Routing aligns cost with difficulty. Done well, users notice no difference except that the product is faster on simple requests.
Latency improves too
Small models usually answer faster. Routing easy requests to them makes the common case quicker, which users feel more than anything else.
Quality can improve
When the strong model is not swamped with easy traffic, you can afford to give it more thinking budget or context on the hard requests.
Start with explicit rules
The cheapest router is a few lines of code. Look at the request before sending it and decide. Code blocks, long inputs, words like prove, plan or debug, or a request coming from a feature known to be demanding all point to the strong model. Short questions from a feature like quick replies point to the cheap one.
Rules are transparent and free to evaluate. When a routing decision looks wrong in your logs, you can see exactly which rule fired and fix it.
Route by feature first
Often the simplest rule is per feature: autocomplete and tagging always use the cheap model, the planning assistant always uses the strong one. Per-request rules then only refine features with mixed traffic.
Avoid clever rules early
Resist building dozens of rules on day one. Two or three obvious ones, measured for a week, teach you more than an elaborate decision tree built on guesses. Add rules only when the logs show a clear group of misrouted requests.
- Input longer than a set number of characters goes to the strong model
- Code fences or stack traces go to the strong model
- Requests from known simple features go to the cheap model
- Explicit user choice of a premium mode overrides everything

Escalate when validation fails
Rules miss some hard requests. Catch them after the fact by validating the cheap model's answer. If you asked for JSON, does it parse and match the schema? If you asked for code, does it compile or pass a quick test? If you asked for a label, is it on the allowed list? A failed check triggers a retry on the strong model.
Validation-based escalation is powerful because it uses the cheap model's own failure as the difficulty signal. It costs one extra call only on the requests that need it.
Self-reported confidence is weak
Asking a model how confident it is gives answers that correlate only loosely with correctness. Prefer checks you can run in code.
Cap the escalation chain
Allow at most one escalation per request. If the strong model also fails validation, return a graceful error or route to a person instead of looping.
A small router in code
The router below combines both ideas. It applies rules to pick a first model, validates the answer as JSON, and escalates once on failure. The cheap tier here is the keyless endpoint on this site; the strong tier reads its base URL, key and model from environment variables, so it can point at Gemini's OpenAI-compatible endpoint or any other provider you use.
Keep tiers in configuration
Names, base URLs and keys belong in environment variables or a config file. Swapping the strong model after a release or a retirement then needs no code change.
import json, os, re
from openai import OpenAI
cheap = OpenAI(base_url="https://api.apifreegemini.com/v1", api_key="unused")
strong = OpenAI(base_url=os.environ["STRONG_BASE_URL"], api_key=os.environ["STRONG_API_KEY"])
TIERS = {"cheap": (cheap, "free-ai"), "strong": (strong, os.environ["STRONG_MODEL"])}
def looks_hard(text):
return len(text) > 3000 or "```" in text or re.search(r"\b(prove|debug|plan|refactor)\b", text, re.I)
def ask(tier, system, text):
client, model = TIERS[tier]
r = client.chat.completions.create(model=model, temperature=0.2, max_tokens=600,
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}])
return r.choices[0].message.content
def route(system, text):
first = "strong" if looks_hard(text) else "cheap"
for tier in ([first] if first == "strong" else ["cheap", "strong"]):
out = ask(tier, system, text)
try:
return tier, json.loads(out.strip().strip("`").removeprefix("json"))
except json.JSONDecodeError:
continue
return "none", None
print(route('Return JSON {"topic": str, "sentiment": "pos|neg|neutral"}.',
"The new invoice layout is much clearer, thanks!"))
Adding a classifier when rules are not enough
For traffic where simple rules perform poorly, such as open-ended chat, a small classifier can help. Ask the cheap model to label the request as simple or complex with a one-word answer and a strict format, then route on that label. Keep the classification prompt short to limit overhead.
Measure whether it pays off. A classifier adds a call to every request, so it must save more through better routing than it costs in latency and tokens.
Sample and review
Each week, review a sample of routed requests by hand: easy ones sent to the strong model and hard ones answered by the cheap model. Adjust rules or the classifier prompt based on what you see.
Keep the classifier cheap
Limit the classifier's output to a single word with a small max_tokens value and a temperature of zero. Long explanations from the classifier add cost and latency without improving the routing decision.
Measuring cost and quality
A router without measurement is a guess. For every request, log the tier chosen, whether it escalated, tokens in and out, latency and whether the user accepted the answer, for example by not regenerating or editing it. From those logs, compute cost per accepted answer and escalation rate per feature.
Enterprises evaluating Gemini or any model for large data volumes will recognise this as ordinary cost accounting. The difference is that routing gives you a lever to move those numbers without changing the product.
Watch the escalation rate
A rising escalation rate for one feature means the cheap tier is struggling there, perhaps after a model update. Moving that feature to the strong tier by default may be cheaper than double calls.
- Tier chosen and reason
- Escalated or not
- Prompt and completion tokens
- Latency to first token and total
- User accepted, edited or regenerated

Routing, limits and availability
Routing and fallback work well together. If the cheap tier returns 429 because of rate limits or 503 because it is busy, the router can send that request to the strong tier instead of failing. The reverse also holds: when the strong provider has an incident, routing more traffic to the cheap tier keeps simple features alive.
Respect each tier's limits. The endpoint on this site allows one request per second per IP with bursts of three, two in parallel, and 10,000 requests or 10,000,000 tokens per day. A router that floods it will just collect 429 responses with Retry-After headers.
Per-tier concurrency
Give each tier its own concurrency limit in your client. A shared pool lets one slow tier block requests that the other could have answered.
An honest view of the cheap tier
APIFreeGemini is not affiliated with Google. Its free-ai model is an independent open-weight model of about 35B parameters, offered free with no key and no SLA. It is a reasonable cheap tier for prototypes, internal tools and low-stakes features such as tagging, short summaries and drafts. It is text only and has a 32,000-token context, so images and very long documents must go elsewhere.
For production traffic where availability and consistent quality matter, a paid fast model is usually the better cheap tier, with the free endpoint as an extra fallback. The article on choosing between model tiers helps pick the paid options, and handling retired models explains how to keep router configuration current.
Tell users which tier answered
In internal tools, showing a small marker for the tier that answered helps people calibrate trust and report misroutes. In public products it is optional, but it does make feedback about quality much easier to interpret.

Send a test prompt to the keyless free-ai endpoint from the home page, no sign-up or key required.
Read also
- How to add a free AI step to n8n or Apple Shortcuts without a key
- Open-weight models vs Gemini: when is a mid-size model good enough?
- How to move your chat context between ChatGPT, Gemini and an API
- When is it worth switching on thinking or reasoning mode in an API?
- How to keep a Gemini API key out of your app and off the bill