AI & ML

What is Model Routing in AI?

· 5 min read
Community Article
Community articles are authored by SitePoint Premium contributors. Content is screened before publication, and SitePoint reserves the right to moderate or remove articles that violate our guidelines. Views expressed are those of the authors and do not necessarily reflect those of SitePoint.

What is Model Routing in AI?

Matthew Duffin
Matthew Duffin
Published in
AI·
·Updated:

The AI briefing for Developers

Stay up to date with AI tools, model releases, and developer workflows that matter.

Weekly. Free. One click to leave.

Share this article

What is Model Routing in AI?
SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools
Start Free Trial

7 Day Free Trial. Cancel Anytime.

"Do you know the closest ATM?" and "I was charged twice, the refund never arrived, and now my card is blocked" are both customer messages. Most AI apps send both to the same large model and pay large-model prices for each one.

Model routing fixes that. A router looks at each request and sends it to the cheapest model that can handle it, and keeps the expensive model for the requests that need it.

In this guide we'll cover what model routing is, how routers decide, and what it saves. Then we'll build a small router in about 60 lines of JavaScript and run it over 200 customer messages. At one setting it matched a large model's accuracy for about a third of the cost. At another it came within a point and a half for 89% less.

What Is Model Routing in AI?

Model routing in AI is the practice of sending each request to the model best suited to it, instead of sending every request to one model. A router sits between your app and a pool of models, reads each request, and picks a model based on what you care about: cost, speed, or quality.

You'll also see it called AI model routing, LLM routing, or LLM model routing. They all mean the same thing. The pool might be a small and a large model from one provider, or models from several providers behind one API.

The idea rests on one observation: most requests are easy. A small model answers them as well as a large one, in a fraction of the time and for a fraction of the price. The router's whole job is finding the hard ones.

The diagram below shows a typical AI model routing architecture.

ai-model-routing-architecture-diagram.png

AI Model Routing Architecture

How Does Model Routing Work?

Model routing works in three steps: the router reads the request, decides which model should answer it, and forwards the request to that model. The middle step is where routers differ. Routing tools decide which model to use in one of four ways.

Rule-Based Routing

Rule-based routing uses rules you write by hand. Requests from free-plan users go to a small model. Anything tagged as code goes to a coding model. Prompts over a certain length go to a model with a bigger context window. It's simple, predictable, and free to run, but the rules only know what you thought of in advance.

What Is Intelligent Model Routing?

Intelligent model routing uses a model to make the decision. A small, fast classifier reads each request and predicts which model in the pool will answer it well. You'll also see it called smart or dynamic model routing.

Two more terms come up here. Task-aware routing picks a model by the kind of job, like summarising, coding, or answering a support question. Context-aware routing also looks at what surrounds the request, like the conversation so far, the user, or the tools available.

The big platforms work this way. Microsoft describes its Foundry model router as "a trained language model" that picks a model for each prompt in real time. Google says Gemini Notebook uses its new Decisions API as a real-time router, serving everyday queries with up to 40% lower latency. I've tested the Google Decisions API against Jev on the same messages we'll use below.

Cascade Routing

Cascade routing tries the cheapest model first and only moves up when the answer isn't good enough. The usual test is confidence: if the cheap model is sure, keep its answer. If it isn't, send the request to a stronger model. It's also called confidence-based routing, and it's what we'll build below.

A cascade needs no separate classifier, because the first model's own confidence does the routing. The trade-off is that escalated requests pay for two models and wait for both.

Fallback Routing

Fallback routing is about staying up, not saving money. If a model times out, hits a rate limit, or its provider has an outage, the router sends the request to the next model on a list. Most production routers combine fallbacks with one of the three methods above.

What Are the Benefits of Model Routing in AI Systems?

