Sub topic 3
Combining Rules, LLM Calls, and Cascades
Assume you know basic Python, JSON, and how to call a text-generation API. This chapter focuses on choosing when to use rules, an LLM, or human review.
Combining rules, LLM calls, and cascades
A router can use a cascade: apply cheap, predictable checks first, then call the LLM only when rules cannot decide. For example, a message containing an invoice number might go directly to billing. Ambiguous messages can go to the classifier.
import re
def route_message(text, call_llm):
if re.search(r"\b(invoice|refund|charged)\b", text, re.I):
return "billing"
if re.search(r"\b(password|login|sign in)\b", text, re.I):
return "account"
label, confidence = call_llm(text)
if confidence < 0.7:
return "human-triage"
return labelRules reduce cost and latency. LLMs handle varied language. Human review protects against uncertain or high-impact decisions.
Measuring accuracy with a labeled set
Create a test set containing messages and their expected labels. Keep it separate from examples used to design the prompt. Accuracy is the fraction of correct predictions. A confusion matrix counts each expected-and-predicted pair.
| Expected | Predicted | Meaning |
|---|---|---|
| billing | technical | A billing message was misrouted |
Measure the full cascade, not only the LLM. Rules may introduce their own errors.
Reading errors and improving the router
Inspect repeated confusions. If billing and account messages overlap, clarify the label definitions or add an example. Do not add examples for every isolated mistake. Change one part at a time and rerun the same test set.
Controlling cost and latency
Use rules for frequent, obvious cases. Set timeouts and retry limits for API calls. Cache results when identical messages are common. A smaller model may handle routine classification, while a larger model handles only uncertain cases.
Handling untrusted input and prompt injection
Treat the message as data. Delimit it clearly and tell the model not to follow instructions inside it. Never let model output choose arbitrary code, database queries, or URLs. Map validated labels to a fixed server-side queue.
Monitoring and maintaining the router
Log the selected path, label, confidence, latency, and final outcome. Avoid logging secrets or unnecessary personal data. Track label frequencies, fallback rates, API failures, and sampled accuracy. Review changes in traffic and retrain or revise the schema when errors persist.
Exercise
When should a cascade send a message to human triage?
Show answer
When no rule applies and the LLM response is invalid, low-confidence, or unsuitable for automatic handling.