Sub topic 2
Rule-Based Routing Between Model Sizes
Assume you know basic Python, can call a hosted language model through an API, and understand tokens and per-token pricing. This chapter focuses on deciding which model should handle a request.
Rule-based routing
A router is code that selects a model before generation begins. A rule-based router uses explicit signals, such as prompt length, task words, user tier, or required output format. It is easy to inspect, test, and change.
def route(prompt: str) -> str:
text = prompt.lower()
hard_markers = ("prove", "step by step", "refactor", "analyze")
if len(prompt) > 4000 or any(marker in text for marker in hard_markers):
return "large"
return "small"
for prompt in ("Summarize this note.", "Prove the theorem step by step."):
print(route(prompt))The example sends likely complex requests to the large model. Keep rules conservative for high-risk tasks. A false “small” decision can harm quality, while a false “large” decision mainly increases cost and latency. Review rules when your request mix changes.
Estimating confidence in the small model
A cascade uses the small model first, then escalates uncertain answers. Confidence is an estimate of the chance that an answer is acceptable. It might come from a calibrated classifier, a verifier, structured checks, or model-provided scores.
Do not treat a language model’s uncalibrated self-rating as a probability without testing it. A score of 0.8 is useful as a threshold only if answers near that score are actually correct about 80% of the time.
Cascades: try small first, escalate when needed
In a cascade, every request initially pays for the small model. Requests below the confidence threshold also pay for the large model. This differs from direct routing, which calls exactly one model.
def answer(prompt, call_small, call_large, threshold=0.8):
text, confidence = call_small(prompt)
if confidence >= threshold:
return text, "small"
return call_large(prompt), "large"A higher threshold escalates more requests. That can improve quality when the large model is better, but it raises cost and latency. A lower threshold saves resources but accepts more small-model errors. Evaluate several thresholds on labeled examples before choosing one.
Exercise
The small model is correct on 80% of requests, and the large model is correct on 95% of escalated requests. What should you measure before lowering the cascade threshold?
Show answer
Measure quality on the requests that would stop at the lower threshold, plus escalation rate, cost, and latency.