Sub topic 7
Routing with a Learned Classifier
This chapter assumes you have read the chapter on rule-based routing. You should be comfortable with basic Python and have seen scikit-learn's fit and predict interface. You should also know what accuracy, precision and recall mean on a labeled dataset.
What a classifier router is
A rule-based router uses conditions you wrote by hand, such as "prompts over 4000 characters go to the large model". Rules are cheap and easy to explain, but you have to guess which signals matter. A learned classifier router replaces the guesses with a small model trained on your own traffic.
The classifier reads a request and predicts whether the small model can handle it well enough. The router then compares that prediction to a threshold and sends the request to one model. This is still routing, not cascading. The router pays for the classifier plus exactly one language model call, and it never runs the small model just to see how it did.
Where labels come from
The classifier is only as good as its labels. A label here answers the question "is the small model good enough for this prompt?" You build it from a sample of real prompts:
- Collect a few thousand prompts from production logs. Remove personal data first, following your data policy.
- Run both models on each prompt.
- Grade each answer. Use exact match, unit tests, or a rubric scored by a human or a stronger judge model, depending on the task.
- Convert the two grades into one label.
The mapping from grades to label has an edge case. There are four combinations of small and large results:
| Small correct | Large correct | Best route | Label (small is enough) |
|---|---|---|---|
| yes | yes | small, because it is cheaper | 1 |
| yes | no | small | 1 |
| no | yes | large | 0 |
| no | no | small, because the large model gains nothing | 1 |
The last row matters. If both models fail, paying for the large model buys nothing. Labeling that prompt 0 teaches the classifier to spend money on prompts that are simply too hard or badly graded. Only prompts where escalation actually helps get label 0.
def make_label(record):
"""Return 1 if the small model is the right choice, 0 if only the large model helps."""
return int(record["small_correct"] or not record["large_correct"])
records = [
{"prompt": "What is the capital of France?", "small_correct": True, "large_correct": True},
{"prompt": "Prove that the square root of 2 is irrational", "small_correct": False, "large_correct": True},
{"prompt": "Convert 5 km to miles", "small_correct": True, "large_correct": True},
{"prompt": "Refactor this module to remove circular imports", "small_correct": False, "large_correct": True},
]
for r in records:
print(make_label(r), r["prompt"])If your grading is noisy, label noise puts a ceiling on how well the classifier can do. Spend time on grading quality before you tune the classifier.
Choosing features
The classifier needs numbers to work with. There are four common choices, from cheapest to most expensive:
- Handcrafted features. Length, number of code blocks, presence of digits, language, and the task type if your application already knows it. This is essentially the rule-based router's signals, fed to a model that learns the weights.
- TF-IDF. A sparse vector of word weights, scored by how distinctive each word is. It runs in well under a millisecond and works well when the prompt wording separates easy from hard tasks.
- Embeddings. A dense vector from an embedding model. It captures meaning rather than exact words, but each request needs an extra embedding call, which adds latency and cost.
- A fine-tuned small language model. The most capable option, and the slowest to train and serve. Choose it only when simpler features plateau.
Start with TF-IDF or handcrafted features. If the classifier takes 50 ms and the small model call takes 300 ms, you have already spent a sixth of your latency budget before any answer is generated.
Training a minimal classifier
The example below trains a logistic regression on TF-IDF features. It needs scikit-learn (pip install scikit-learn). The toy dataset is far too small for real use. It only shows the mechanics.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
prompts = [
"What is the capital of France?",
"Translate 'hello' to Spanish",
"Fix the typo in this sentence",
"List three colors",
"Convert 5 km to miles",
"Summarize this sentence in five words",
"Prove that the square root of 2 is irrational",
"Refactor this module to remove circular imports and explain each step",
"Analyze the trade-offs of these three database designs",
"Debug this race condition in my async code",
"Derive the gradient of the loss for this model",
"Plan a migration from a monolith to services step by step",
]
# 1 = small model is enough, 0 = only the large model helps
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2)),
LogisticRegression(class_weight="balanced", max_iter=1000),
)
model.fit(prompts, labels)
def small_score(prompt: str) -> float:
"""Estimated probability that the small model is enough."""
# classes_ is [0, 1], so column 1 is P(label == 1)
return float(model.predict_proba([prompt])[0][1])
def route(prompt: str, threshold: float = 0.6) -> str:
return "small" if small_score(prompt) >= threshold else "large"
for p in ["What is 12 miles in km?", "Analyze and refactor this async code step by step"]:
print(route(p), round(small_score(p), 2), p)Three details are worth noting:
class_weight="balanced"stops the majority class from dominating. In real traffic, easy prompts usually outnumber hard ones, so a classifier that always says "small" can look accurate while missing every hard prompt.predict_probagives a score, not just a class. The score lets you move the threshold later without retraining.- The pipeline bundles the vectorizer and the model. You can save it as one object, so training and serving use identical preprocessing.
The exact scores you see will vary with the data and library version. With only twelve examples, treat them as illustrative.
Setting the threshold
A threshold of 0.5 is a default, not a decision. The two kinds of mistake have different costs:
- Sending a hard prompt to the small model (false "small"). Quality drops. The user sees a wrong or weak answer.
- Sending an easy prompt to the large model (false "large"). Money and latency are wasted, but the answer is fine.
Most teams care more about the first mistake, so they raise the threshold. A higher threshold sends fewer requests to the small model, which raises both cost and quality. You pick the point on that curve by replaying held-out labeled data. The sweep function from the evaluation chapter works for cascades, but a router needs its own version because it never runs both models at serving time:
def evaluate_router(records, scores, threshold, cost_small, cost_large):
"""records: dicts with small_correct and large_correct.
scores: classifier's P(small is enough) for each record, in the same order."""
correct = 0
to_small = 0
for r, s in zip(records, scores):
if s >= threshold:
to_small += 1
correct += int(r["small_correct"])
else:
correct += int(r["large_correct"])
n = len(records)
frac_small = to_small / n
cost = frac_small * cost_small + (1 - frac_small) * cost_large
return correct / n, frac_small, cost
held_out = [
{"small_correct": True, "large_correct": True},
{"small_correct": False, "large_correct": True},
{"small_correct": True, "large_correct": True},
{"small_correct": False, "large_correct": False},
]
scores = [0.9, 0.2, 0.7, 0.4]
for t in (0.3, 0.5, 0.8):
acc, frac, cost = evaluate_router(held_out, scores, t, cost_small=1.0, cost_large=10.0)
print(f"threshold={t}: accuracy={acc:.2f} to_small={frac:.2f} cost={cost:.2f}")The cost formula matches the router formula from the cost chapter: one model per request. For a fair comparison, add the classifier's own cost per request to the result. For TF-IDF it is close to zero. For an embedding-based router it can be a visible fraction of the small model's price.
Also compare against two baselines before you trust the classifier:
- Always large. This is the quality ceiling and the cost ceiling.
- Your best rule-based router. If the classifier barely beats a length-and-keywords rule, the extra training pipeline is not earning its keep.
When a classifier is worth it
| Row | Rule-based | Learned classifier | Cascade |
|---|---|---|---|
| Needs labeled data | No | Yes, with graded answers from both models | Only for tuning the threshold |
| Cost per request | One model | Classifier plus one model | Small model, plus large on escalation |
| Added latency | Negligible | Classifier inference time | Small model call before any escalation |
| Handles subtle difficulty | Poorly | Well, if the data is good | Well, if confidence is reliable |
| Failure is visible as | Obvious misrouted patterns | Silent drift | Over-escalation or false confidence |
A classifier router fits best when:
- Traffic is high enough that the savings pay for building and maintaining the pipeline.
- Difficulty is predictable from the prompt alone, so a score computed before any model call is informative.
- Latency matters, so you cannot afford to wait for a small model to fail before escalating.
It fits poorly when you have no grading signal, when traffic is low, or when difficulty depends on details the prompt text does not reveal. In those cases a cascade is a better choice, because it uses the small model's own output as evidence.
Failure modes
Distribution drift. The classifier learned from last quarter's traffic. If users start asking different things, such as a new product feature or a new language, its scores become unreliable and nothing raises an error. Monitor the share of traffic sent to each model and re-grade a fresh sample on a schedule.
Model changes invalidate labels. The labels say "this small model succeeds on this prompt." If you upgrade or swap the small model, every label is out of date. Re-run the labeling step after any model change.
Feedback loop. Once the router is live, the large model only sees prompts the router sent it. Logs from that traffic are biased, and if you train the next classifier on them alone, it inherits the old router's blind spots. Keep a small random slice of traffic, for example 2 to 5 percent, that runs both models regardless of the score. That slice is your unbiased training and evaluation data.
Overconfident scores. Logistic regression is usually reasonably calibrated. Tree ensembles and neural classifiers often are not, so a score of 0.9 may not mean 90 percent. Check by bucketing held-out scores and comparing each bucket's score with its actual success rate. If they disagree, calibrate with CalibratedClassifierCV or choose your threshold empirically, as in the sweep above.
Rare hard cases. If hard prompts are 3 percent of traffic, a classifier can score high overall accuracy while missing most of them. Measure recall on the "needs large" class separately, not just overall accuracy.
No fallback. The classifier is one more component that can fail or time out. Decide in advance what happens then. The simplest safe default is to route to the large model, which costs more but protects quality.
Exercise
A classifier router is trained on production logs from a period when all traffic went to the small model. The team labels a prompt 0 whenever the small model's answer was graded wrong, and 1 otherwise. After launch, the router sends far too many prompts to the large model, and the large model often fails on them as well. What went wrong with the labels, and how would you fix it?
Show answer
The labels treat "small model wrong" as "needs the large model," but the large model was never run on those prompts. Many were probably hard or badly graded for any model, so label 0 does not mean escalation helps. Fix it by running both models on a sample, grading both answers, and labeling a prompt 0 only when the small model fails and the large model succeeds. Prompts where both fail should be labeled 1, or dropped, because the large model adds cost without adding quality.
Exercise
On a held-out set of 1,000 prompts, a classifier router at threshold 0.5 sends 70 percent of requests to the small model. The small model costs 1 unit and the large model costs 10 units per request. What is the expected cost per request, ignoring the classifier's own cost? If the threshold is raised so that only 50 percent go to the small model, what is the new cost?
Show answer
Router cost is fracsmall * costsmall + (1 - fracsmall) * costlarge. At 70 percent: 0.7 1 + 0.3 10 = 3.7 units. At 50 percent: 0.5 1 + 0.5 10 = 5.5 units. Raising the threshold increases the cost by about 49 percent, so it should be justified by a measured quality gain on the held-out data.