The main benefits of model routing in AI systems are lower cost, faster responses, and fewer outages, without giving up quality on the hard requests.

  • Lower cost. Easy requests stop paying large-model prices. In the test below, routing cut the bill by 68% to 89%.
  • Faster responses. Small models answer in a fraction of the time. Nine in ten of our routed messages came back in about a quarter of a second.
  • Quality where it counts. The hard requests still reach the strongest model.
  • Reliability. With fallbacks, one provider's outage doesn't take your app down.
  • Less lock-in. Once requests go through a router, swapping or adding a model is a config change.

What We're Building

We'll build a cascade router for a job every support tool has: sorting customer messages. Each message gets one of ten labels, like atm support or request refund.

The router has two models:

  • The cheap model is Jev from TypeSafe. Jev is a System One model. It answers typed questions instead of writing text, and every answer comes back with a confidence score. My tutorial on building a typed AI pipeline with Jev and Clairic covers how these models work.
  • The strong model is Claude Opus 5.5. It's slower and costs far more per message, but it gets more of the hard ones right.

The test set is 200 messages from Banking77, a public set of banking support messages: ten labels, 20 messages each. They're the same 200 messages from my zero shot classification test, which is where the single-model numbers below come from.

Prerequisites

  • Node.js 22 or later
  • A TypeSafe API key and an Anthropic API key

Install the two SDKs:

npm install @typesafe-ai/sdk @anthropic-ai/sdk

Put both keys in a .env file and run the examples with node --env-file=.env. It's the same setup as in my guide to getting a YouTube API key.

TYPESAFE_API_KEY=...
ANTHROPIC_API_KEY=...

Step 1: Ask the Cheap Model First

Create router.mjs. The first function sends the message to Jev with one multiple-choice question, and returns the label Jev picked along with its confidence:

import Anthropic from '@anthropic-ai/sdk';
import { choice, TypeSafeClient } from '@typesafe-ai/sdk';

export const LABELS = [
  'atm support',
  'card acceptance',
  'cash withdrawal charge',
  'lost or stolen card',
  'receiving money',
  'request refund',
  'top up limits',
  'topping up by card',
  'unable to verify identity',
  'verify my identity',
];
const QUESTION = 'Which label best fits this customer message to a bank?';

export async function askCheap(message) {
  const jev = new TypeSafeClient(); // reads TYPESAFE_API_KEY
  const { answers } = await jev.systemOne({
    state: message,
    questions: { label: choice(QUESTION, Object.fromEntries(LABELS.map((l) => [l, null]))) },
  });
  return { label: answers.label.choice, confidence: answers.label.confidence };
}

Confidence runs from 0 to 1. When nearly all the probability sits on one label, it's close to 1. When Jev is torn between two labels, it drops.

Step 2: Add the Strong Model

The second function asks Claude Opus 5.5 the same question. The output_config block limits the answer to one of our labels, so there's no free text to parse. SitePoint's guide to LLM structured output with JSON Schema explains how that works.

export async function askStrong(message) {
  const claude = new Anthropic(); // reads ANTHROPIC_API_KEY
  const response = await claude.messages.create({
    model: 'claude-opus-5-5',
    max_tokens: 2000,
    system: `You sort customer messages sent to a bank. Pick the one label that best fits the message.\n\nLabels:\n${LABELS.map((l) => `- ${l}`).join('\n')}`,
    messages: [{ role: 'user', content: message }],
    output_config: {
      effort: 'low',
      format: {
        type: 'json_schema',
        schema: {
          type: 'object',
          properties: { label: { type: 'string', enum: LABELS } },
          required: ['label'],
          additionalProperties: false,
        },
      },
    },
  });
  const text = response.content.find((block) => block.type === 'text')?.text;
  if (response.stop_reason !== 'end_turn' || !text) throw new Error('No answer from the strong model');
  return { label: JSON.parse(text).label };
}

Step 3: Route on Confidence

The router itself is about a dozen lines:

export async function route(message, { cheap = askCheap, strong = askStrong, threshold = 0.8 } = {}) {
  const first = await cheap(message);
  if (first.confidence >= threshold) return { label: first.label, model: 'cheap' };
  try {
    const second = await strong(message);
    return { label: second.label, model: 'strong' };
  } catch {
    return { label: first.label, model: 'cheap (strong model failed)' };
  }
}

