Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Model Routing Should Be a Policy Engine, Not a Vibe Check

Not every AI request needs the strongest model, but routing by intuition creates silent quality regressions. A production model router that combines task class, risk, context, latency, budget, capability requirements, and evaluation data.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#model-routing#llm-routing#ai-cost#ai-agents#evaluation#reliability#typescript#python
On this page

Using the strongest available model for every request is simple. It is also an expensive way to solve problems that may include intent classification, short extraction, deterministic formatting, and a handful of genuinely difficult reasoning tasks.

The obvious response is model routing.

That phrase can hide a lot of hand-waving.

I have seen designs that amount to:

Text
if prompt.length < 500:    use cheap modelelse:    use smart model

Length is not difficulty. A 60-character permission question can be high risk. A 10,000-token document may require only straightforward extraction. A routing rule that saves money while quietly moving the hardest edge cases onto the wrong model is not an optimization.

I prefer to treat model selection as an application policy with measurable inputs, explicit constraints, and a fallback path.

The example here is a SaaS assistant that handles support questions, structured extraction, RAG answers, and tool-using workflows.

Start with capabilities, not prices

A model is eligible only if it can satisfy the technical contract of the task.

That can include:

Text
required input modalityminimum context requirementstructured-output supporttool-calling supportregion / data-processing requirementlatency classapproved provider list

I represent those constraints separately from quality tiers.

type ModelProfile = {  id: string;  tier: "fast" | "balanced" | "strong";  contextLimit: number;  supportsTools: boolean;  supportsStructuredOutput: boolean;  approvedDataClasses: Set<"public" | "internal" | "restricted">;  regions: Set<string>;};

A cheaper model that cannot legally or technically process the request is not a candidate.

This is especially important in enterprise products where model routing can accidentally become data routing.

Classify the task before selecting a model

I want a small application-level task vocabulary.

type TaskClass =  | "intent-classification"  | "structured-extraction"  | "rag-answer"  | "tool-planning"  | "complex-analysis";​type TaskRequirements = {  taskClass: TaskClass;  risk: "low" | "medium" | "high";  inputTokens: number;  needsTools: boolean;  needsStructuredOutput: boolean;  dataClass: "public" | "internal" | "restricted";  region: string;  latencyBudgetMs: number;  remainingBudgetMicros: bigint;};

Some fields come from deterministic application state. Others may come from a lightweight classifier.

I do not ask the same model that wants to execute an expensive action to decide, without constraints, whether it deserves the expensive model.

The host owns the routing decision.

Filter impossible candidates first

Deterministic eligibility should happen before scoring.

function eligibleModels(  models: ModelProfile[],  task: TaskRequirements,): ModelProfile[] {  return models.filter((model) => {    if (task.inputTokens > model.contextLimit) return false;    if (task.needsTools && !model.supportsTools) return false;    if (      task.needsStructuredOutput &&      !model.supportsStructuredOutput    ) {      return false;    }    if (!model.approvedDataClasses.has(task.dataClass)) return false;    if (!model.regions.has(task.region)) return false;    return true;  });}

This keeps policy failures explainable.

If no model remains, I want no eligible model for restricted data in region X, not a mysterious provider error after the router silently picked something else.

Routing rules should encode risk

The cheapest reasonable model for a newsletter subject line is not necessarily the right model for a high-impact tool plan.

A simple baseline policy might be:

function requiredTier(task: TaskRequirements): ModelProfile["tier"] {  if (task.risk === "high") return "strong";  if (task.taskClass === "complex-analysis") return "strong";  if (task.taskClass === "tool-planning") return "balanced";  if (task.taskClass === "rag-answer") return "balanced";  return "fast";}

That is not sophisticated. It is intentionally inspectable.

I would rather begin with explicit routing rules and evaluation data than train a routing model before I understand which requests are being misrouted.

Cost is a constraint, not the only objective

Once candidate models pass technical and quality policy, cost can help choose among them.

I think of the objective roughly as:

Text
minimize expected cost and latencysubject to:  capability requirements  data policy  quality floor  risk policy  run/tenant budget

That is different from pick cheapest.

The budget ledger from the previous article can expose a normal, conserve, or blocked state. In conserve mode, optional enrichment may move from balanced to fast models, but high-risk actions do not get downgraded below their quality floor just because the tenant is near a budget limit.

Sometimes the correct budget behavior is to stop or ask the user before spending more.

A cheap-first cascade needs an acceptance test

Another routing pattern is a cascade:

  1. try a fast model;
  2. accept the result if it meets a verifiable quality condition;
  3. escalate otherwise.

This works well when the acceptance test is strong.

Structured extraction is a good example. A smaller model can attempt the extraction. The application validates schema and domain invariants. If required fields are missing or inconsistent, escalate.

type ExtractionResult<T> = {  value: T;  validationErrors: string[];};​async function extractWithCascade<T>(input: {  fast: () => Promise<ExtractionResult<T>>;  strong: () => Promise<ExtractionResult<T>>;}): Promise<T> {  const first = await input.fast();​  if (first.validationErrors.length === 0) {    return first.value;  }​  const second = await input.strong();  if (second.validationErrors.length > 0) {    throw new Error("Extraction failed validation after escalation");  }​  return second.value;}

