Uncertainty, abstention and calibration
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Implement majority-vote self-consistency over scripted samples with a deterministic tie rule and an agreement signal.
- Implement an abstention gate with an inclusive threshold and predict its decisions at and around the boundary.
- Explain calibration, recognize overconfidence from a reliability table, and state why verbalized confidence needs structural checks.
Overview
#Where uncertainty comes from
An AI feature is uncertain in three distinguishable ways, and conflating them causes bad design:
- Sampling uncertainty: at nonzero temperature, the same prompt yields different outputs (lesson 3).
- Knowledge uncertainty: the answer is not in the model or in your retrieved sources (lesson 9).
- Ambiguity: the input itself supports multiple reasonable answers.
Each has a different remedy: sampling controls, retrieval with abstention, and clarification or scoped options. What none of them fixes is overconfidence, the tendency to present a guess with the tone of a fact. That is a product-level problem with product-level controls.
Abstention thresholds
When your pipeline produces a confidence-like signal (retrieval score, classifier score, agreement rate), you can gate the reply: answer only when the signal clears a threshold, otherwise abstain or escalate. The gate is deliberately boring code:
function abstainGate(confidence, threshold = 0.7) {
return confidence >= threshold ? "answer" : "abstain";
}
// abstainGate(0.65) -> "abstain"
// abstainGate(0.9) -> "answer"
// abstainGate(0.7) -> "answer" (the boundary is inclusive by rule)
Two design notes. First, the threshold is a product decision with a confusion cost on each side: too low and users receive unsupported answers, too high and the feature abstains constantly. Tune it against labeled cases, not vibes. Second, a retrieval similarity score is a weak confidence signal (lesson 8); treat thresholds on it as heuristics to evaluate, not as probabilities.
Self-consistency: agreement as a signal
For tasks with a discrete answer space, sample the same prompt several times and let the majority vote speak. Agreement rate is a cheap uncertainty signal: unanimous answers are more likely reliable than 3-to-2 splits.
function majorityVote(labels) {
const counts = {};
for (const label of labels) counts[label] = (counts[label] || 0) + 1;
let best = null;
let bestCount = -1;
for (const [label, count] of Object.entries(counts)) {
if (count > bestCount) { best = label; bestCount = count; }
}
return { label: best, agreement: bestCount / labels.length };
}
// majorityVote(["yes", "yes", "no", "yes", "no"])
// -> { label: "yes", agreement: 0.6 }
The tie rule is insertion order: the first label to reach the maximum count wins, which keeps the function deterministic. In the example, agreement 0.6 is below a 0.7 threshold, so a gated pipeline abstains despite the majority label. That is the lesson in one line: a majority of uncertain samples is still uncertain.
Calibration: does 90 percent mean 90 percent?
A confidence number is calibrated when it matches observed frequency: among the cases where the system says 90 percent, it should be right about 90 percent of the time. Measuring this is mechanical: bucket outputs by stated confidence, compute accuracy per bucket, and compare. A model that says 90 percent and is right 60 percent of the time is overconfident; its numbers need rescaling (recalibration) before anything downstream trusts them.
Expect verbalized confidence from models to be poorly calibrated out of the box, and expect it to degrade on out-of-distribution inputs, precisely where you need it most. The defenses are structural rather than psychological: prefer measured signals (agreement, retrieval scores, validation outcomes) over the model's self-report, and phrase UI copy that reflects the state ("I could not verify this in the sources") instead of decorating guesses with confidence percentages.
Uncertainty in the product, not just the pipeline
The UI is where uncertainty policy becomes visible: show citations so users can check grounding, render abstentions as clear next steps rather than dead ends, and never style a guess to look like a verified answer. A feature that says "I do not know, here is where I looked" builds more trust than one that is confidently wrong once. This is the same honesty contract as lesson 9's sentinel and lesson 7's degradation states, applied to the last mile.
Finally, connect this to evaluation (lesson 13): abstention behavior, agreement thresholds and calibration buckets are all evaluable with deterministic graders. "The model seems confident" is not a spec; "abstains when agreement is below 0.7 on the labeled set" is.
Planned lesson ai-engineering-caching-and-latency extends the pipeline work with caching and latency budgets.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement majorityVote(labels): count occurrences, pick the label with the highest count (ties go to the first label to reach the maximum, i.e. insertion order), and return { label, agreement } where agreement is the winning count divided by labels.length.
starter.javascriptfunction majorityVote(labels) { // Count labels; winner is the highest count, ties resolved by first // label to reach the maximum (insertion order). Return // { label, agreement } where agreement = winningCount / labels.length. }Reveal the reference answer
reference.javascriptfunction majorityVote(labels) { const counts = {}; for (const label of labels) counts[label] = (counts[label] || 0) + 1; let best = null; let bestCount = -1; for (const [label, count] of Object.entries(counts)) { if (count > bestCount) { best = label; bestCount = count; } } return { label: best, agreement: bestCount / labels.length }; } console.log(JSON.stringify(majorityVote(["yes", "yes", "no", "yes", "no"])));Authored expected output: {"label":"yes","agreement":0.6}
Three yes and two no votes give label yes and agreement 3/5 = 0.6. The tie rule makes the function deterministic; without a stated rule, tie behavior is an unspecified bug.
Exercise 2Implement
Implement abstainGate(confidence, threshold) with threshold defaulting to 0.7 and an inclusive boundary: return "answer" when confidence >= threshold, otherwise "abstain". Log the decisions for 0.65 and 0.9.
starter.javascriptfunction abstainGate(confidence, threshold = 0.7) { // "answer" when confidence >= threshold, otherwise "abstain". } console.log(abstainGate(0.65)); console.log(abstainGate(0.9));Reveal the reference answer
reference.javascriptfunction abstainGate(confidence, threshold = 0.7) { return confidence >= threshold ? "answer" : "abstain"; } console.log(abstainGate(0.65)); console.log(abstainGate(0.9));Authored expected output: abstain answer
0.65 is below the threshold so the gate abstains; 0.9 clears it so the gate answers. The boundary case 0.7 answers by the inclusive rule, which is why the rule must be written down.
Exercise 3Predict
The pipeline samples five scripted answers for the same question, computes majorityVote, and abstains when agreement is below 0.7. With samples [yes, yes, no, yes, no], predict both logged lines: the vote JSON and the final decision.
starter.javascriptfunction majorityVote(labels) { const counts = {}; for (const label of labels) counts[label] = (counts[label] || 0) + 1; let best = null; let bestCount = -1; for (const [label, count] of Object.entries(counts)) { if (count > bestCount) { best = label; bestCount = count; } } return { label: best, agreement: bestCount / labels.length }; } function abstainGate(confidence, threshold = 0.7) { return confidence >= threshold ? "answer" : "abstain"; } // Scripted samples for the same question (self-consistency). const samples = ["yes", "yes", "no", "yes", "no"]; const vote = majorityVote(samples); console.log(JSON.stringify(vote)); console.log(abstainGate(vote.agreement));Reveal the reference answer
reference.javascript// Predicted output: // // {"label":"yes","agreement":0.6} // abstain // // Trace: three yes and two no votes give label yes with agreement // 3/5 = 0.6. The gate threshold is 0.7 inclusive, and 0.6 < 0.7, so the // pipeline abstains despite the majority label. A divided vote signals // ambiguity; the honest output is abstention or escalation.Authored expected output: {"label":"yes","agreement":0.6} abstain
The majority label is yes but agreement 0.6 is below the 0.7 threshold, so the gate abstains. This is the intended behavior: a divided vote is a signal of ambiguity, not a mandate to answer.
Exercise 4Explain
A reliability review finds that among cases where the assistant stated 90 percent confidence, it was correct 60 percent of the time. Explain what this means, what it implies for the UI, and one structural remedy.
starter.text// No code needed; write the explanation.Reveal the reference answer
reference.textThe system is overconfident: its 90 percent bucket behaves like 60 percent, so stated confidence cannot be trusted as a probability. UI copy should not decorate answers with those percentages, and high-stakes flows should not gate on them. A structural remedy is to recalibrate or replace the signal: bucket measured outcomes and rescale, or gate on measured signals such as retrieval scores and self-consistency agreement, then verify the new signal with an eval set.Authored expected output: An explanation identifying overconfidence, its UI implication, and a structural remedy with verification
Calibration is a measurable property; the fix is a measured signal plus evaluation, not a better-sounding adjective.
Exercise 5Explain
Knowledge check: what does temperature 0 change about a model's uncertainty?
starter.text// Choose the correct option.Reveal the reference answer
reference.textIt removes sampling randomness so the output is reproducible, but it does not address knowledge gaps or ambiguous inputs, and it does not make the chosen output correct. Confidence and determinism are different properties.Authored expected output: It removes sampling randomness only; correctness and knowledge gaps are unaffected
Determinism is a property of the decoding step; truthfulness and calibration are properties of the system around the model.
Common misconceptions
#- Myth: temperature 0 makes the model certain. Fact: it removes sampling randomness; knowledge gaps and ambiguity remain, and the model can be confidently wrong.
- Myth: a model's stated confidence is a probability. Fact: verbalized confidence is often poorly calibrated, especially on unfamiliar inputs; prefer measured signals.
- Myth: a majority vote of samples is reliable. Fact: a 3-to-2 split is weak evidence; gate on agreement, not just on which label won.
Follow-up practice
#- ai-engineering-caching-and-latency
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.