Picking the right model per request with a lightweight router

Look at the traffic of almost any AI application and you will find that a large share of calls are small chores: generating a title for a conversation, summarizing a tool result, classifying whether a message needs a reply, rewriting a sentence. These calls often go to the same expensive model that handles the hard reasoning, simply because it was the default. Developers who add a router, a small piece of code that picks a model per request, regularly report that a big portion of their calls can move to a cheaper or local model with no visible change for users.
This guide is for anyone running an app or agent that makes many model calls. You will learn how routing works, which tasks are safe to route, how to write a simple rule-based router in Python, and where routing backfires. Examples use OpenAI-compatible clients, so the same code can point at Groq's API, a local server or the keyless free-ai endpoint on this site.
Frequently asked questions
What is an LLM router?
It is code that inspects a request before sending it and chooses which model or provider should handle it. The choice can depend on task type, prompt length, required quality, cost or availability. The caller sees one interface while the router decides behind it.
Which tasks are usually safe to route to a small model?
Short, well-specified jobs with easy-to-check output: titles, tags, classification, short summaries of supplied text, format conversion and simple rewrites. They depend mostly on the input, not on deep knowledge or long reasoning.
How does rule-based routing differ from learned routing?
Rule-based routing uses explicit conditions such as task name or prompt length. Learned routing trains a classifier or uses a small model to predict which requests need the strong model. Rules are transparent and easy to debug; learned routers can adapt but need evaluation data.
Does routing reduce quality?
If done carelessly, yes. A request routed to a model that cannot handle it produces a worse answer, sometimes silently. Good routers keep hard and ambiguous requests on the strong model and are tested on real traffic before being trusted.
Can I route between a local model and a cloud API?
Yes, and it is a popular setup. A small local model handles private or trivial tasks, while a cloud model handles complex ones. Both can expose the OpenAI format, so the router only switches base URL and model name.
Is routing the same as a fallback chain?
No. Routing chooses a model before the call based on the request. A fallback chain reacts after a failure, such as a rate limit, by trying another provider. Many systems use both: route first, then fall back if the chosen model is unavailable.
How much can routing save?
It depends entirely on your traffic mix. Apps where most calls are small chores save a lot; apps where every call is a hard reasoning task save little. Log your calls by task type for a week before estimating.
The hidden chores in an AI app
Coding assistants are a good illustration. Besides the main agent loop, they make side calls to name the session, summarize tool outputs, decide whether a command needs permission and compress old context. Each side call is small, but there are many of them. One developer who built a hybrid router for such a tool found that these background calls could be served by a local model while the main agentic work stayed on the cloud model, cutting cloud calls substantially.
Chat apps, support bots and content tools have similar patterns. A support bot may first classify the intent, then extract an order number, then write a reply. Only the last step needs strong language skills. A personal assistant on a small home server might send greetings and reminders to a local model and anything involving research or long text to a fast cloud API.
Log before you route
Add a task label to every model call and log token counts. After a few days you can see which tasks dominate volume and which dominate cost. Those numbers decide whether routing is worth the complexity.
What makes a task safe to route
The best candidates share three traits. The output is short. The answer depends mostly on information in the prompt rather than world knowledge. And mistakes are cheap or easy to detect. A slightly dull conversation title costs nothing; a wrong legal summary costs a lot.
Tasks to keep on the strong model
Multi-step reasoning, code generation beyond snippets, anything requiring up-to-date or specialised knowledge, long-form writing and decisions with real consequences. When in doubt, keep a task on the stronger model until you have evidence the smaller one copes.
Validation makes routing safer
If the output can be checked automatically, for example JSON that must match a schema or a label from a fixed list, you can route aggressively and retry on the strong model when validation fails.
- Session titles and tags
- Yes/no or category classification with a fixed label set
- Summaries of text you supply, under a few hundred words
- Reformatting: Markdown to plain text, list to table, dates to ISO
- Short rewrites for tone or length
- Extraction of fields that clearly appear in the input

