Sub topic 7
Routing with a Learned Classifier
This chapter assumes you know basic Python, have called a hosted language model through an API, and understand per-token pricing. You should also have seen the rule-based router and the cascade from earlier chapters.
Why move beyond rules
A rule-based router uses signals you wrote by hand: prompt length and a list of task words. Rules are cheap and easy to explain, but they miss cases. A short prompt such as "Why does this fail?" may need the large model. A long prompt that pastes a log file may only need a summary from the small model.
A learned classifier replaces the hand-written rules with a small model trained on examples. It reads the request and predicts which tier should handle it. The router is still a router: it picks one model before any answer is generated, so each request pays for only one model.
How the classifier is trained
Training needs labeled requests. Each label says which tier the request needs. A practical way to build them:
- Collect a sample of real prompts, ideally a few thousand.
- Run each prompt through both the small and the large model.
- Grade both answers with a human reviewer, a test, or a trusted judge model.
- Label the prompt "small" if the small answer was good enough. Label it "large" if only the large answer was good enough.
- Train a classifier to predict the label from the prompt.
The input can be simple features, such as length and word counts, or a text embedding (a list of numbers that represents the meaning of the text). The classifier itself is usually small: logistic regression or a small neural network. It must be much cheaper and faster than the models it routes between. Otherwise it erases the savings.
A minimal example
This example uses scikit-learn. The tiny dataset is only to show the shape of the code. A real one needs far more rows.
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",
"Summarize this short note in one line",
"Prove that the square root of 2 is irrational",
"Refactor this module to remove circular imports",
"Analyze the trade-offs of these three database designs",
]
labels = ["small", "small", "small", "large", "large", "large"]
router = make_pipeline(TfidfVectorizer(), LogisticRegression())
router.fit(prompts, labels)
def route(prompt: str) -> str:
return router.predict([prompt])[0]
print(route("What is the capital of Spain?"))
print(route("Analyze and refactor this design"))TF-IDF turns each prompt into numbers based on which words it contains and how rare those words are. Logistic regression then learns which words point toward each tier.
Using the probability, not just the label
Most classifiers can output a probability. You can use it to bias the router toward quality. Send a request to the small model only when the classifier is quite sure it is easy:
def route_with_margin(prompt: str, min_small_prob: float = 0.7) -> str:
classes = list(router.classes_)
probs = router.predict_proba([prompt])[0]
p_small = probs[classes.index("small")]
return "small" if p_small >= min_small_prob else "large"Raising min_small_prob sends more traffic to the large model. This raises cost and quality together. You choose the value on a labeled sample, as covered in the evaluation chapter.
When a classifier is worth it
| Situation | Better choice |
|---|---|
| Few request types, clear signals | Rules |
| Many varied request types, rules keep failing | Classifier |
| You have no labeled data yet | Rules or a cascade |
| Traffic is large enough that routing errors cost real money | Classifier |
| Small model confidence is easy to measure | Cascade |
A classifier has real costs. You must collect and grade data, retrain when traffic changes, and host another component. If the savings from a better router are smaller than that work, stay with rules.
Common errors
- Training on the wrong label. If you label by "which model is cheaper and adequate" but your grading is loose, the router learns to send hard requests to the small model.
- Imbalanced data. If 95% of prompts are "small", a classifier that always says "small" looks accurate. Check the recall on the "large" class, which is the class where mistakes hurt quality.
- Distribution drift. Users change what they ask. A router trained on last quarter's prompts may degrade. Keep a sample of recent traffic for re-checking.
- Evaluating on training data. Hold out a test set. Otherwise you will overstate how well the router works.
- A slow router. Embedding with a large model to decide whether to use a large model defeats the purpose.
Exercise
A classifier router labels 95% of your test prompts "small" and reports 94% accuracy. A teammate says it is working well. What do you check first, and why?
Show answer
Check recall on the "large" class, for example with a confusion matrix. Predicting "small" for everything would score about 95% on this data, so 94% accuracy shows little. The router may be sending hard requests to the small model, which lowers answer quality.