The cascade is safe because the acceptance condition is external to the model.

Self-reported confidence is not enough

This pattern makes me nervous:

Text
Ask small model to answer.Ask small model whether it is confident.If confidence > 0.8, trust it.

The same failure that produced a wrong answer can produce confident self-assessment.

Confidence can be a feature, but I prefer stronger escalation signals:

Text
schema/domain validationretrieval coveragecitation supportknown ambiguitymissing required fieldstool-policy conflictindependent classifier/judge calibrated on evals

For high-risk cases, the route itself can bypass the cheap attempt entirely.

A cascade should not spend one extra model call just to discover something the application already knew was difficult.

Routing classification can be wrong too

If a classifier decides whether a task is “simple” or “complex,” that classifier becomes part of the quality system.

It needs an evaluation set.

TypeScript
type RoutingCase = {  input: string;  expectedMinimumTier: "fast" | "balanced" | "strong";  tags: string[];};

I include edge cases where short text hides difficult semantics:

Text
"Can I delete this production key?""Refund 8,400 EUR.""Which of these clauses wins if they conflict?"

And long inputs whose task is mechanically simple:

Text
"Extract invoice number, date, and total from this document."

Length can remain one feature. It should not be the model of difficulty.

Evaluate quality by route, not only globally

Suppose overall answer quality remains flat after routing.

That can hide this:

Text
low-risk support: improved cost, same qualityhigh-risk tool planning: 8% regression

I slice evaluation by:

Text
task classrisk classchosen model/tierfallback/escalation statuslanguagecontext-size buckettenant policy class

Critical slices can have independent release gates.

Routing is infrastructure that changes which intelligence handles which user. It deserves the same regression discipline as a model upgrade.

Log the reason for the route

A production trace should not merely say:

Text
model = model-balanced-2

I want:

Text
route.task_class = rag-answerroute.risk = mediumroute.required_tier = balancedroute.selected_profile = balanced-euroute.reason = quality-floorroute.policy_version = 12

If a user reports a bad answer, I can see whether the model underperformed or the router selected a weaker model than intended.

Do not log the entire private prompt to explain routing. The structured route decision is enough for most investigations.

Route failures need a fallback policy

A preferred model can be rate-limited or unavailable.

Fallback is not simply “pick anything else.”

TypeScript
type FallbackPolicy = {  allowedProfiles: string[];  preserveMinimumTier: boolean;  allowCrossProvider: boolean;};

For a low-risk summarization task, falling back from balanced to fast may be acceptable.

For a high-risk approval proposal, I may preserve the minimum tier and return a temporary error if no equivalent model is available.

Availability should not silently lower safety requirements.

This connects directly to the circuit-breaker article: an unhealthy provider can be removed from the eligible set, but the remaining candidates still pass routing policy.

Provider diversity is not free resilience

Supporting two model providers can reduce dependency risk, but it also doubles integration surfaces:

Text
message formatsstructured-output behaviortool schemasrate-limit semanticsstreaming eventssafety behaviorusage accountingregional availability

I keep a provider adapter contract and run the same routing/evaluation cases across every eligible backend.

Do not claim “automatic provider failover” until the fallback has been tested with the exact tool and structured-output features the workflow uses.

A second provider that cannot execute the task is not a fallback.

Model changes should not require routing-code edits everywhere

Profiles belong in configuration or a registry.

TypeScript
type ModelRegistry = {  byId(id: string): ModelProfile | undefined;  active(): ModelProfile[];};

Application workflows ask for capabilities/tier, not a hard-coded vendor model string.

That lets operations canary a new model, retire an old one, or change provider mappings without rewriting business logic.

The registry version should appear in traces and eval records.

Shadow routing before moving traffic

A useful rollout pattern is to run the new router in shadow mode.

Production still uses the current model, while the candidate router records what it *would* have selected.

For a sampled subset, I can also run the candidate model offline or asynchronously and compare:

Text
route agreementquality deltacost deltalatency deltaescalation rate

This catches surprising traffic classes before the router changes the user experience.

I do not run expensive shadow inference on every request indefinitely. A bounded sample is enough to learn where the policy differs.

Route the whole workflow carefully

One agent run may contain several model roles:

Text
intent classifierretrieval query rewriteplanneranswer generatorjudge

They do not need the same model.

The biggest savings often come from moving narrow supporting tasks to smaller models while keeping the core difficult reasoning step strong.

That is usually safer than downgrading the entire agent because “the user request looks simple.”

It also produces clearer evaluation: each model has a job with a specific contract.

When routing is unnecessary

If one model already meets quality, latency, cost, and compliance requirements and traffic is modest, a router adds configuration, failure modes, and evaluation work.

Use the simple architecture until there is a measurable reason to split.

Routing becomes useful when task classes have genuinely different requirements or AI spend/latency is large enough that one-size-fits-all is wasteful.

The key is to make the decision explicit.

A model router is not a clever prompt that guesses which model feels appropriate. It is a policy boundary between product requirements and provider capabilities. Once it has eligibility rules, quality floors, budget constraints, fallbacks, traces, and evals, model selection becomes another production subsystem that can be tested rather than a cost-saving heuristic you hope is right.

KEEP READING

Related engineering notes