A rule-based router in Python
The simplest router is a dictionary from task name to model configuration plus a length check. It is transparent, easy to test and often good enough. The example sends small tasks to the keyless free-ai endpoint and everything else to a stronger provider of your choice. For Groq, the base URL in its documentation is OpenAI-compatible; put your own key in an environment variable, never in code.
Why character length is a rough proxy
Character counts are a cheap stand-in for tokens. They are fine for a threshold like this, but if you route on context limits, count tokens properly, because languages and code tokenize very differently.
import os
from openai import OpenAI
small = OpenAI(base_url="https://api.apifreegroqkey.com/v1", api_key="free")
strong = OpenAI(
base_url=os.environ.get("STRONG_BASE_URL", "https://api.groq.com/openai/v1"),
api_key=os.environ["STRONG_API_KEY"],
)
STRONG_MODEL = os.environ.get("STRONG_MODEL", "your-chosen-model")
SMALL_TASKS = {"title", "classify", "summarize_short", "reformat"}
def route(task, messages):
size = sum(len(m["content"]) for m in messages)
if task in SMALL_TASKS and size < 6000:
return small, "free-ai"
return strong, STRONG_MODEL
def ask(task, messages, **kw):
client, model = route(task, messages)
r = client.chat.completions.create(model=model, messages=messages, **kw)
return r.choices[0].message.content
print(ask("title", [{"role": "user", "content": "Give a 4-word title for: fixing a flaky CI test"}]))Learned and model-based routers
Once rules stop scaling, some teams train a small classifier on logged requests labelled by which model gave an acceptable answer. Others ask a small, fast model to rate the difficulty of each request before routing. Both approaches can work, but both add latency and a new component that can fail.
A model-based router must itself be cheap and quick, or it eats the savings. It also needs evaluation: collect a set of requests, note which ones the small model handled well, and check how often the router agrees. A router that sends ten percent of hard requests to the small model may be worse than no router at all.
Confidence and escalation
Another pattern is to try the small model first and escalate when the answer looks weak, for example when it fails validation or the model says it is unsure. This works for checkable tasks and costs an extra call on escalation.

Local plus cloud: the home-server pattern
Builders running assistants on small home computers often pair a local model for always-available, private chores with a cloud API for heavier lifting. The local model answers instantly without network or quota concerns, while the cloud model handles long documents and tricky questions. Both sides speak the OpenAI format, so the router only swaps base URLs.
The keyless endpoint is a convenient middle tier in such a setup: no key to store on the device, a 32,000-token context and up to 16,000 tokens of output. It runs free-ai, an independent open-weight model of around 35B parameters that is not affiliated with Groq or any model Groq hosts. It has no SLA, so treat it as a best-effort option and keep a fallback. Our article on self-hosting versus hosted APIs discusses the hardware side of this choice.
Privacy routing
Routing can follow data sensitivity as well as difficulty. Messages containing personal details can stay on the local model, while generic questions go to the cloud. This requires reliable detection of sensitive content, which is itself a task to test carefully.
Common ways routing goes wrong
Routers fail quietly. The app still answers, just worse, and nobody notices until users complain. A few patterns cause most of the trouble.
Prompt drift between models
A prompt tuned for one model may behave differently on another. System prompts, formatting instructions and few-shot examples sometimes need small adjustments per model, which means maintaining two prompt versions.
Context splits
If different turns of a conversation go to different models, the style can jump and one model may misread the other's output. Route by task within a conversation, but keep the user-facing replies on one model where possible.
Silent quality regressions
When a provider updates its model, the routed tasks can change behaviour overnight. Keep a small regression test per routed task and run it regularly.

Combining routing with fallbacks and limits
Every provider has limits. The keyless endpoint allows one request per second per IP with bursts of three, two in parallel and a daily cap of 10,000 requests or 10 million tokens, resetting at midnight UTC. Groq's free plan has per-model limits; check its current limits page. A router that sends lots of small calls to one free endpoint can hit these quickly, so add a short queue or rate limiter on your side and respect the Retry-After header on 429 responses.
When the chosen model returns 503, retry after a few seconds or move the request to the other tier. For heavier traffic patterns and pricing trade-offs, our comparison of flat subscriptions and pay-per-token APIs helps decide where to send the bulk of your calls.
Use the free tier as a tier, not a foundation
A free endpoint without an SLA is excellent for low-stakes chores and experiments. For tasks users depend on, make sure the router can always reach a paid or local option when the free one is busy.
A rollout plan that keeps quality visible
Introduce routing gradually. Start with one task, such as titles, and send a small share of its traffic to the small model while logging both versions for comparison. If nobody can tell the difference, move the whole task, then pick the next one. Keep the ability to switch any task back with a configuration change rather than a deploy.
Make the router configurable
Store the task-to-model map in configuration rather than code. Being able to change it without redeploying makes experiments cheap and lets you react quickly when a provider has an outage or changes limits.
- Week one: label and log all calls by task
- Week two: route one low-risk task, compare outputs
- Week three: route remaining low-risk tasks, add validation
- Ongoing: run regression prompts per task after any model change

Send a request to the keyless free-ai endpoint from the home page and see how it fits your project, no sign-up needed.
Read also
- Can a Fast LLM API Power Game NPC Dialogue in Real Time?
- What Are Pruned LLMs, and Are Expert-Pruned Models Worth Using?
- What Is Continuous Batching, and Why Does It Raise LLM Throughput?
- Self-Hosting a 30B Model for a Small Team vs Using a Hosted API
- Flat AI Subscription or Pay-per-Token API: Which Costs You Less?