Sub topic 9
Combining rules, LLM calls, and cascades
This chapter covers three ways to decide where a message goes: rules, an LLM call, or a mix of both. It assumes you have read the earlier chapters and can call a chat API from Python. You should also know the classify and route functions from the previous chapters, and be comfortable with accuracy and confusion counts.
Why one method is rarely enough
An LLM can read almost any message, but each call costs money and takes time. Plain rules, such as keyword checks, regular expressions, or lookups on metadata, are fast, free, and predictable. They fail on wording they did not anticipate.
Most production routers combine the two. The question is how to arrange them. There are three common patterns:
- Rules only. Every decision comes from code you wrote.
- LLM only. Every decision comes from a model call.
- Hybrid. Rules handle the cases they can decide safely, and the LLM handles the rest.
A cascade is a hybrid with an order. Cheap steps run first, and each step either decides or passes the item to the next step. The last step is usually a human queue.
Comparing the three approaches
| Approach | Strengths | Weaknesses | Fits when |
|---|---|---|---|
| Rule-based | Fast, free, deterministic, easy to audit | Brittle on new wording, grows hard to maintain | Inputs are structured or use fixed phrases |
| LLM | Handles varied wording, needs no keyword lists | Costs per call, adds latency, can be inconsistent | Inputs are free text with many phrasings |
| Hybrid cascade | Cheap on easy items, flexible on hard ones | More parts to test and monitor | Traffic has a large share of easy, predictable items |
Pick by looking at your traffic. If 30% of messages come from an automated system with a fixed subject line, a rule can handle that 30% at no cost. The LLM then sees only the messages that need it.
Rules that are safe to trust
A rule is worth adding only if you can show it is almost never wrong. Good candidates are:
- Metadata. The message arrived through a "billing" form, or from a known payment-processor address.
- Exact or near-exact phrases. An automated notice such as "Your payment failed" followed by a fixed template.
- Format checks. An empty message, or one containing only an order number.
Bad candidates are single common words. A rule such as "if the text contains refund, route to billing" will misroute "I do not want a refund, I want the app to stop crashing."
Keep rules narrow and conservative. When a rule does not match, it should say nothing. It should never guess.
import re
AUTOMATED_PAYMENT_FAILURE = re.compile(
r"^Subject:\s*Payment failed for invoice \d+", re.IGNORECASE
)
def rule_label(text, metadata):
"""Return (label, reason) when a rule is certain, otherwise None."""
if not text.strip():
return "other", "empty message"
if metadata.get("source") == "billing-form":
return "billing", "submitted through billing form"
if AUTOMATED_PAYMENT_FAILURE.match(text):
return "billing", "automated payment-failure notice"
return NoneThe function returns a reason along with the label. Logging the reason lets you see later which rule made each decision, which matters when you audit mistakes.
A two-stage cascade
The simplest cascade has two stages: rules first, then the LLM. The code below reuses classify and QUEUES from earlier chapters.
def cascade_route(text, metadata, call_llm, threshold=0.7):
"""Return (queue, source) where source records which stage decided."""
hit = rule_label(text, metadata)
if hit is not None:
label, _reason = hit
return QUEUES.get(label, "human-triage"), "rule"
label, confidence = classify(text, call_llm)
if confidence < threshold:
return "human-triage", "llm-low-confidence"
return QUEUES.get(label, "human-triage"), "llm"Returning the source is deliberate. It lets you measure each stage separately: how many items each one handles, and how accurate each one is.
Rules as overrides after the LLM
Rules do not only run before the model. Sometimes you want a rule to run after it, as a safety check or policy override. Examples:
- A message mentions legal action or a regulator. Send it to a specific team regardless of the label.
- The customer is on a premium plan. Send it to a priority queue whatever the label is.
- The LLM says "billing" but the metadata says the message came from the account-settings page. Flag the disagreement for review.
A pre-filter saves cost. A post-filter enforces policy. You can use both in the same router.
LEGAL_TERMS = re.compile(r"\b(lawyer|attorney|lawsuit|regulator)\b", re.IGNORECASE)
def route_with_overrides(text, metadata, call_llm, threshold=0.7):
queue, source = cascade_route(text, metadata, call_llm, threshold)
if LEGAL_TERMS.search(text):
return "legal-review", "override"
if metadata.get("plan") == "premium" and queue != "human-triage":
return f"priority-{queue}", "override"
return queue, sourceNote the order of checks. The legal override comes first because it must win over everything else. Decide the precedence of overrides on purpose, and write it down.
Cascading across models
A cascade can also have several LLM stages. A small, cheap model runs first. If its confidence is high, you accept the answer. If not, you escalate to a larger, slower model.
def two_model_classify(text, call_small, call_large, accept=0.9):
label, confidence = classify(text, call_small)
if confidence >= accept:
return label, confidence, "small"
label, confidence = classify(text, call_large)
return label, confidence, "large"This pattern depends on the small model's confidence being meaningful. Self-reported confidence from a model is a rough signal, not a calibrated probability. Before trusting it, check on a labeled set: among items where the small model reports 0.9 or higher, how often is it actually right? If the answer is 75%, the accept threshold is too low.
Choosing thresholds from data
Do not guess the thresholds. Use your labeled examples from the evaluation chapter and sweep values. For each candidate threshold, measure two things:
- Coverage. The share of items the cheap stage decides on its own.
- Accuracy on that share. How often those decisions are right.
Raising the threshold lowers coverage and raises accuracy. The cost of a wrong automatic decision against the cost of a human review sets the best point. If a misrouted billing message costs a day of delay and a human review costs two minutes, a high threshold is justified.
def sweep_thresholds(scored, thresholds):
"""scored: list of (confidence, was_correct) pairs from a labeled set."""
if not scored:
raise ValueError("scored must not be empty")
rows = []
for t in thresholds:
accepted = [ok for conf, ok in scored if conf >= t]
coverage = len(accepted) / len(scored)
accuracy = sum(accepted) / len(accepted) if accepted else None
rows.append((t, coverage, accuracy))
return rows
scored = [(0.95, True), (0.9, True), (0.8, False), (0.75, True), (0.5, False)]
for t, coverage, accuracy in sweep_thresholds(scored, [0.5, 0.7, 0.9]):
print(t, round(coverage, 2), accuracy)Running this prints coverage and accuracy for each threshold. With the sample data, a threshold of 0.9 covers 40% of items and is right every time, while 0.5 covers everything and is right 60% of the time.
Failure modes in hybrid systems
Hybrid routers add failure modes that a single method does not have.
- Silent rule drift. A rule that was accurate when written becomes wrong after a product change, such as a renamed form. Because rules run first, they hide the problem from the LLM. Track rule accuracy through periodic audits of a random sample of rule decisions.
- Rule and LLM disagreement. If you run both on a sample, differences point to a bad rule or a label gap. Disagreement is a useful signal even when you route by the rule.
- Escalation overload. If the low-confidence path grows, the human queue backs up. Watch the share of items reaching each stage.
- Cost surprises. A cascade that escalates too often calls both models for most items, which costs more than using the large model alone. Measure the escalation rate.
- Order bugs. An override placed in the wrong position can swallow items. Test the precedence with explicit examples.
Testing the cascade
Test each stage alone and then the whole cascade. For rules, you can write ordinary unit tests with a fake call_llm that fails the test if it is called, which proves the rule short-circuits the model.
def test_rule_skips_llm():
def forbidden(_prompt):
raise AssertionError("LLM should not be called")
queue, source = cascade_route(
"Subject: Payment failed for invoice 4412", {}, forbidden
)
assert (queue, source) == ("billing-team", "rule")
def test_low_confidence_goes_to_triage():
def fake_llm(_prompt):
return '{"label": "technical", "confidence": 0.4}'
queue, source = cascade_route("The thing is weird", {}, fake_llm)
assert (queue, source) == ("human-triage", "llm-low-confidence")
test_rule_skips_llm()
test_low_confidence_goes_to_triage()
print("ok")For the whole cascade, run the labeled set through it and compare accuracy, cost, and latency with the LLM-only version. A cascade is worth keeping only if it keeps accuracy close to the baseline while cutting cost or latency.
Choosing a design
Use these questions in order:
- Do some inputs carry structure, such as a source field or fixed template? If yes, add narrow rules for them.
- Is there a policy that must hold regardless of the model, such as legal escalation? If yes, add an override after the LLM.
- Is the LLM bill or latency a problem? If yes, test a cheap-model-first cascade and sweep the threshold.
- Can you audit each stage? If not, add the
sourcefield and sampling before you add more stages.
Each added stage must justify itself with measured results. A simple router that you understand is better than a complex one you cannot debug.
Exercise
A cascade runs a rule first, then a small model, then a large model. On your labeled set the small model reports confidence of at least 0.9 on 60% of items, but is correct on only 80% of those. What does this tell you about the accept threshold, and what would you change?
Show answer
The reported confidence is not calibrated, because items at 0.9 or higher should be right far more often than 80% of the time if the threshold is to be trusted. Raise the accept threshold (for example, sweep 0.95 and above) and measure coverage and accuracy again, accepting that fewer items will be decided by the small model. Also consider fixing the cause, such as improving the prompt or label definitions, and check whether the errors cluster on particular labels in the confusion counts.
Exercise
Your rule "if the text contains refund, route to billing" decides 15% of traffic. A reviewer samples 100 of those items and finds 12 were not billing issues. Give two ways to fix this and one way to keep it from happening again.
Show answer
Fix 1: narrow the rule, for example require a phrase like "request a refund" or a matching metadata field, so it only fires in clear cases. Fix 2: remove the rule and let the LLM decide, then compare accuracy and cost on the labeled set. To prevent a repeat, sample and label rule-routed items on a regular schedule and log which rule made each decision, so a falling rule accuracy is noticed early.