if (process.argv[2]) console.log(await route(process.argv[2]));

If Jev is at least 80% confident, its answer goes straight back. If not, Claude answers instead. And if Claude fails, the router falls back to Jev's answer, because a shaky answer beats an error page.

Try it on an easy message and a harder one:

node --env-file=.env router.mjs "card is lost, please help"
{ label: 'lost or stolen card', model: 'cheap' }

node --env-file=.env router.mjs "Which ATMs accept this card?"
{ label: 'atm support', model: 'strong' }

Jev was sure about the lost card. On the ATM question it leaned towards card acceptance with a confidence of 0.64, so the router asked Claude, which got it right.

Because cheap, strong, and threshold are options, the same function routes between any two models.

How Can Model Routing Reduce AI Costs?

Model routing reduces AI costs by keeping easy requests on a cheap model and paying for the expensive one only when it's needed. Here's what that looked like on our 200 messages, starting with each model on its own:

SetupAccuracyMedian responseCost per 1,000 messages
Jev on every message92.0%226 msUS$0.016
Claude Opus 5.5 on every message95.0%1,926 msUS$1.96

Opus gets six more messages right out of 200, and costs more than 120 times as much.

Now the router, at four confidence thresholds:

ThresholdSent to OpusAccuracyCost per 1,000 messagesSaving against Opus aloneMedian response
0.75.5%93.0%US$0.1294%229 ms
0.810.5%94.5%US$0.2289%234 ms
0.921%94.5%US$0.4378%251 ms
0.9531%95.0%US$0.6268%274 ms

model-routing-cost-results.png

Two results stand out:

  • At 0.8, one message in ten went to Opus. Accuracy was 94.5%, half a point under Opus alone, for 89% less.
  • At 0.95, about three in ten went to Opus. Accuracy matched Opus exactly, for 68% less.

Speed improved too. At the 0.8 threshold, the messages Jev kept came back in a median of 227 ms. The ones that escalated took about 2.1 seconds, because they waited for both models.

A note on method: I ran every message through both models once and saved the answers, then replayed the router over them at each threshold. That's how you compare thresholds without paying for the same test four times.

Then I ran the router live to check. At 0.95 it scored the same 95.0% and sent 61 messages to Opus. At 0.8 it scored 93.5% and sent 20, a point under the replay. Two answers moved: one of Jev's confidence scores landed at 0.82 instead of 0.78, just over the line, and Opus changed its answer on one message. Scores near the threshold shift a little between runs, so leave yourself a margin.

The choice of cheap model matters less than you'd think. With Google's Gemini Decision 1 in first place instead of Jev, a 0.7 threshold reached the same 95% for US$0.28 per 1,000 messages.

Does Model Routing Hurt Output Quality?

Model routing can cost a little quality, and the threshold decides how much. In our test the gap to Opus ranged from nothing at 0.95 to two points at 0.7.

The loss comes from one place: answers the cheap model got wrong while feeling sure. At the 0.8 threshold, Jev kept five wrong answers because its confidence was above the line. Opus got four of those five wrong as well, so only one was a real loss: "Do all ATMs take this card?", which Jev filed under card acceptance with a confidence of 0.91.

Escalating isn't risk-free either. On one message, Jev had the right label with a confidence of 0.44, and Opus overruled it with the wrong one.

Three habits keep quality up:

  • Set the threshold from your own data. Run a few hundred real requests through both models, then pick the lowest threshold that meets your accuracy bar.
  • Improve the cheap model before you lean on the expensive one. In my test, adding a one-line description to each label took Jev from 93% to 99% on fresh messages, which leaves far less to escalate.
  • Don't expect routing to fix a model that makes things up. A router chooses who answers. It doesn't check the answer. For that, see how to reduce hallucinations in LLMs.

How to Optimize Costs Using AI Model Routing

