Sub topic 1
What Classification and Routing Mean, and When an LLM Fits
Prerequisites
This chapter assumes you have:
- Basic Python or similar scripting experience.
- Experience calling a chat or text-completion API from code.
- A working knowledge of JSON.
- Some familiarity with classification metrics such as accuracy, precision, and recall.
You do not need any machine learning training background. This chapter covers framing and decision-making. The later chapters build the prompt, the validation code, and the evaluation.
Classification and routing defined
Classification assigns a piece of text to one of a fixed set of labels. The input might be a support message, an email, a log line, or a product review. The output is a label such as billing or technical.
Routing is the action taken because of that label. A classifier alone changes nothing. A router uses the label to send the item to a queue, a team, a template, a downstream model, or a person.
The two parts have different failure modes, so keep them separate in your design:
- A classification error means the label is wrong for the text.
- A routing error means the label was right but the item went to the wrong place, for example because the label-to-handler table is out of date.
Throughout this tutorial the running example is a support inbox. Each incoming message gets one label from billing, technical, account, or other. A label then decides which team's queue receives the message.
The shape of the pipeline
Every system in this tutorial follows the same flow. The model only handles the middle step. Code you write handles everything around it.
Notice that there are two paths to human triage. Designing those exits early is the main habit this chapter tries to build. A router that can only answer with a confident label will route wrongly in the cases it understands least.
Kinds of classification task
Decide which kind of task you have before you write any prompt. The kind determines the output format and the routing logic.
| Task kind | What the output looks like | Example | Routing consequence |
|---|---|---|---|
| Single-label | Exactly one label | Ticket category | One destination per item |
| Multi-label | Zero or more labels | Topics mentioned in a review | Item may fan out to several handlers |
| Ordinal | One value on an ordered scale | Urgency: low, medium, high | Thresholds decide priority |
| Binary | Yes or no | Is this message spam? | Often a filter in front of other routing |
This tutorial focuses on single-label classification. It is the most common case, and the validation and evaluation techniques extend to the others. If your items often belong to two categories at once, such as a billing question that also reports a bug, you have a multi-label task. Forcing it into single-label gives the model an impossible job, and your accuracy numbers will look worse than the model deserves.
When an LLM fits
An LLM is one of several ways to classify text. The right choice depends on your data, your volume, and your tolerance for errors.
| Approach | Strengths | Weaknesses |
|---|---|---|
| Keyword or regex rules | Fast, free, fully predictable | Brittle on paraphrase, hard to maintain as rules grow |
| Trained classifier (for example logistic regression or a fine-tuned encoder) | Cheap per item, fast, consistent | Needs hundreds or thousands of labeled examples, retraining when labels change |
| LLM with a prompt | Works with zero or few labeled examples, handles varied phrasing, labels change by editing text | Per-call cost and latency, output can be inconsistent, needs validation |
An LLM tends to be a good fit when most of these hold:
- You have little labeled data. You can start with label definitions and a few examples instead of a training set.
- The text is varied and informal. Customers describe the same problem in many ways, and rules miss paraphrases.
- The labels change often. Adding a label means editing the prompt, not retraining a model.
- Volume is moderate. A few thousand to a few hundred thousand items a day is usually affordable. At very large volumes per-call cost becomes the deciding factor.
- Occasional errors are tolerable or catchable. A wrong label costs a re-route, not a safety incident, and a human path exists for uncertain items.
- Judgment is needed. The label depends on meaning, such as "is this customer asking about a refund or complaining about a bug?"
When an LLM does not fit
Pick something simpler in these cases:
- The rule is exact. If messages from
[email protected]always go to billing, write that as code. A deterministic check is cheaper, faster, and never wrong in a surprising way. - Latency budgets are tight. If you must decide in a few milliseconds, a network call to a model is usually too slow.
- You need the same answer every time. Model output can vary between calls, even with low sampling temperature. If auditors need identical results for identical inputs, a rule-based or trained model is easier to defend.
- Errors are costly and not recoverable. If a wrong label triggers an irreversible action, such as deleting an account, do not let the model decide alone.
- You already have lots of labeled data and high volume. A small trained classifier is likely cheaper and at least as accurate.
In practice many systems combine approaches: rules for the exact cases, an LLM for the rest. Chapter nine covers that in detail.
Writing a task frame before writing a prompt
Before touching a prompt, write down the task in a form you can check. The snippet below is a small structure that records the decisions this chapter describes and reports obvious gaps. It does not call a model.
from dataclasses import dataclass
@dataclass
class TaskFrame:
input_description: str
labels: list[str]
single_label: bool
fallback_label: str
handlers: dict[str, str] # label -> destination
wrong_route_cost: str # e.g. "re-route by hand" or "customer-visible delay"
def problems(self) -> list[str]:
found = []
if len(set(self.labels)) != len(self.labels):
found.append("duplicate labels")
if self.fallback_label not in self.labels:
found.append("fallback label is not in the label list")
unrouted = [
label for label in self.labels
if label != self.fallback_label and label not in self.handlers
]
if unrouted:
found.append(f"labels with no handler: {unrouted}")
if not self.wrong_route_cost.strip():
found.append("cost of a wrong route is not stated")
return found
frame = TaskFrame(
input_description="Customer support messages, 1 to 10 sentences, English",
labels=["billing", "technical", "account", "other"],
single_label=True,
fallback_label="other",
handlers={
"billing": "billing-team",
"technical": "support-engineering",
},
wrong_route_cost="Message waits until the receiving team re-routes it",
)
print(frame.problems())Running this prints ["labels with no handler: ['account']"]. The check caught a gap in the routing table before any model call was made. The fallback label needs no handler of its own here because the later routing code sends it to human triage.
Common framing errors
These mistakes show up before the first prompt is written, and they are expensive to fix later.
- Labels that describe the same thing from different angles.
bugandurgentoverlap because a message can be both. Labels should answer one question, such as "what is this about?" Chapter two covers how to design them. - No fallback. Without an
otherlabel the model must pick a wrong label for anything unexpected, and you will never see how often that happens. - Treating the model's answer as the decision. The model proposes a label. Your code validates it and decides whether to act on it.
- No definition of correct. If two humans disagree on a label, the model cannot be "right." Have two people label 50 messages. If they agree on far fewer than 90 percent, fix the label definitions before blaming the model.
- Skipping the cost of errors. A mislabeled newsletter and a mislabeled legal threat are not equal mistakes. State which errors matter most, because that guides your confidence threshold and your evaluation.
- Putting routing logic inside the prompt. Asking the model to "choose the right team" mixes two jobs. Ask it for a label and keep the label-to-team table in code, where you can change it without re-testing the prompt.
What the rest of the tutorial builds
The chapters that follow turn this frame into a working router. You will design the label set, write a prompt that fences the input, ask for JSON, and validate it with retries and a safe default. Then you add confidence thresholds and routing, measure accuracy and confusion on a labeled set, read the errors, and handle cost, injection, and monitoring.
Exercise
A team receives 200 messages a day. About 30 percent come from one automated billing system and always contain the phrase "INVOICE-AUTO". The rest are free-text messages from customers about billing, bugs, and account problems. The team has no labeled data. Describe how you would split the work between rules and an LLM, and name two exits to human review you would add.
Show answer
Use a rule for the automated messages: if the text contains "INVOICE-AUTO", route to the billing queue without calling the model. This is exact, free, and instant. Send the remaining free-text messages to the LLM, since they vary in phrasing and the team has no labeled data to train a model. Add one exit to human triage for output that fails validation after the retries are used up, and another for results whose confidence is below the threshold. An other label routed to triage is a reasonable third exit.
Exercise
Your single-label classifier keeps scoring poorly on messages like "I was charged twice and now the app crashes when I open my invoice." What does this suggest about the task framing, and what are two ways to respond?
Show answer
The messages belong to more than one category, so the task may really be multi-label, or the labels overlap. One response is to switch to a multi-label output and route the item to both handlers. Another is to add a rule in the label definitions about which label wins when two apply, for example "choose the problem the customer asks to have solved first," and then check agreement between human labelers on those cases.