Catching hallucinations before users do

55 min7 partsCoreFast-moving topicChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • 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:

  1. yes_probability(logprob_yes, logprob_no) and classify(probs, threshold): a score from the checker's two tokens, and a decision from the score.
  2. best_threshold(probs, labels, min_precision): the threshold that sends the most supported answers while staying precise enough.
  3. ece(probs, labels) and fit_temperature(logits, labels, grid): how far the scores are from honest, and the one number that fixes them.
CallReturns
yes_probability(-1.2, -0.4)0.310
best_threshold on ten checked answers, at 95% precision0.91
ece of an overconfident checker0.088
fit_temperature on 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.

Part 1 of 7about 8 min
Why models make things up

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).

Predict

Which of the two is easier to catch automatically?

Pick an answer above to see the rest

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.

Predict

With no penalty for a wrong answer, when does guessing beat saying I don't know?

Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 8 min
Ground the answer

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))
Predict

The answer quotes two passages from the policy. Which does the check reject?

Pick one to see what it prints.
Pick an answer above to see the rest

What the quote check can't see

The check has a limit worth knowing.

Predict

An answer about a gift card quotes the gear return window, word for word. Does the quote check stop it?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 12 min
A score from Yes and No

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}")
Predict

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 one to see what it prints.
Pick an answer above to see the rest

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:

Ten checked answers at two thresholds
0510
0.91 and up: 3 of 3 sent are supported, 3 of the 6 supported are sent
0.74 and up: 5 of 6 sent are supported, 5 of the 6 supported are sent
sent and supportedheld backsent but not supported

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%.

Part 3 done
Part 4 of 7about 12 min
Calibration

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.

Predict

A checker scores 200 answers at about 0.9. If its scores are calibrated, about how many of those answers are supported?

Pick an answer above to see the rest
Predict

Dividing every raw score by a temperature of 1.5 before turning it into a probability does what to the calibration error?

Pick one to see what it prints.
Pick an answer above to see the rest

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.

Part 4 done
Part 5 of 7about 8 min
Ask several times

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")
Predict

Answering only when at least 4 of 5 samples agree: about what share of the questions get answered?

Pick one to see what it prints.
Pick an answer above to see the rest

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.

Part 5 done
Part 6 of 7about 4 min
The worked example

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?

Predict

Order status comes from the shop's database. How should the assistant get it into an answer?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 3 min
Follow-ups

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.

Predict

Every response matches the schema, with a return_days field that's a whole number. What does that rule out?

Pick an answer above to see the rest

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.

Check yourself
5 questions
  1. 1.Which of these is a hallucination?

  2. 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. 3.Every quote in an answer is found, word for word, in the retrieved policy. Can the answer still be wrong?

  4. 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. 5.You sample each answer five times and send it only when four agree. What does that cost?

Practice

Sources (16)
  1. 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.”
  2. 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.”
  3. 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%”
  4. 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%”
  5. 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%”
  6. Reduce hallucinations · Anthropic, Claude Platform Docs · Nov 19, 2026
    “Explicitly give Claude permission to admit uncertainty. This technique can drastically reduce false information.”
  7. 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.”
  8. 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.”
  9. 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.”
  10. Using logprobs · OpenAI Cookbook · Dec 20, 2023
    “When logprobs is enabled, the API returns the log probabilities of each output token”
  11. Using logprobs · OpenAI Cookbook · Dec 20, 2023
    “logprobs provide a probability associated with each class prediction, enabling users to set classification or confidence thresholds.”
  12. 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.”
  13. 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.”
  14. 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.”
  15. 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.”
  16. Structured model outputs · OpenAI API docs · Nov 19, 2026
    “Structured Outputs constrains completed, non-refusal model output to your supplied JSON Schema.”