Sub topic 4
Rule-based routing
Prerequisites
This chapter assumes you can read and write basic Python, including functions, tuples, and regular expressions. It also assumes you have called a hosted language model through an API, and that you know tokens are billed per unit and that larger models cost more and respond more slowly. The earlier chapters covered model tiers, the cost, latency, and quality trade-off, and the signals a router can see. This chapter turns those signals into working rules.
What a rule-based router is
A rule-based router is a function that looks at a request and picks a model using fixed, human-written conditions. It runs before any model call. It does not call a model itself, and it does not learn from data.
Rule-based routing has three properties that make it the usual first choice:
- It is cheap. Checking a string length or a keyword takes microseconds and costs nothing in tokens.
- It is predictable. The same input always gets the same decision, so you can explain why a request went where it did.
- It is easy to change. Adding a rule is a code edit, not a training run.
The cost is coverage. Rules only catch the cases you thought of, and they judge the surface of a request, not its real difficulty. A short question can be hard, and a long one can be trivial.
The baseline router
The simplest useful router has two kinds of rule: a length limit and a list of words that suggest hard work.
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"This function does the following:
- It lowercases the prompt once, so keyword checks ignore case.
- It sends the request to the large model if the prompt is longer than 4,000 characters or contains any marker.
- It sends everything else to the small model.
The function is a good starting point. It also has several flaws that show up as soon as real traffic reaches it. The rest of this chapter covers them.
Choosing the signals
A rule is only as good as the signal it reads. The common signals fall into four groups.
| Signal | Example rule | Why it works | Where it fails |
|---|---|---|---|
| Length | More than 4,000 characters goes to large | Long inputs often need more reasoning and context handling | A long document with a trivial task, such as "extract the date" |
| Keywords | "prove", "refactor" go to large | Some verbs reliably signal multi-step work | Words that appear in easy requests, or hard requests with no keyword |
| Task type | `task == "classification"` goes to small | The calling code often knows the task better than any text check | Needs the caller to supply accurate labels |
| Caller context | Paid tier or an internal tool goes to large | Business value can justify the cost | Says nothing about difficulty |
Task type, when your application knows it, is usually the strongest signal. A feature that only ever extracts fields from invoices does not need to guess difficulty from words. It can declare the task and route on it. Text-based rules are for the cases where the application cannot tell.
Length is worth a second look. The baseline counts characters, but providers bill and limit by tokens. Characters are a fine proxy for English text. For code, other languages, or text full of numbers, the ratio shifts. If a hard limit matters, such as a context window of the small model, count tokens with the provider's tokenizer instead.
Making rules explicit and auditable
The baseline hides its reasoning inside one if. When a request is routed wrongly, you cannot tell which condition fired. A better structure is an ordered list of named rules. The router returns the model and the name of the rule that decided.
import re
from dataclasses import dataclass
SMALL = "small"
LARGE = "large"
HARD_PATTERN = re.compile(
r"\b(prove|step[- ]by[- ]step|refactor|analy[sz]e)\b", re.IGNORECASE
)
SIMPLE_TASKS = {"classification", "extraction", "language_detection"}
@dataclass(frozen=True)
class Decision:
model: str
rule: str
# Each rule is (name, test, model). The first test that returns True wins.
RULES = [
("hard_keyword", lambda p, meta: HARD_PATTERN.search(p) is not None, LARGE),
("simple_task", lambda p, meta: meta.get("task") in SIMPLE_TASKS, SMALL),
("too_long", lambda p, meta: len(p) > 4000, LARGE),
]
def route(prompt: str, metadata: dict | None = None, default: str = SMALL) -> Decision:
metadata = metadata or {}
for name, test, model in RULES:
if test(prompt, metadata):
return Decision(model, name)
return Decision(default, "default")
if __name__ == "__main__":
print(route("Prove that the square root of 2 is irrational."))
print(route("Please improve this sentence."))
print(route("x" * 5000, {"task": "classification"}))
print(route("x" * 5000))Running it prints:
Decision(model='large', rule='hard_keyword')
Decision(model='small', rule='default')
Decision(model='small', rule='simple_task')
Decision(model='large', rule='too_long')The Decision record is the useful part. Log it with every request, and you can later answer "why did this go to the large model?" and "how often does each rule fire?" without guessing.
The code uses str | None, which needs Python 3.10 or later.
Why order matters
Rules are checked in order, and the first match wins. Reordering them changes behavior.
Look at the last two calls in the demo. A 5,000-character document with task="classification" goes to the small model because simple_task comes before too_long. That ordering says the task type outranks the length. If you swapped the two rules, the same request would go to the large model. Neither order is wrong. Each encodes a different belief about what predicts difficulty, and you should choose deliberately and write the belief down.
A practical order is:
- Hard constraints first. For example, a prompt that exceeds the small model's context window must go to the large model, whatever else is true.
- Strong, specific signals next. Declared task types and explicit markers belong here.
- Weak, general signals last. Length and keyword guesses go here.
- A default at the end.
The default is a policy decision
The default decides what happens to every request your rules do not recognize. The baseline defaults to small, which minimizes cost and makes unrecognized hard requests fail quietly with a weaker answer. Defaulting to large reverses that. Quality is safer, and cost rises with every request you did not anticipate.
Choose the default by asking which mistake is cheaper:
- If wrong answers are costly, such as in legal, medical, or code-changing features, default to large and write rules that explicitly allow small.
- If volume is high and errors are cheap or easy to spot, default to small and write rules that explicitly demand large.
Which side you choose is a product decision, not a coding one. Record it in a comment next to the default.
Edge cases and failure modes
The baseline looks reasonable and still misroutes in predictable ways.
Substring matches
The baseline tests m in text, which matches inside words. The word "improve" contains "prove", so "Please improve this sentence" goes to the large model. The same happens with "proven", "approve", and "reproved". The regular expression in the second version uses \b, a word boundary, so "prove" matches only as a whole word. It also accepts both "analyze" and "analyse" through analy[sz]e.
Word boundaries fix one problem and create a smaller one. "Proves" no longer matches \bprove\b. If you want inflections, list them: prov(e|es|ed|ing). Add each form on purpose, and test it.
Keywords in quoted or pasted content
A user pastes an email and asks for a one-line summary. The email contains "step by step" and "analyze". The router sees the keywords and sends the request to the large model, though the task is easy. Where you can, run keyword rules on the instruction and not on the pasted content. That means your application should keep them in separate fields.
Template inflation
If your application wraps the user's text in a long prompt template or system prompt, len(prompt) measures the template as well. Then every request looks long. Measure the user-supplied text, or set the limit with the template's size in mind.
Language and phrasing
Keyword lists written in English miss requests in other languages. They also miss hard requests phrased differently, such as "walk me through why this holds" in place of "prove". Treat keyword rules as a rough filter that catches some hard requests, not all of them.
Conflicting rules
Two rules can disagree on the same request, for example a simple task type with a hard keyword in the text. Order resolves the conflict, but it does so silently. When you add a rule, test it against the rules already in the list. Check what happens when two of them match at once.
Rule growth
Rule lists grow, because every misrouted request invites a patch. After some dozens of rules, nobody knows which ones still matter. Record how often each rule fires, and remove the ones that never do.
Testing the rules
Because the router is a plain function, you can test it like one. Keep a short table of example prompts with the expected model, including the awkward ones you have found.
CASES = [
("Prove that the sum of two even numbers is even.", None, "large"),
("Please improve this sentence.", None, "small"),
("Refactor this function to remove the global state.", None, "large"),
("Label the sentiment of this review.", {"task": "classification"}, "small"),
("What is the capital of France?", None, "small"),
("y" * 4001, None, "large"),
]
for prompt, meta, expected in CASES:
got = route(prompt, meta).model
assert got == expected, (prompt[:40], got, expected)
print("all routing cases pass")Every time a misrouted request is reported, add it here first, then change the rules. That keeps old fixes from breaking when someone edits a rule later.
This test checks the rules against your intentions. It does not tell you whether the intentions are good. For that you need to compare answers on a labeled sample, which a later chapter on evaluating a routing policy covers.
Estimating what a router saves
A router pays for exactly one model per request, so its expected cost follows from the share of traffic sent to each side.
def expected_cost_router(frac_sent_to_small, cost_small, cost_large):
# A router pays for exactly one model per request.
return frac_sent_to_small * cost_small + (1 - frac_sent_to_small) * cost_largeSuppose a small-model call costs 1 unit and a large-model call costs 10. If the router sends 70% of requests to small, the expected cost is 0.7 × 1 + 0.3 × 10 = 3.7 units per request. Always sending requests to the large model costs 10, so the router saves 63%.
That saving assumes that the 70% sent to small are answered about as well by the small model as the large one would have answered them. The formula measures cost only. A router that sends 95% of traffic to small looks cheaper, but if it does so by misrouting hard requests, quality drops and the saving is not real. Measure both numbers together.
The router's own cost is close to zero, which is the main difference from a cascade. A cascade always calls the small model first and so pays for it on every request. A router decides first and pays for one model.
The two error types
A router can be wrong in two directions, and they hurt differently.
- A hard request sent to the small model. The user gets a worse answer. This is a quality loss and is often invisible in the logs.
- An easy request sent to the large model. The user gets a good answer more slowly and at higher cost. This is a cost loss and shows up directly in your bill.
Most teams tune rules to make the first error rare and accept more of the second. When you cannot tell which case matters more, write that down as part of the default decision above.
Where rules run out
Rules work well when difficulty correlates with something you can read off the request cheaply. They work badly when it does not. Warning signs include:
- Rule lists that keep growing, with each new rule fixing a handful of cases.
- Misrouted requests that no keyword or length threshold separates from correctly routed ones.
- Different teams maintaining conflicting rules for the same feature.
At that point, consider the other strategies in this tutorial. A cascade lets the small model's own confidence signal when to escalate. A learned classifier replaces hand-written conditions with a model trained on labeled examples. Neither makes rules obsolete. Many production systems keep a short list of hard rules, such as context-window limits and declared task types, and put a cascade or classifier behind them for everything else.
Summary of working practice
- Prefer declared task type over guessing from text.
- Return the name of the rule with every decision and log it.
- Order rules from hard constraints to weak guesses, and end with a deliberate default.
- Match whole words, and apply keyword rules to the instruction, not to pasted content.
- Keep a test table of tricky prompts and add to it with every misrouting.
- Compute expected cost, but never without a quality check beside it.
Exercise
A router uses the check "prove" in prompt.lower() to send requests to the large model. A user submits "Can you approve my draft and improve the tone?" Which model does the router choose, and why is that a problem? Show a regular expression that fixes it.
Show answer
The router chooses the large model. The check is a substring match, and both "approve" and "improve" contain "prove". The request is easy, so the large model adds cost and latency without any quality gain. Use a word boundary: re.compile(r"\bprove\b", re.IGNORECASE).search(prompt). That matches "prove" only as a whole word and ignores "approve" and "improve".
Exercise
Your router sends 80% of requests to the small model, which costs 2 units per call. The large model costs 20 units per call. What is the expected cost per request? What does this number leave out?
Show answer
0.8 × 2 + 0.2 × 20 = 1.6 + 4.0 = 5.6 units per request, against 20 for always using the large model. The number covers cost only. It does not show whether the small model answers its 80% of requests as well as the large model would, so you must measure answer quality on a sample alongside it.
Exercise
A rule list has "toolong" (more than 4,000 characters goes to large) before "simpletask" (classification goes to small). A 6,000-character document arrives with task="classification". Where does it go, and how do you change the outcome if you want it to go to the small model?
Show answer
It goes to the large model, because the first matching rule wins and "toolong" matches first. To send it to the small model, move "simpletask" above "too_long" so the declared task type outranks the length check.