To optimize costs using AI model routing, measure first, route second, and keep measuring. These six steps cover LLM model routing cost optimization for any pair of models:

  1. Get a baseline. Run a sample of real requests through your current model and record accuracy, response time, and cost.
  2. Run the same sample through a cheaper model. Note where it agrees with the big one. That's the traffic you can move.
  3. Pick a routing signal. Use confidence if the cheap model reports it. If it doesn't, use rules or a small classifier.
  4. Sweep the threshold. Replay the saved answers at several thresholds and choose the cheapest one that meets your quality bar.
  5. Log which model answered. The split between models is the first thing to check when the bill changes.
  6. Re-test when models change. New model versions shift both prices and accuracy, so last quarter's threshold may be wrong.

The return is easy to estimate once you know the split. If nine in ten requests stay on a model that costs 1% as much, the bill drops by about 89%, which is what we measured.

Which Inference Providers and AI Gateways Have Multi-Model Routing?

Several inference providers have multi-model routing built in, and most AI gateway platforms support model routing too, so you don't have to write your own. As of November 2026, these are the top model routing solutions for AI apps. Each name links to the tool's model routing docs:

ToolHow it routes
OpenRouter Auto RouterA decision model picks a model and a reasoning effort for each request. There's no extra fee: you pay the standard rate of the model it selects.
Microsoft Foundry model routerPart of Microsoft Foundry (formerly Azure AI Foundry). A trained model picks from OpenAI, Anthropic, xAI, Meta, and DeepSeek models, in Balanced, Cost, or Quality mode.
Amazon Bedrock Intelligent Prompt RoutingPredicts the response quality of each model and routes between two models in the same family.
Cloudflare AI Gateway dynamic routingRule-based flows you build visually or in JSON: route by user, split traffic for A/B tests, and fall back when a rate limit is hit.
LiteLLM RouterOpen-source load balancing across deployments by latency, cost, or usage, with retries and fallbacks.
nexos.ai Smart RoutingA model selector that chooses a model for each request from the ones your organization has approved.

Hosted model routing platforms for large language models decide for you, which is the fastest way to start. A hand-built router like ours takes more work, but you choose the signal and you can see why every request went where it did.

Frequently Asked Questions

What is an LLM router?

An LLM router is the component that does model routing for large language models. It can be a function in your own code, like the one in this guide, a hosted model such as Microsoft Foundry's model router, or a feature of an AI gateway.

What is smart model routing?

Smart model routing is another name for intelligent model routing: a model, not a hand-written rule, decides where each request goes. Dynamic model routing means the same thing.

What's the ROI of AI model routing?

The ROI of AI model routing depends on how much of your traffic a cheaper model can handle. In our test, a 0.8 threshold kept 89.5% of messages on the cheap model and cut the cost per 1,000 messages from US$1.96 to US$0.22, for about a point of accuracy. The build was about 60 lines of code.

How does OpenRouter's auto model routing work?

OpenRouter's auto model routing works through its Auto Router. You set the model to openrouter/auto, and a decision model picks a model and a reasoning effort for each request. You pay the standard rate of whichever model it selects, with no extra fee.

How does OpenClaw model routing work?

OpenClaw model routing is a primary model plus an ordered list of fallbacks. In the OpenClaw model routing configuration you set agents.defaults.model.primary and agents.defaults.model.fallbacks, and an agent can override the fallback list. When a model fails, OpenClaw first rotates auth profiles on the same provider, then moves to the next model on the list, as its model failover docs describe. That makes it fallback routing, not cost-based routing.

How does an AI gateway simplify model routing?

An AI gateway simplifies model routing by putting every model behind one API, one set of keys, and one place for logs. Your app calls the gateway, and the routing rules live in config instead of code, so changing a model doesn't need a deploy.

What is mid-stream failover in AI model routing?

Mid-stream failover is when a router switches models after a streamed response has already started, because the first model failed partway through. It's the hardest kind of failover, because the user has already seen part of an answer. Many routers only fail over before the first token arrives and return an error after that, so check what your gateway does.

Source: Matthew Duffin · www.sitepoint.com