Catching hallucinations before users do
- Define a hallucination, tell the two kinds apart, and say why scoring that ignores abstaining rewards guessing
- Ground answers in word-for-word quotes, and check every quote against the source in code
- Turn a checker model's Yes and No token probabilities into a score you can threshold
- Measure whether that score is calibrated, and fix it with temperature scaling
- Sample an answer several times and answer only when the samples agree, knowing what it costs
A checker from Yes and No, the way the coding round asks
A PracHub report from an Anthropic coding round: the candidate got a helper that returns a token probability for each input in a batch, and had to build a binary classifier with it (1 report). Pointed at an answer and its source, that classifier is a hallucination check. This lesson's practice problem builds it, in three levels:
yes_probability(logprob_yes, logprob_no)andclassify(probs, threshold): a score from the checker's two tokens, and a decision from the score.best_threshold(probs, labels, min_precision): the threshold that sends the most supported answers while staying precise enough.ece(probs, labels)andfit_temperature(logits, labels, grid): how far the scores are from honest, and the one number that fixes them.
Call Returns yes_probability(-1.2, -0.4)0.310 best_thresholdon ten checked answers, at 95% precision0.91 eceof an overconfident checker0.088 fit_temperatureon the same checker1.5, which brings the error to 0.047
The lesson follows the outdoor shop's assistant, which told a customer that returns take 60 days when its policy says 30: what hallucinations are, quotes checked in code, a checker's Yes and No, calibration, and asking several times. Seven steps end with a small task in the editor.
Two wrong answers from the shop's assistant
The outdoor shop's assistant answers from its instructions, its return policy and its catalog. Two answers went wrong last week:
- A customer asked how long returns take, and the assistant said 60 days. The policy it was given says 30.
- A customer asked whether the camp lantern is waterproof, and the assistant said yes, rated for rain. The catalog entry doesn't say either way.
Both are hallucinations, which OpenAI defines as plausible but false statements generated by language models. A prep site's list of Anthropic ML engineer questions asks for exactly this definition (1 source), and another asks how you'd handle hallucinations in a model deployed to users (1 source).
Which of the two is easier to catch automatically?
How the scoring decides whether a model guesses
Whether a model guesses depends on how its answers are scored. Say a right answer scores 1, a wrong one scores wrong, and "I don't know" scores 0. A model that's right with chance p_right expects p_right + (1 - p_right) * wrong points from a guess.
With no penalty for a wrong answer, when does guessing beat saying I don't know?
Ask for the quotes first, then check that each one is really there
Anthropic's docs give three moves against hallucinations:
- Give the model permission to admit uncertainty, which can drastically reduce false information.
- Ask it to extract word-for-word quotes before it answers, so the answer rests on the actual text.
- Verify claims with citations, which return the exact passages that support each claim.
Quotes are worth asking for because a program can check them. A quote that isn't in the source was made up, and an answer resting on it gets stopped. unsupported makes that check. It lowercases the source and each quote, turns every run of spaces and line breaks into one space, and returns the quotes it can't find in the source. You'll write it in the next step.
policy = "Unused gear can be returned within 30 days of delivery. Worn items are not accepted."
quotes = ["returned within 30 days of delivery", "Worn items are accepted"]
print(unsupported(quotes, policy))
The answer quotes two passages from the policy. Which does the check reject?
What the quote check can't see
The check has a limit worth knowing.
An answer about a gift card quotes the gear return window, word for word. Does the quote check stop it?
Ask a checker model Yes or No, and read how sure it was
A second model can read the answer and its source and answer one question: is every claim in the answer supported by the source? Asked to reply with one token, Yes or No, it gives more than a verdict. OpenAI's cookbook notes that with logprobs enabled, the API returns the log probabilities of each output token (the natural log of each token's probability), and that they enable classification or confidence thresholds.
Anthropic's coding round asked for exactly this build: given a helper that returns a token probability for each input in a batch, make a binary classifier (1 report).
print(f"{yes_probability(-0.1, -2.4):.3f} {yes_probability(-1.2, -0.4):.3f}")
The checker gives Yes a log probability of −1.2 and No −0.4. What's the chance of Yes, counting only those two tokens?
Pick the threshold from answers people checked
The score now works like any classifier's: answers at or above a threshold go out, and the rest are held back, the way the evals lesson picks a judge's threshold. Two numbers from answers people checked decide where it goes. Precision is the share of the answers sent that really are supported. Recall is the share of all supported answers that get sent. A higher threshold buys precision and pays in recall.
The shop needs 95% of what it sends to be supported, and within that, it wants to send as much as it can. Here are two thresholds on ten answers people checked:
The first meets the 95% bar. The second sends more, but one in six of what it sends is wrong.
In the editor, write best_threshold(probs, labels, min_precision): try each score as the threshold, and keep the one with the most recall whose precision is high enough. It prints the threshold for ten checked answers at two bars, 95% and 80%.
A score you act on has to be calibrated
A threshold of 0.9 means something only if answers scored 0.9 are supported about 90% of the time. A score with that property is calibrated. Anthropic's researchers found that larger models are well calibrated on multiple choice and true/false questions when they're asked in the right format. Guo and colleagues found the opposite for many trained classifiers: modern networks are often overconfident, and a one-number fix, temperature scaling, is surprisingly effective on most datasets.
A checker scores 200 answers at about 0.9. If its scores are calibrated, about how many of those answers are supported?
Dividing every raw score by a temperature of 1.5 before turning it into a probability does what to the calibration error?
Fit the temperature on answers people checked
Temperature scaling divides the raw score by one number, fit on answers people checked, before turning it into a probability. It never changes which answers rank above which, so the precision and recall at any rank stay put. What it fixes is the meaning of the number, which is what makes a threshold like 0.9 safe to write into a policy.
To fit it, try each temperature on a grid, and keep the one whose probabilities give the lowest log loss on the checked answers: −log p for a supported answer, and −log(1 − p) for one that wasn't.
In the editor, write fit_temperature(logits, labels, grid). It fits the simulated checker, then prints the calibration error at that temperature.
Ask the same question several times, and answer only when the answers agree
Anthropic's docs suggest running the same prompt several times and comparing the outputs, since inconsistencies across them could indicate hallucinations. SelfCheckGPT built a detector on the same idea: sample several responses and check them against each other, with no external database.
The simulation below asks 1,000 questions five times each. On 70% of them the model knows the answer and almost always gives it. On the rest it guesses among four answers. Each question's confidence is the share of its five samples that agree with the most common one. majority returns that answer and that share, and you'll write it in the next step.
rng = random.Random(8)
# (share of 5 samples that agree, majority answer is right)
results = []
for _ in range(1000):
# the model knows this answer, or is guessing
knows = rng.random() < 0.7
samples = []
for _ in range(5):
if knows:
samples.append("right" if rng.random() < 0.95 else rng.choice("abc"))
else:
samples.append(rng.choice(["right", "a", "b", "c"]))
top, agree = majority(samples)
results.append((agree, top == "right"))
for cut in (0.0, 0.6, 0.8):
kept = [right for agree, right in results if agree >= cut]
wrong = len(kept) - sum(kept)
print(f"answer when {cut:.0%}+ agree: {len(kept) / len(results):5.1%} answered, {wrong:3} wrong, {len(results) - len(kept):3} handed off")
Answering only when at least 4 of 5 samples agree: about what share of the questions get answered?
Five samples cost five times the output
Sampling five answers costs about five times the output tokens, and the cost lesson priced output at five times input. Use it where a wrong answer is expensive, like a refund amount, not for every greeting. Agreement also needs a way to tell when two answers say the same thing in different words: the semantic entropy method groups answers by meaning rather than by their exact words before counting.
In the editor, write majority(samples), the agreement count the last step called. It prints the answer five samples agree on, and the share that do.
A worked example: handling hallucinations in the shop's assistant
The prompt, from a prep site's Anthropic list: how would you handle hallucinations in a generative AI model deployed to users (1 source)? For the shop, that means the assistant should never state a policy, price or spec it can't back up.
1. Clarify. Which wrong answers cost the most? A wrong refund amount or return window costs money. A slightly off product tip costs less. How fast must answers be? Can the assistant hand a conversation to a person?
Order status comes from the shop's database. How should the assistant get it into an answer?
What a schema guarantees
OpenAI's Structured Outputs constrains a completed, non-refusal response to the JSON Schema you supply, a description of the fields an answer must have and their types.
Every response matches the schema, with a return_days field that's a whole number. What does that rule out?
Two more follow-ups
Two shorter follow-ups come up too: the model judging its own answers, and the rate in production.
Asking the model whether its own answer is true
The same Anthropic paper on calibration had models estimate the probability that their own answers were true, and found the estimates informative when the questions were well formatted. It's a cheap first filter, and it shares the model's blind spots, so check it against people before trusting it.
Measuring the hallucination rate in production
Sample answers from real traffic, have people or a checked judge mark unsupported claims, and report the rate with an interval, as the evals lesson does for pass rates. Track it by kind of question, since a new product line with thin catalog entries is where gaps get filled with guesses.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.Which of these is a hallucination?
2.A prompt change raises your eval's accuracy from 72% to 74%. It also makes the model stop saying it doesn't know. What do you check before shipping?
3.Every quote in an answer is found, word for word, in the retrieved policy. Can the answer still be wrong?
4.Your checker's answers scored around 0.9 turn out supported only 75% of the time. You can't retrain it. What fixes its scores?
5.You sample each answer five times and send it only when four agree. What does that cost?
Practice
Sources (16)
- Why language models hallucinate · OpenAI research post (the page shows no date; its paper, arXiv 2509.04664, is dated 2025-09-04) · Sep 4, 2025
“Hallucinations are plausible but false statements generated by language models.”
- Why language models hallucinate · OpenAI research post (the page shows no date; its paper, arXiv 2509.04664, is dated 2025-09-04) · Sep 4, 2025
“language models hallucinate because standard training and evaluation procedures reward guessing over acknowledging uncertainty.”
- Why language models hallucinate · OpenAI research post, SimpleQA table (gpt-5-thinking-mini against OpenAI o4-mini) · Sep 4, 2025
“Abstention rate (no specific answer is given) | 52% | 1%”
- Why language models hallucinate · OpenAI research post, SimpleQA table (gpt-5-thinking-mini against OpenAI o4-mini) · Sep 4, 2025
“Accuracy rate (right answer, higher is better) | 22% | 24%”
- Why language models hallucinate · OpenAI research post, SimpleQA table (gpt-5-thinking-mini against OpenAI o4-mini) · Sep 4, 2025
“Error rate (wrong answer, lower is better) | 26% | 75%”
- Reduce hallucinations · Anthropic, Claude Platform Docs · Nov 19, 2026
“Explicitly give Claude permission to admit uncertainty. This technique can drastically reduce false information.”
- Reduce hallucinations · Anthropic, Claude Platform Docs · Nov 19, 2026
“ask Claude to extract word-for-word quotes first before performing its task. This grounds its responses in the actual text, reducing hallucinations.”
- Reduce hallucinations · Anthropic, Claude Platform Docs · Nov 19, 2026
“Run Claude through the same prompt multiple times and compare the outputs. Inconsistencies across outputs could indicate hallucinations.”
- Citations · Anthropic, Claude Platform Docs · Nov 19, 2026
“Citations return the exact passages that support each claim, so you can verify answers and surface sources to your users.”
- Using logprobs · OpenAI Cookbook · Dec 20, 2023
“When logprobs is enabled, the API returns the log probabilities of each output token”
- Using logprobs · OpenAI Cookbook · Dec 20, 2023
“logprobs provide a probability associated with each class prediction, enabling users to set classification or confidence thresholds.”
- SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection for Generative Large Language Models · Manakul, Liusie and Gales, arXiv 2303.08896 (EMNLP 2023) · Mar 15, 2023
“a simple sampling-based approach that can be used to fact-check the responses of black-box models in a zero-resource fashion, i.e. without an external database.”
- Detecting hallucinations in large language models using semantic entropy · Farquhar et al., Nature 630 · Jun 19, 2024
“Our method addresses the fact that one idea can be expressed in many ways by computing uncertainty at the level of meaning rather than specific sequences of words.”
- Language Models (Mostly) Know What They Know · Kadavath et al. (Anthropic), arXiv 2207.05221 · Jul 11, 2022
“We first show that larger models are well-calibrated on diverse multiple choice and true/false questions when they are provided in the right format.”
- On Calibration of Modern Neural Networks · Guo et al., arXiv 1706.04599 (ICML 2017) · Jun 14, 2017
“on most datasets, temperature scaling ... is surprisingly effective at calibrating predictions.”
- Structured model outputs · OpenAI API docs · Nov 19, 2026
“Structured Outputs constrains completed, non-refusal model output to your supplied JSON Schema.”