Skip to content
The AI Agent Factory

35.4 Model routing

Approved by
Panaversity ·
12 min read

In everyday life. A hospital does not send every patient to the senior surgeon. A nurse takes blood pressure, a junior doctor handles a sore throat, the surgeon operates. And some records never leave the building, whoever asks.

What you will learn. What goes in a model registry, and how to route each kind of work to the cheapest model that does it well and may see the data. When to use no model, and how to fail safely.

Why it matters. Chapter 32 showed that the model is the biggest bill you can control. Routing is where you control it, one activity at a time.

The model registry

A table in Neon, one row per model the platform may use:

ColumnExampleWhy it is there
idqwen3.7-flashThe exact model, not a family name
provider, routeAlibaba Cloud, AI Gateway route economyWhere calls go
regionSingaporeDecides which tenants may use it
price_in, price_out$0.03, $0.13 per million tokens (up to 32K input)Cost per call
context_limit1M tokens, with price tiersSome prices rise with longer input: Claude Haiku 5.5 costs five times as much per token above 100K
tool_calling, structured_outputmeasured pass ratesSome models call tools less reliably
scoresper activity, from the golden setQuality, measured on your work: 0.875 means 7 of 8 golden questions right
data_classespublic, businessThe data it may see
statusactive, on probation, withdrawnA model can be pulled at once

Scores come from your golden set, as in Chapter 32's model comparison, never from a public leaderboard. A model that is excellent at general questions can still misread your suppliers' invoices.

Routes by activity

An AP assignment is not one kind of work. It is several activities, and each can go to a different model:

ActivityWhat it isRoute in this lab
Extract fieldsRead supplier, date, amount, PO number from an invoiceEconomy model
Match by ruleSame PO number, amount within 1%No model: a tested rule
Judge an unclear matchTwo possible POs, or a partial deliveryClaude Haiku
Handle an exceptionA dispute, a fraud signal, a new supplierClaude, with a person's review

No model is a real route. If a tested rule matches an invoice correctly every time, the match needs no model call at all.

What routing saves, honestly

Using the paper's prices from model.ts, and its medium invoice of 10 model calls at 12,000 input and 1,000 output tokens each:

SetupCalls by modelModel cost per invoiceFor 300 invoices
All Claude Haiku10 Haiku$0.0170$5.10
Extraction to the economy model6 economy, 4 Haiku$0.0097$2.92
Plus a rule for clear matches6 economy, 2 Haiku$0.0063$1.90

The table compares like with like: every row uses the paper's medium call, and none includes the exceptions, which take their own route.

Two lessons. First, the saving is real but measured in a few dollars per worker per month, as Chapter 32 warned; it matters at hundreds of workers. Second, "cheaper" depends on the price list, not the label. In model.ts, DeepSeek Flash costs more per token than Claude Haiku, so sending unclear matches to it would raise the cost. Route by measured price and score, never by reputation.

Routes by data class

Every activity's data has a class, and every tenant has rules. From Chapter 32:

Data classMay go to
Public or made-upAny tested model
The client's business dataOnly providers in the client's data agreement
Regulated or restrictedOnly approved regions

Acme's contract says supplier data stays in the United States. So for Acme, the economy model in Singapore is not a candidate for invoice extraction, however cheap. Acme's extraction goes to Claude Haiku with US-only inference, Anthropic's option to run the model only in the United States, and costs more. The router must know this without anyone remembering it.

The router

Step 3. Build src/router.ts. Given an activity, the tenant and the data class, choose a model from the registry: only active models whose data_classes and region the tenant allows, and whose score for that activity meets the minimum. Rank them by price for a typical call, cheapest first, then by score. Return a primary and a fallback list from the same filtered set. If the list is empty, refuse and escalate. Calls go through AI Gateway. Write the tests first: Acme never gets a Singapore model; a withdrawn model is never chosen; when every allowed model fails, the call is refused, not sent elsewhere.

The heart of it:

export function route(activity: Activity, tenant: Tenant, dataClass: DataClass, reg: ModelRow[]) {
  const allowed = reg.filter((m) =>
    m.status === "active" &&
    m.data_classes.includes(dataClass) &&
    tenant.allowedRegions.includes(m.region) &&
    (m.scores[activity] ?? 0) >= MIN_SCORE[activity]);
  if (allowed.length === 0) return { kind: "refuse", reason: "no approved model" };
  allowed.sort((a, b) => cost(a, activity) - cost(b, activity) || b.scores[activity] - a.scores[activity]);
  return { kind: "route", primary: allowed[0], fallbacks: allowed.slice(1) };
}

The filter comes before the ranking, and the fallbacks come from the same filtered list. That is the whole safety of the router. A fallback chosen from the full registry would, on the day Haiku has an outage, send Acme's invoices to Singapore.

The router choosing a model for Lahore Foods' judge activity, whose allowed regions are the US, Singapore and China and whose minimum score is 0.85. On the left, the registry of five models. Claude Haiku 5.5, US, judge score 0.875, active. Claude Sonnet 5.5, US, score 1.0, active. Qwen Flash, Singapore, score 0.75, crossed out because its score is below 0.85. DeepSeek Flash, China, score 0.875, active. An old economy model, Singapore, crossed out because it is withdrawn. Three arrows go to step 1, the filter: active only, allowed data class, the tenant's regions, score at or above the minimum; fallbacks come from this same set. Step 2 ranks them by the price of a typical call, then by score: primary Claude Haiku 5.5 at $0.0017, fallback 1 DeepSeek Flash at $0.0048, fallback 2 Claude Sonnet 5.5 at $0.034. A note below says that for Acme, whose data must stay in the US, the region filter also removes DeepSeek Flash and Qwen Flash, so the set is Haiku then Sonnet; when Haiku is down the call goes to Sonnet, never outside the US, and an empty set means the call is refused.

Figure 35.2. Filter first, then rank. The lab's registry and prices; a typical judge call is 12,000 input and 1,000 output tokens.

Where AI Gateway fits. The gateway sends the call, logs it, caches where allowed, and retries within a route. Your router decides which route. Make sure the gateway's own fallback setting cannot cross the line your router drew: configure one gateway route per allowed set, not one route with every provider.

What to check. Is the data class set by trusted code that knows where the data came from, not by the model? Is the minimum score per activity written down, with the golden-set run that produced it? What happens when no model is allowed: does the worker tell a person, or fail silently?

The invariant. Each activity goes to the cheapest model that does it well enough and may see its data. A fallback never crosses a data boundary.

Check yourself. Haiku and Sonnet are both down for an hour. Acme's unclear matches cannot be routed. What should happen? (They wait or go to a person. They must not fall back to a model outside Acme's allowed regions. An hour's delay is a cost; a data breach is a contract breach.)

Owner
Panaversity