Sub topic 8
Routing items to handlers
This chapter assumes you have read the earlier chapters of this tutorial. You should have a label set with an other fallback, a prompt that asks for JSON, and a classify function that validates the reply and returns a (label, confidence) pair. You should also be comfortable with Python dictionaries and dataclasses.
What routing adds to classification
Classification answers "what is this?" Routing answers "who or what handles it?" The router takes the validated label and confidence from the classifier and chooses a destination. A destination might be a team queue, a function, an API endpoint, or a human reviewer.
Keep the two steps separate. The classifier describes the item, and the router decides what to do about it. This lets you change the destinations without touching the prompt. For example, you can split billing into two queues, or send everything to humans during an outage. You can also test the routing logic without calling a model.
The routing table
The simplest router is a dictionary from label to destination. The routing function from the earlier code looks like this:
QUEUES = {
"billing": "billing-team",
"technical": "support-engineering",
"account": "account-services",
}
def route(text, call_llm, threshold=0.7):
label, confidence = classify(text, call_llm)
if confidence < threshold:
return "human-triage"
return QUEUES.get(label, "human-triage")QUEUES deliberately has no entry for other. Two separate guards send an item to human-triage:
- The confidence check. If the classifier is unsure, a person decides.
- The lookup default.
QUEUES.get(label, "human-triage")returns the triage queue for any label that has no destination. That includesotherand any label you add toLABELSbut forget to add toQUEUES.
The second guard matters during maintenance. If someone adds a label and forgets the queue, items go to a person instead of raising a KeyError or disappearing.
The decision flow
Every path ends at a real destination. A router with an unhandled case silently drops items, and nobody notices until a customer complains.
Returning a reason, not just a queue
route returns only a queue name. In production you also need to know why an item went where it did. When a queue owner says "we keep getting items that don't belong to us," you need to tell low-confidence escalations apart from unmapped labels.
Separating the decision into a pure function makes this easy. It takes a label and confidence and returns a queue and a reason. It never calls a model, so you can run it as shown:
from dataclasses import dataclass
QUEUES = {
"billing": "billing-team",
"technical": "support-engineering",
"account": "account-services",
}
@dataclass(frozen=True)
class Decision:
queue: str
reason: str
def decide(label, confidence, threshold=0.7):
if confidence < threshold:
return Decision("human-triage", "low_confidence")
queue = QUEUES.get(label)
if queue is None:
return Decision("human-triage", "no_queue_for_label")
return Decision(queue, "routed")
cases = [("billing", 0.92), ("billing", 0.55), ("other", 0.95), ("shipping", 0.9)]
for label, confidence in cases:
print(label, confidence, decide(label, confidence))The output is:
billing 0.92 Decision(queue='billing-team', reason='routed')
billing 0.55 Decision(queue='human-triage', reason='low_confidence')
other 0.95 Decision(queue='human-triage', reason='no_queue_for_label')
shipping 0.9 Decision(queue='human-triage', reason='no_queue_for_label')Store the reason with the item, along with the label and confidence. The monitoring chapter uses these fields to track how often each path is taken.
To combine this with the classifier, call classify first and pass its result to decide. This is the same flow as route, with the reason preserved.
Choosing the threshold
The threshold is a trade-off between two costs:
- A high threshold sends more items to humans. Fewer items are misrouted, but triage staff carry more work.
- A low threshold automates more items. Humans see less, but more items reach the wrong team.
The value 0.7 in the example is a starting point, not a recommendation. Models report their own confidence in text, and that number is not a calibrated probability. A reply of 0.9 does not mean the label is right 90% of the time. Pick the threshold by measuring on labeled examples. For each candidate threshold, check what share of items would be automated and how accurate those automated items are. The evaluation chapter shows how to collect the data for this.
A single global threshold is often too coarse, because mistakes cost different amounts. Sending a refund request to the technical team is an annoyance. Sending a security report to the billing team could be serious. A per-label threshold handles this:
THRESHOLDS = {"billing": 0.8, "technical": 0.7, "account": 0.9}
DEFAULT_THRESHOLD = 0.9
def decide_per_label(label, confidence):
queue = QUEUES.get(label)
if queue is None:
return "human-triage"
if confidence < THRESHOLDS.get(label, DEFAULT_THRESHOLD):
return "human-triage"
return queueLabels missing from THRESHOLDS get a strict default. A new label therefore starts out cautious.
Dispatching to handlers in code
Sometimes the destination is a function rather than a queue name, for example one that creates a ticket, calls an API, or drafts a reply. The same dictionary pattern works, with callables as values:
def handle_billing(text):
return f"billing ticket created: {text[:30]}"
def handle_technical(text):
return f"engineering ticket created: {text[:30]}"
def handle_triage(text):
return f"queued for human review: {text[:30]}"
HANDLERS = {
"billing": handle_billing,
"technical": handle_technical,
}
def dispatch(text, label, confidence, threshold=0.7):
handler = HANDLERS.get(label, handle_triage)
if confidence < threshold:
handler = handle_triage
return handler(text)
print(dispatch("I was charged twice for May", "billing", 0.95))
print(dispatch("The export button does nothing", "technical", 0.4))
print(dispatch("Do you sponsor events?", "other", 0.9))The triage handler is both the fallback for unknown labels and the target for low confidence, so no path lacks a handler.
Handlers that change state, such as creating tickets or sending emails, need extra care:
- Make them idempotent. Retries and reprocessing can deliver the same item twice. Use a stable item ID so a second delivery does not create a duplicate ticket.
- Classify once, and store the result. If a downstream failure causes a retry, reuse the stored label. Calling the model again may return a different label for the same text.
- Catch handler errors separately from classifier errors. A failing billing API is not a classification failure. Send the item to a retry or dead-letter queue and keep its label.
Edge cases
- Items that fit two labels. A message such as "I was charged after my login was locked" belongs to both
billingandaccount. A single-label router must pick one. If this happens often, the labels overlap, and you should fix the definitions. If it is rare, add a priority rule or let triage handle it. Multi-label routing is possible, but then the item has several destinations and you must decide who owns the reply. - Empty or very short input. A message like "hi" or an empty body gives the model nothing to work with. A guard before the model call saves a request and avoids a confident wrong answer. The guard should send such items to triage.
- Queue outages. If a destination queue is down, do not rewrite the label. Keep the classification and let the delivery layer retry.
- Label drift. If you rename a label in the prompt but not in
QUEUES, every item falls through to triage. This is safe, but the automation rate drops to zero without any error. A startup check that every label inLABELSis either inQUEUESor intentionally unrouted catches this. A test that asserts the check is cheap.
UNROUTED = {"other"}
def check_routing_config(labels, queues, unrouted=UNROUTED):
missing = set(labels) - set(queues) - set(unrouted)
extra = set(queues) - set(labels)
if missing or extra:
raise ValueError(f"missing={sorted(missing)} extra={sorted(extra)}")
check_routing_config(["billing", "technical", "account", "other"], QUEUES)
print("routing config ok")Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Routing on the raw model reply | Malformed output crashes the router or misroutes items | Route only on output that `classify` has validated |
| No default destination | Unknown labels raise errors or drop items | Use `.get(label, "human-triage")` |
| One threshold for every label | Costly mistakes get the same bar as cheap ones | Use per-label thresholds |
| Not storing the reason | You cannot tell why items reached triage | Store label, confidence, and reason |
| Re-classifying on retry | The same item can end up in different queues | Store the first result and reuse it |
Summary
Routing turns a validated label and confidence into a destination. Keep it separate from classification and make it a lookup with a default. Send low-confidence items and labels without a queue to a human. Record the reason for every decision. Tune thresholds from data, and keep them stricter where mistakes are expensive.
Exercise
A new label shipping is added to LABELS and to the prompt, but nobody adds it to QUEUES. Using the route function above, what happens to a message the model labels shipping with confidence 0.95, and why is it useful to run check_routing_config at startup?
Show answer
The confidence is above the 0.7 threshold, so the first check passes. QUEUES.get("shipping", "human-triage") finds no entry and returns "human-triage". The item is not lost, but every shipping message goes to humans and automation silently drops for that label. check_routing_config would raise a ValueError at startup that lists "shipping" as missing, so the gap is found before any items are processed.
Exercise
In decide, a message gets label billing with confidence 0.65 and the default threshold of 0.7. What Decision is returned, and which two things would you change to automate more billing items safely?
Show answer
It returns Decision(queue="human-triage", reason="low_confidence"). To automate more safely, lower the billing threshold only after measuring on labeled examples that billing items in the 0.6 to 0.7 range are still mostly correct. Also improve the billing definition or add few-shot examples so the model's confidence on clear billing messages rises without guessing more.