Sub topic 3
Routing with a Learned Classifier
Assume you know basic Python, can call language models through an API, and understand token-based pricing. A learned classifier is a model that predicts which model tier should handle a request. It learns from labeled examples instead of relying only on hand-written rules.
Create records containing request features and a target label. The label can be the smallest model that meets your quality requirement, or the model that produced the best answer during testing. Useful features include token count, detected task type, language, customer tier, and the small model's confidence score.
from sklearn.linear_model import LogisticRegression
features = [[120, 0], [2500, 1], [80, 0], [1800, 1]]
labels = ["small", "large", "small", "large"]
router = LogisticRegression().fit(features, labels)
def choose_model(token_count, needs_reasoning):
return router.predict([[token_count, needs_reasoning]])[0]A classifier is worth using when rules have become difficult to maintain and you have enough representative, labeled traffic. It adds training, validation, and drift-management work.
Evaluating a Routing Policy and Choosing a Threshold
Evaluate on a held-out sample that the router did not see during training. Measure quality, cost, latency, and escalation rate. If the policy uses a confidence threshold, test several thresholds rather than choosing one by intuition.
| Policy | Quality | Cost | Latency |
|---|---|---|---|
| Small model only | Lower | Low | Low |
| Large model only | Higher | High | High |
| Classifier router | Measured | Mixed | Mixed |
Choose the lowest-cost policy that satisfies your quality and latency targets. Check quality separately for important request types because an acceptable average can hide failures on coding, legal, or multilingual tasks.
Timeouts, Errors, and Fallbacks
A routing decision can fail, and a selected model can time out. Set a deadline and use a secondary model when the primary call fails.
def call_with_fallback(prompt, primary, secondary):
try:
return primary(prompt)
except TimeoutError:
return secondary(prompt)Monitoring a Routed System Over Time
Record the selected tier, latency, cost, errors, confidence, and sampled quality results. Watch for changes in traffic, model behavior, and feature distributions. Retrain or retune when these distributions drift.
Common Pitfalls
- Training on unrepresentative requests.
- Treating classifier confidence as answer correctness.
- Optimizing cost while ignoring severe failures.
- Forgetting that a cascade pays for both calls when escalation occurs.
- Routing sensitive requests without checking privacy and access requirements.
Exercise
When should you prefer a learned classifier over simple rules?
Show answer
Prefer it when you have representative labeled data and rules no longer capture request differences clearly enough.