Sub topic 11
Reading errors and improving the prompt and labels
This chapter assumes you have the classify and evaluate functions from the earlier chapters. It also assumes you can read a confusion matrix and that you know precision and recall. The goal is to turn a list of wrong predictions into specific changes to the labels, definitions, and examples.
Start from the confusion counts, not from single failures
The evaluate function returns overall accuracy and a Counter of (expected, predicted) pairs. Accuracy tells you whether you have a problem. The off-diagonal pairs, where expected and predicted differ, tell you where it is.
Suppose an evaluation run on 63 labeled messages produced these counts:
from collections import Counter
LABELS = ["billing", "technical", "account", "other"]
confusion = Counter({
("billing", "billing"): 18, ("billing", "account"): 1, ("billing", "other"): 1,
("technical", "technical"): 17, ("technical", "account"): 4,
("account", "account"): 12, ("account", "technical"): 3,
("other", "other"): 5, ("other", "billing"): 2,
})
def top_confusions(confusion, n=3):
off_diagonal = [(pair, c) for pair, c in confusion.items() if pair[0] != pair[1]]
return sorted(off_diagonal, key=lambda item: item[1], reverse=True)[:n]
def label_metrics(confusion, labels):
metrics = {}
for label in labels:
true_pos = confusion[(label, label)]
actual = sum(c for (exp, _), c in confusion.items() if exp == label)
predicted = sum(c for (_, pred), c in confusion.items() if pred == label)
precision = true_pos / predicted if predicted else 0.0
recall = true_pos / actual if actual else 0.0
metrics[label] = (round(precision, 2), round(recall, 2))
return metrics
print(top_confusions(confusion))
print(label_metrics(confusion, LABELS))Accuracy here is 52/63, about 0.83. The three most common errors are technical predicted as account (4), account predicted as technical (3), and other predicted as billing (2).
The per-label numbers add detail. account has precision 0.71 (12 of the 17 items predicted as account were correct), so it is absorbing messages that belong elsewhere. other has recall 0.71, so some items that should reach the fallback are being forced into a real label.
Read the metrics as follows:
- Low precision for a label means the model over-assigns it. Its definition is probably too broad, or a neighboring label is too narrow.
- Low recall for a label means the model under-assigns it. Its definition may be missing a common phrasing or case.
- A symmetric pair of errors, such as technical↔account, usually means the boundary between those two labels is unclear.
Look at the actual messages
Counts show where to look. They don't explain why the model erred. For each of the top confusion pairs, read 10 to 20 of the failed messages. That means all of them when a pair has fewer. To make this easy, keep the failures during evaluation. This version reuses classify from the earlier chapter and also returns the failed items:
from collections import Counter
def evaluate_with_failures(examples, call_llm):
if not examples:
raise ValueError("examples must not be empty")
confusion = Counter()
failures = []
for text, expected in examples:
predicted, confidence = classify(text, call_llm)
confusion[(expected, predicted)] += 1
if predicted != expected:
failures.append(
{"text": text, "expected": expected,
"predicted": predicted, "confidence": confidence}
)
accuracy = (len(examples) - len(failures)) / len(examples)
return accuracy, confusion, failures
def failures_for(failures, expected, predicted):
return [f for f in failures if f["expected"] == expected and f["predicted"] == predicted]Calling failures_for(failures, "technical", "account") gives you the messages behind the largest confusion. Read them with one question in mind: why would a reasonable person, or the model, choose the predicted label?
Sort each error into a cause
Different causes need different fixes, so tag every failure you read before you change anything.
| Cause | What you see | Typical fix |
|---|---|---|
| Overlapping labels | The message fits two definitions, such as "I can't log in after my payment failed" | Add a tie-break rule, or merge or split labels |
| Vague definition | The model's choice is defensible under the wording you gave it | Rewrite the definition with concrete inclusions and exclusions |
| Missing example | A recurring phrasing or pattern is always missed | Add a few-shot example for it |
| Wrong gold label | The model is right and your expected label is wrong | Correct the dataset |
| Out-of-scope input | Spam, an empty message, a non-English message, or a thank-you note | Make sure the fallback label covers it, or handle it before the model call |
| Format failure | The reply was not valid JSON and fell back to `other` | Fix the output instructions or the parsing, not the labels |
Wrong gold labels are more common than people expect. In a first review pass, it is normal for several percent of disagreements to be dataset mistakes. If you tune the prompt to match a wrong label, you make the classifier worse.
Format failures also hide in the numbers. Our classify returns ("other", 0.0) when parsing fails twice. Those items show up as errors into other, and they look like a labeling problem when they are a plumbing problem. Check the confidence of failed items: a value of exactly 0.0 together with other suggests a parse failure.
Apply one change at a time
The improvement loop is short and should stay short.
Change one thing per pass. If you rewrite two definitions and add three examples at once, you can't tell which edit helped. Keep each prompt version in version control with its evaluation numbers next to it.
Fixing the label definitions
Take the technical↔account confusion. Suppose the failed messages look like "I get a 403 error when I open the admin page" and "Why can't my teammate see the dashboard?" Both involve permissions and errors, so both labels are plausible. The original definitions were:
- technical: Bugs, errors, outages, and how-to questions about the product
- account: Login, password, profile, and permission changes
The fix is to state the boundary:
LABELS = {
"billing": "Charges, invoices, refunds, and payment failures",
"technical": (
"Bugs, errors, outages, and how-to questions about the product. "
"Includes error messages even when they mention permissions or login."
),
"account": (
"Requests to change or recover account data: reset a password, "
"update a profile, grant or remove a user's permissions. "
"Not for error messages."
),
"other": "Anything that does not clearly fit the labels above",
}The new account definition describes requests to change something. The technical definition says that error reports belong to it. Together they give a rule that two people could apply the same way.
If a tie-break rule still leaves many cases unresolved, the labels may be wrong for your data. Merge two labels the model and your own reviewers keep mixing up when the handlers for both labels are the same team anyway. Split a label if one queue receives items that need very different handling.
Fixing the examples
When the failures share a pattern the definitions can't easily describe, add few-shot examples. Choose examples from the failures, with the correct label, and keep them short:
FEW_SHOT = [
("I get a 403 error on the admin page", "technical"),
("Please give my colleague access to the billing settings", "account"),
("Thanks, that fixed it!", "other"),
]
def examples_block(examples):
lines = []
for text, label in examples:
lines.append(f'Message: "{text}"\nLabel: {label}')
return "Examples:\n" + "\n\n".join(lines) + "\n\n"Insert examples_block(FEW_SHOT) into the prompt before the <message> tags. Pick examples that show a boundary, such as two near-identical messages with different labels, instead of repeating easy cases. Cover each label at least once so the model isn't pushed toward the labels that appear in the examples most.
The third example matters for the fallback. Courtesy messages, spam, and empty inputs are a steady source of misroutes. Showing them with the label other is often enough.
Guard against overfitting
Watch for regressions too. A change that fixes four technical→account errors can break three billing messages. Compare the full confusion counts before and after, not just overall accuracy. Small labeled sets are noisy: on 63 messages, one item moves accuracy by about 1.6 points. Treat differences of one or two items as unproven. If the model is sampled with a nonzero temperature, run the evaluation more than once before you trust a small gain.
Know when to stop
Some errors won't go away. If two human reviewers disagree on the same messages, the model can't do better than they do. Measure this by having a second person label a sample, then compare their labels with yours. That agreement rate is a practical ceiling for the classifier.
Remaining ambiguous cases are better handled in the routing layer than in the prompt. Low-confidence results go to human-triage, as in the earlier routing chapter. Check whether the failures you can't fix have lower confidence than the correct predictions. If they do, a threshold will catch many of them. If the model is confidently wrong, confidence won't help, and you will need better definitions or examples.
Record each iteration briefly: the change you made, the cause you were targeting, and accuracy and per-label metrics before and after. That log makes later changes safer, and it becomes the baseline for the monitoring chapter.
Exercise
An evaluation shows that 6 of 20 billing messages were predicted as account. You read them and find that 4 are "my card was declined and now I can't log in", and 2 are clearly billing questions the model got wrong. Name two changes you could make, and say how you would check that they worked without fooling yourself.
Show answer
First, fix the boundary for the mixed messages. Either add a tie-break rule such as "if a payment problem is the cause, choose billing", or add one or two few-shot examples of this pattern labeled billing. If your team decides these should go to account services instead, correct the gold labels. Second, for the two plain misclassifications, check whether a definition is too vague, or whether a similar example is missing. Make one change at a time and re-run the evaluation. Compare the full confusion counts, not only accuracy, to check that no other pair got worse. Tune on a development set and confirm the result on a held-out test set that you didn't use for choosing examples.