Sub topic 7
Using confidence and abstaining when unsure
This chapter assumes you can call a chat API from Python, parse JSON, and read accuracy numbers. It also assumes you have the classify and route functions from the earlier chapters: classify returns a (label, confidence) pair, and route turns that pair into a queue name.
A classifier that always answers will sometimes answer wrongly. A router that always acts on the answer will then send some messages to the wrong team. Abstaining means the system declines to decide and passes the item to a person or a slower process. This chapter covers where confidence values come from, how to set the threshold, and what can go wrong.
Why abstaining is worth designing
Wrong routes and abstentions have different costs. Suppose a billing complaint lands in the technical queue. It waits, someone reads it, someone forwards it, and the customer waits longer. An abstention sends the item to human triage, where one person reads it once and routes it correctly. Triage costs a little time per item. A wrong route can cost more, and nobody notices it unless the receiving team complains.
Abstention trades coverage for accuracy on the answered items.
- Coverage is the fraction of items the system decides on its own.
- Accuracy on answered items is the fraction of those automatic decisions that are correct.
Raising the threshold lowers coverage and usually raises that accuracy. Your job is to pick the point on that curve that fits your staffing and your tolerance for errors.
Where confidence comes from
The prompt from earlier chapters asks the model for {"label": ..., "confidence": ...}. That is one of three common sources.
| Source | How it works | Strength | Weakness |
|---|---|---|---|
| Self-reported number | The model writes a number in its JSON | Works with any API and costs no extra calls | Poorly calibrated. Values cluster near 0.9 and 0.95 |
| Token log probabilities | Read the probability of the label token, if the API exposes it | Closer to the model's actual uncertainty | Not every API offers it, and it is harder with JSON output |
| Agreement across samples | Ask several times with some randomness and measure how often the answers match | Catches unstable decisions | Multiplies cost and latency |
The self-reported number is the simplest and is what the code here uses. Treat it as a ranking signal, not as a probability. A reported 0.9 does not mean the model is right 90% of the time. It means that items scored 0.9 are probably more reliable than items scored 0.6. Whether that holds for your data is something you must measure.
Three ways an item ends up abstaining
The pipeline already has three abstention paths. It helps to see them as one mechanism.
- Low confidence. The model returns a label but a score below the threshold.
- The
otherlabel. The model decided nothing fits.QUEUES.get(label, "human-triage")sends it to people, even with high confidence. - Validation failure. The reply was not valid JSON, or the label was not in the label set, even after retries.
classifyreturns("other", 0.0), which fails the threshold check.
The zero confidence in the third case is deliberate. A failure should never look like a confident answer, and a confidence of 0.0 makes that impossible.
The routing code
Here is the router again. All the abstention logic is in two lines.
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")Two details are worth noticing.
- The comparison is
<, so a confidence exactly equal to the threshold is accepted. Choose the direction on purpose and keep it the same in your evaluation code. otheris not inQUEUES, so it always falls through to triage. You do not need a special case for it.
Choosing the threshold from data
Do not choose 0.7 because it feels reasonable. Run the classifier over a labeled set, record the confidence for each item, and compute coverage and accuracy at several thresholds.
def threshold_sweep(results, thresholds):
"""results: list of (expected, predicted, confidence) tuples."""
if not results:
raise ValueError("results must not be empty")
rows = []
for t in thresholds:
answered = [(e, p) for e, p, c in results if c >= t]
coverage = len(answered) / len(results)
if answered:
accuracy = sum(e == p for e, p in answered) / len(answered)
else:
accuracy = None
rows.append((t, coverage, accuracy))
return rows
results = [
("billing", "billing", 0.95),
("billing", "billing", 0.90),
("technical", "technical", 0.92),
("technical", "technical", 0.85),
("account", "account", 0.80),
("account", "technical", 0.75),
("technical", "billing", 0.72),
("billing", "other", 0.50),
("account", "account", 0.55),
("technical", "other", 0.30),
]
for t, coverage, accuracy in threshold_sweep(results, [0.5, 0.7, 0.9]):
acc = "n/a" if accuracy is None else f"{accuracy:.2f}"
print(f"{t:.1f} coverage={coverage:.2f} accuracy={acc}")Running it prints:
0.5 coverage=0.90 accuracy=0.67
0.7 coverage=0.70 accuracy=0.71
0.9 coverage=0.30 accuracy=1.00At 0.9 the system is right on every item it answers, but it answers only three in ten. At 0.5 it answers nine in ten and is wrong on one in three of those. The None case matters: at a very high threshold nothing may be answered, and dividing by zero would crash the sweep.
This evaluation only means something if the labeled set resembles real traffic. Ten items are far too few. Use enough items that each label has dozens of examples, and keep a separate set from the examples in your prompt.
Check that confidence carries information
Before you trust any threshold, group results by confidence band and compute accuracy in each band. Accuracy should rise with confidence. A pattern like this is healthy:
| Confidence band | Items | Accuracy |
|---|---|---|
| 0.9 to 1.0 | 420 | 0.97 |
| 0.7 to 0.9 | 310 | 0.88 |
| 0.5 to 0.7 | 120 | 0.61 |
| Below 0.5 | 50 | 0.34 |
If every band has roughly the same accuracy, the model's number tells you nothing, and a threshold only moves items to humans at random. In that case switch to another source, such as agreement across samples, or rely on the other label and validation failures alone.
Setting the threshold by business constraint
Work backward from a constraint, not toward a number.
- Error budget. If misrouted tickets must stay under 5% of automatic decisions, pick the lowest threshold whose accuracy on answered items is at least 0.95.
- Human capacity. If triage can handle 20% of volume, pick the threshold where coverage is 0.80, then check the accuracy you get.
- Both at once. If the two constraints cannot be met together, you have a real finding. Improve the labels or prompt, add examples, or add staff. Moving the threshold will not fix it.
Per-label thresholds
One global threshold assumes every label has the same risk. Often it does not. Sending an account-permission request to the wrong team may be a security concern, while a misrouted how-to question is a mild annoyance. You can store a threshold per label:
THRESHOLDS = {"billing": 0.7, "technical": 0.6, "account": 0.85}
DEFAULT_THRESHOLD = 0.7
def route_by_label(text, call_llm):
label, confidence = classify(text, call_llm)
if confidence < THRESHOLDS.get(label, DEFAULT_THRESHOLD):
return "human-triage"
return QUEUES.get(label, "human-triage")Each extra threshold is another number you must tune and re-tune. With a small labeled set, per-label values overfit quickly. Start with one global threshold and split it only when the per-label sweeps clearly disagree.
Edge cases and failure modes
- Out-of-range values.
classifyalready rejects confidence outside 0 to 1. Without that check, a model that answers95(meaning percent) would pass every threshold. - Ties at the boundary. A model that only ever says 0.7, 0.8, or 0.9 makes thresholds jump in steps. The sweep will show large coverage changes between adjacent values.
- Prompt changes shift the scale. If you edit the prompt or switch model versions, the confidence distribution can move. Re-run the sweep every time. A threshold tuned for one version is not valid for the next.
- Triage overflow. If the threshold is too high, the human queue grows faster than people can clear it. Abstention does not fix a backlog. It moves the backlog.
- Learning from triage. Items that humans resolve are free labeled data. Save the final human label with the model's prediction and confidence, and use them in the next evaluation.
Exercise
Exercise
Using the sweep output above, your team requires at least 95% accuracy on automatically routed items. Which of the three thresholds meets that, what is the coverage, and what happens to the rest of the items?
Show answer
Only 0.9 qualifies, with accuracy 1.00. Coverage is 0.30, so 30% of items are routed automatically and the other 70% go to human triage. Thresholds 0.5 and 0.7 give accuracy of 0.67 and 0.71, which is below the requirement. Because only ten examples were used, the team should confirm the result on a much larger labeled set before relying on it.
Exercise
A confidence-band table shows 0.93 accuracy in the 0.9 to 1.0 band and 0.91 in the 0.5 to 0.7 band. What does this say about raising the threshold, and what would you try next?
Show answer
The bands have almost the same accuracy, so the confidence number does not separate good answers from bad ones. Raising the threshold would send many correct items to humans without removing many errors. Try a different signal, such as agreement across several samples, or tighten the label definitions and add examples for the confused labels.