# Routing

**Also known as:** LLM router · Intent classification · Model routing  
**Category:** AI Patterns (Model in the loop)  
**Complexity:** 2/5  
**Guide:** https://layra4.dev/architectures/ai/routing

*Classify first, so each request reaches the prompt built for it.*

A prompt that handles every kind of request collects instructions for each, and they conflict. Refund rules confuse the technical answers. Code examples mislead the billing questions. Every fix for one kind of request can quietly break another.

Routing adds a small step in front. Rules, an embedding match or a small model gives the request a label. Plain code then sends it to the branch for that label, with its own prompt, tools and model. The router now limits quality: the best branch cannot fix a request sent to the wrong one.

> **In one sentence.** One cheap classification step in front of several focused branches beats one big prompt that tries to handle everything.

## Origin (2024)

Named as a workflow pattern in Anthropic's Building effective agents (2024). It is the Content-Based Router from Enterprise Integration Patterns (2003), with a model in place of a fixed rule.

## The parts

### The classifier

The small, fast step that labels the request before any real work. It runs on every request, so its cost and latency are the tax the pattern charges.

- Use the simplest thing that works: rules, then embeddings, then a small model
- Returns a label from a fixed set, plus a rough confidence score

> "cancel my subscription" → { intent: "billing.cancel", confidence: 0.93 }

### The route table

The mapping from label to branch, in plain code. It is boring on purpose: the intelligence lives in the classifier and the branches, so the mapping can be complete, typed and easy to review.

- Covers every label; a missing one is a compile error
- Names the prompt, tools and model for each branch in one place

### The branch

Where a routed request lands: a prompt with examples for exactly this kind of work, the few tools it needs, and the cheapest model that handles it. Each branch is owned and tested on its own.

- A prompt change affects only this branch
- Model chosen per branch: most traffic is easier than the hardest traffic

### The fallback

The branch for low-confidence and out-of-scope requests: a general prompt, a clarifying question, or a person. It is a real branch, not an error path.

- Reached through a confidence floor
- Its share of traffic is the router's health metric

## Design rules

### Try the simplest classifier first

Keyword rules and an embedding similarity check handle more routing than people expect, at almost no cost and fully predictable. Use a small model only when labels need real reading, and rarely a large one.

### Classify into a fixed set, through a schema

Free-text labels drift: “billing”, “Billing”, “billing_question”, and the switch silently stops matching. An enum output makes unknown labels impossible, and the compiler can check the route table covers every label.

### Give unclear requests a fallback

Send low-confidence requests to a fallback: a general prompt, a clarifying question or a person. Set the floor from labelled requests, because a model's own score is rough. Without it, the wrong branch answers.

### Test the router on its own

Keep a labelled set of real requests and rerun it after every change. Router accuracy limits the whole system, and the test needs only assertions. Tested only end to end, a misroute looks like a branch failure.

## A router and its branches

```
src/assistant/
router/                         # the front door: label, then dispatch
  classify.ts                   # rules → embeddings → small model; a label from a fixed set
  routes.ts                     # label → branch, complete; the product's surface in one file
  fallback.ts                   # where low confidence goes
branches/                       # one folder per kind of request
  billing/                      # its own prompt, examples and tools
  technical/                    # other examples, other tools, maybe a bigger model
eval/                           # the two layers, scored separately
  router.ts                     # labelled real requests; accuracy per label
  branches.ts                   # each branch against its own cases
```

Each branch is owned separately: you can improve and test billing/ without rereading technical/. The router folder stays small on purpose.

## Examples

### Label cheaply, dispatch plainly

```typescript
const { intent, confidence } = await smallModel.call({
  input: request.text,
  schema: z.object({ intent: z.enum(INTENTS), confidence: z.number() }),
});                                    // a fraction of the cost of any branch

if (confidence < FLOOR) return fallback.handle(request);  // unclear: no guessing

const branch = routes[intent];         // complete: a missing entry will not compile
metrics.increment(`route.${intent}`);  // the label explains why this answer happened

return branch.model.call({
  system: branch.prompt,               // examples for THIS kind of request only
  tools: branch.tools,                 // and no other tools
  input: request.text,
});
```

A small model returns a label from a fixed set, a confidence floor sends unclear requests to the fallback, and each branch has its own prompt, tools and model.

## When to use

- Different kinds of request pull one prompt in different directions
- Kinds of request need different tools or permissions
- Most traffic is easy, and a cheap model could serve it

## When not to use

- Requests do not fall into kinds you can name
- One request often needs several branches combined
- Traffic is too low to know what the kinds are yet

## Benefits

- Each branch is small and can be tested on its own
- A prompt change affects one branch, not the whole product
- Easy requests can go to a model that costs a tenth as much

## Costs

- One classification call before every request
- A misrouted request fails, however good its branch is
- Many branch prompts to version and keep consistent on shared rules

## Pitfalls

- No fallback, so unclear requests are forced into the nearest branch.
- Free-text labels, so the switch silently stops matching as the wording drifts.
- Branch prompts that drift apart on shared rules, like tone or refund policy.
- Too many branches. Prompts copied between branches are the sign you split too finely.

## Similar patterns, compared

Routing is dispatch: one request, one branch, nothing to merge. Its neighbours split work up, and an older pattern does the same dispatch at the network edge.

### Routing vs Multi-Agent Orchestration

The router picks one specialist per request; the orchestrator uses several and merges what comes back. — [Multi-Agent Orchestration](https://layra4.dev/architectures/ai/multi-agent)

**What is genuinely the same**

- Both replace one general prompt with specialists that have their own prompts and tools
- Both put a deciding step in front of the work

**What actually differs**

- A routed request lands on exactly one branch, so there is nothing to merge
- A branch is a prompt plus settings; a worker is an agent with its own loop

**Pick Routing when:** Each request is one kind of thing and you can name the kinds. Dispatch is enough; coordination would be pure overhead.

### Routing vs API Gateway

The same idea at different levels: send the request to the part built for it — there by path and header, here by what the text means. — [API Gateway](https://layra4.dev/architectures/architectural/api-gateway)

**What is genuinely the same**

- One entry point in front of many specialists that do not know each other
- Both add a hop that everything now depends on

**What actually differs**

- A gateway matches structure exactly; a router classifies meaning, with some error
- A gateway routes between services; a router usually routes between prompts in one process

## Related patterns

- [Multi-Agent Orchestration](https://layra4.dev/architectures/ai/multi-agent) — when one branch cannot finish the job alone
- [Structured Output](https://layra4.dev/architectures/ai/structured-output) — the enum that keeps the label set fixed
- [Evaluation Harness](https://layra4.dev/architectures/ai/eval-harness) — a labelled request set is the cheapest eval you will write
- [API Gateway](https://layra4.dev/architectures/architectural/api-gateway) — the same dispatch at the network edge, without the guessing
- [Prompt Chaining](https://layra4.dev/architectures/prompting/prompt-chaining) — a fixed sequence of calls: no branch to choose, a check after each

## Further reading

- *Building effective agents* — Anthropic (2024) — Routing as the simplest workflow: classify, then hand off to a specialist.
- *Enterprise Integration Patterns* — Hohpe & Woolf (2003) — The Content-Based Router: this pattern's fixed-rule ancestor.
- *RouteLLM: Learning to Route LLMs with Preference Data* — Ong et al. (2024) — Sending easy queries to a cheap model without losing quality.
