Sub topic 3
What a Router Can Look At
This chapter assumes you can write basic Python, have called a hosted language model through an API, and know that models differ in cost, speed, and capability. It also assumes you know what tokens are and how per-token pricing works. The previous chapter covered the cost, latency, and quality trade-off. Here we ask a narrower question: what information does a router have when it must decide, and how reliable is each piece?
Why the inputs matter
A router makes its decision before the expensive work happens. If it could see the large model's answer, it would not need to route. So every routing signal is a proxy: something cheap to observe that correlates with "this request needs the large model."
Proxies have two properties you should judge for each signal:
- Cost to obtain. Some signals are free (string length). Others need a network call or a model run.
- Reliability. How often does the signal agree with the truth about difficulty? A signal that is free but wrong half the time saves nothing.
A good router uses the cheapest signals that are reliable enough, and only pays for expensive signals when the cheap ones are unclear.
Signal families
Routing signals fall into four families, ordered roughly by how much they cost to compute.
| Family | Examples | Cost to compute | Typical reliability |
|---|---|---|---|
| Request surface | Prompt length, language, presence of code, keywords | Near zero | Low to moderate |
| Request metadata | Endpoint, user tier, feature flag, declared task type | Near zero | High, when set by your own code |
| Derived features | Token count, embedding, classifier score | Small to moderate | Moderate to high |
| Model-side signals | Small model's confidence, self-reported difficulty | One small model call | Moderate, varies by method |
The last family belongs to cascades and is covered in later chapters. This chapter focuses on the first three, which a router can read before any model runs.
Request surface features
Surface features come from the text of the prompt itself and need no model.
Length
Long prompts often carry more context, more instructions, or more documents to reason over. They also cost more to process, so sending them to the large model costs more in absolute terms. Length is the signal used in the rule-based router from the spine:
def route(prompt: str) -> str:
text = prompt.lower()
hard_markers = ("prove", "step by step", "refactor", "analyze")
if len(prompt) > 4000 or any(m in text for m in hard_markers):
return "large"
return "small"Length is a weak proxy. A 5,000-character prompt that pastes a log file and asks "what is the timestamp of the last error?" is easy. A 40-character prompt such as "Is P equal to NP?" is not a request any small model will handle well. Character count also varies by language: the same meaning needs more tokens in some languages than others. If your decision is about cost, count tokens with the tokenizer your provider uses, not characters.
Keywords and phrases
Words such as "prove", "refactor", or "step by step" hint at multi-step reasoning. They are cheap to check and easy to explain to teammates. They also have both kinds of error:
- False positives. "Summarize this in one step by step list" matches a marker but is easy.
- False negatives. "Why does this deadlock?" matches nothing but may need deep reasoning.
Keyword lists drift as users change how they phrase requests. Treat them as a starting point and measure how often they are right (the evaluation chapter shows how).
Structure and content type
You can detect structure cheaply:
- Fenced code blocks or common code punctuation suggest a programming task.
- Many digits and operators suggest arithmetic or data work.
- A request for JSON output with a strict schema suggests a formatting task, which small models often handle well.
- The language of the text, which matters if your small model is weaker in some languages.
Content type is often more informative than length, because it ties to what you know about each model's strengths. If your evaluations show the small model matches the large one on extraction and classification but lags on code generation, then "contains a code request" is a strong signal.
Request metadata
Metadata is information your application already knows about the request that is not in the prompt text. This is the most underused family, and often the most reliable, because your own code sets it.
- Endpoint or feature. A "suggest a subject line" button and a "review this contract" button hit different code paths. You know the difficulty of each by design.
- Declared task type. If your product has task categories (summarize, translate, extract, chat), pass the category to the router.
- User tier. A paid plan might map to the large model by default. This is a business rule, not a difficulty estimate, so keep it separate in your code and in your reports.
- Conversation state. Turn number, whether the user rephrased the previous question (a sign the last answer failed), or whether tools are in use.
- Latency budget. An autocomplete request that must answer within 300 ms cannot wait for a large model. The deadline itself is a routing signal.
A router that combines several of these signals can look like this:
from dataclasses import dataclass
@dataclass
class Request:
prompt: str
task: str # "extract", "chat", "code", ...
deadline_ms: int # how long the caller will wait
retry_of_previous: bool = False
SMALL_FRIENDLY_TASKS = {"extract", "classify", "translate"}
def route(req: Request) -> str:
# Hard constraints first: a tight deadline rules out the large model.
if req.deadline_ms < 500:
return "small"
# A rephrased question suggests the earlier answer failed.
if req.retry_of_previous:
return "large"
# Task type known to be easy for the small model.
if req.task in SMALL_FRIENDLY_TASKS:
return "small"
# Fall back to a surface feature.
if len(req.prompt) > 4000:
return "large"
return "small"
print(route(Request("Pull out the invoice total.", "extract", 3000)))
print(route(Request("Why does this deadlock?", "code", 3000)))
print(route(Request("Why does this deadlock?", "code", 300)))Running it prints small, then small, then small. The second result shows a limit of the design: nothing in the rules marks a short code question as hard, so it falls through to the default. That is the kind of gap an evaluation (covered later) will expose.
The order of the checks encodes priority. Hard constraints such as deadlines come first because they are not negotiable. Quality heuristics come after.
Derived features
Derived features need some computation, but not a call to a generative model.
Token count
Token count is length measured in the unit that determines price. Use it when cost is the concern, for example "never send more than 20,000 tokens to the large model without approval."
Embeddings
An embedding is a list of numbers that represents the meaning of a text, produced by a small, cheap model. Two prompts with similar meaning get similar vectors. A router can compare a new prompt's embedding to labeled examples:
- Find the nearest known prompts.
- If most of them were handled well by the small model, send this one to the small model.
This makes the router sensitive to meaning rather than wording, at the price of an embedding call per request (usually far cheaper than a generation call, but not free, and it adds latency).
Classifier scores
A classifier is a small model trained to predict a label, here "small model is enough" or "needs large model." Its output score is a derived feature, and you can threshold it like any other signal. Training one is the subject of the classifier routing chapter.
Signals the router should not trust
Some tempting signals mislead.
- Politeness or tone. "Please" does not predict difficulty.
- Prompt length alone. As shown above, it fails in both directions.
- User claims. A prompt that says "this is a very hard question" tells you about the user, not the task. It is also easy to game if cost matters to you.
- Signals the model can see but you cannot control. If a user can edit the prompt to change the route, they can steer it. In a system where the large model is more expensive or more permissive, treat prompt-derived signals as untrusted input.
Comparing cost and reliability
Choose signals by asking three questions:
- Can I get it before any model runs? If yes, it can drive a pure router.
- Does it come from my code or from the user? Code-set metadata is trustworthy. User text is not.
- How often is it wrong, and which direction is worse? Sending a hard request to the small model risks a bad answer. Sending an easy request to the large model wastes money. Which error costs more depends on your product.
That last question matters for every later choice. It tells you whether to make the router lean toward the large model (when bad answers are expensive) or toward the small model (when cost dominates).
| Error | Consequence | Example product where it hurts most |
|---|---|---|
| Hard request sent to small model | Poor answer, user distrust, retries | Legal or medical drafting |
| Easy request sent to large model | Higher cost and latency | High-volume autocomplete |
Combining signals
Real routers combine signals. Three patterns are common.
- Ordered rules. Check signals in priority order and return at the first match, as in the code above. Simple and easy to debug.
- Scoring. Assign each signal a weight, add them, and compare the total to a cutoff. This handles weak signals that only matter in combination.
- Staged routing. Use cheap signals first. Only compute expensive ones (an embedding or classifier) when the cheap ones are inconclusive.
A scoring version looks like this:
def difficulty_score(prompt: str, task: str) -> float:
score = 0.0
if len(prompt) > 4000:
score += 0.4
if task == "code":
score += 0.3
lowered = prompt.lower()
if any(w in lowered for w in ("prove", "step by step", "analyze")):
score += 0.3
if "```" in prompt:
score += 0.2
return score
def route(prompt: str, task: str, cutoff: float = 0.5) -> str:
return "large" if difficulty_score(prompt, task) >= cutoff else "small"
print(route("Analyze this step by step: ...", "chat"))
print(route("Translate to French: bonjour", "translate"))The first call scores 0.3 + 0.3 = 0.6 only if both conditions apply. Here the prompt contains "analyze" and "step by step", but the code adds the 0.3 once because it uses any, so the score is 0.3 and the output is small. The second call also prints small. This is a good reminder that scores should be checked on examples, not assumed. If you want each marker to count, sum them separately.
Edge cases
- Missing metadata. Decide a default. Falling back to the large model is safe for quality and costly in volume. Falling back to the small model is the reverse. Log how often the default is used.
- Empty or very short prompts. Length-based rules send these to the small model, which is usually fine, but a short prompt in a long conversation may depend on earlier turns. Compute signals over the full context you actually send, not only the last message.
- Multi-turn drift. A conversation that starts easy can become hard. Re-evaluate the route on each turn instead of fixing it for the session, but be aware that switching models mid-conversation can change style and tone.
- Attachments. If the request includes documents or images, the text length understates the work. Include attachment size or type as a signal.
Summary of design guidance
- Prefer metadata your own code sets over text inspection.
- Use cheap signals first, and add costly ones only when needed.
- Put hard constraints (deadlines, policy) before quality heuristics.
- Treat user-controlled text as untrusted for any route that affects cost or safety.
- Decide which error direction is worse for your product, and lean the router that way.
- Test every rule on examples. Small mistakes in a rule can silently change routing.
Exercise
A router uses only prompt length (over 4,000 characters goes to the large model). Give one example of a request it would send to the wrong model in each direction, and name a signal from this chapter that would improve each case.
Show answer
Wrong toward the small model: a short prompt such as "Why does this deadlock?" asks for hard reasoning but stays under the length limit. A declared task type of "code" (request metadata) or a code-related keyword or classifier score would help. Wrong toward the large model: a long prompt that pastes a log file and asks for one timestamp is easy but exceeds the limit. A declared task type of "extract" (metadata) would route it to the small model.
Exercise
In the scoring example, why does "Analyze this step by step: ..." with task "chat" score 0.3 and not 0.6? How would you change the code so each marker adds to the score?
Show answer
The code uses any(...) over the marker list, which returns one True result regardless of how many markers match, so 0.3 is added once. To count each marker, sum them, for example: score += 0.3 * sum(w in lowered for w in ("prove", "step by step", "analyze")). Then two matches give 0.6, which reaches the 0.5 cutoff.