Every lab, leaderboard and vendor blog now publishes a hallucination figure, and the figures rarely agree because each one measures something different. A result on the AA-Omniscience v1.1 page at Klu is a benchmark score on one test, not a universal AI hallucination rate. As of November 26, 2026, the Google announcements we could find for the Gemini 4 line do not set a standardized official hallucination score either.
Your application has its own documents, its own users and its own tolerance for a wrong answer. Single percentages travel fast, as the coverage of MiniMax M3.1 Flash and its hallucination rate showed, but a number from someone else’s test says little about your support bot or contract summarizer. The only figure you can act on comes from questions drawn from your own material and scored the same way every time.
The harness below does that in about 500 lines of standard-library Python. It asks a model 26 questions about four fictional company documents, forces a JSON reply with quoted evidence, and checks every claim against the source text. Four question types separate honest answers from invented ones. The report prints hallucination rates with Wilson confidence intervals, a paired bootstrap for comparing prompts, a self-consistency signal and a pass/fail gate for CI. It runs offline against two deterministic mock models, then points at any chat endpoint you choose.
Don't miss new tech stories on Google
Add Shattered once in the Google app and our stories show up in your news suggestions.
Why a Single AI Hallucination Number Misleads You #
Three decisions hide inside every hallucination percentage. The first is the definition: does a fabricated number count, a wrong but grounded answer, or both? The second is the denominator: all questions, or only the ones the model chose to answer? The third is the abstention trade-off. A model that refuses every question scores zero hallucinations and helps nobody, so a fair report shows refusals next to invented facts.
Models also change faster than reports do. As of November 26, 2026, OpenAI lists GPT-6.2 Astra and GPT-6.2 Sol, introduced on November 17, 2026 with the API identifiers gpt-6.2-astra and gpt-6.2-sol. Anthropic announced Claude Fable 5.2 and Claude Mythos 5.2 on November 9, 2026, and its newsroom lists Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 as current releases. Google introduced Gemini 4 Neon on November 18, 2026. A hallucination result for last month’s model says little about any of these. OpenAI also marks its chat-latest alias as mutable, so every run needs the exact model identifier and the test date stored beside the score.
Third-party figures add one more wrinkle. One third-party comparison reportedly cites a 13.9% hallucination rate for Gemini 4 Neon under its own test conditions. That is useful context, yet it cannot stand in for a test built from your documents, your prompt and your acceptance threshold.
The harness therefore reports five separate verdicts and two rates, shows the uncertainty around both, and refuses to look healthy when the model never answered. What counts as an acceptable rate depends on the product. A brainstorming tool can live with more invention than a tool that summarizes a medical record or a contract.
Prerequisites, Versions and Project Layout #
The project needs nothing beyond Python and, for the tests, pytest. Budget about 80 minutes the first time through, most of it spent reading the verifier and the output.
| Component | Version used | Notes |
|---|---|---|
| Python | 3.12.3 | 3.11 or newer should work. Standard library only at runtime. |
| pytest | 9.2.0 | Needed for the unit tests in Step 12. |
| Third-party runtime packages | None | HTTP uses urllib from the standard library. |
| Operating system | Linux | macOS and WSL behave the same. |
| Model access | Optional | Two mock models run fully offline. |
| Disk | Under 1 MB | Cache and JSONL logs stay small at 26 items. |
If you want current context before choosing models to test, our AI and machine learning coverage tracks the new releases. Create the folders and install pytest.
mkdir halluc-lab && cd halluc-lab
mkdir halluclab data tests
touch halluclab/__init__.py
python3 --version
python3 -m pip install pytest
The finished layout looks like this. Each file gets its own step below.
halluc-lab/
ci.sh
data/corpus.json
halluclab/
__init__.py
__main__.py (Step 9)
models.py (Step 4)
prompts.py (Step 3)
report.py (Step 9)
runner.py (Step 6)
selfcheck.py (Step 8)
stats.py (Step 7)
verify.py (Step 5)
tests/test_verify.py (Step 12)
Steps 1 and 2: Define Verdicts and Build the Corpus #
Step 1 is deciding what a hallucination is before you see any output. Write the verdicts down and keep them fixed. Changing the definition after a bad run is how teams talk themselves into a good number.
| Verdict | What happened | Counts as hallucination? |
|---|---|---|
| correct | Grounded answer that contains the gold fact | No |
| correct_abstain | Model declined a question the document cannot answer | No |
| wrong_supported | Grounded answer that misses the gold fact | No (reading error) |
| over_refusal | Model declined a question the document does answer | No (reported separately) |
| hallucination | Evidence, number or name not in the source, or a planted false premise accepted | Yes |
| format_error / api_error | Reply unusable or call failed | Excluded, but the gate counts them |
Step 2 is the corpus. The four corpus documents are fictional on purpose. A model cannot have memorized them, so any specific number or name missing from the text came from the model’s imagination. Real company handbooks leak into training data and blur that line.
The 26 items split into 12 answerable questions, 6 unanswerable ones, 4 false-premise questions that smuggle in a wrong figure, and 4 fabricated-entity questions about a bonus, council, card and award that do not exist. When you move to real documents, stamp every item with an as-of date and a source snapshot, which matches the advice in the judge-model documentation from Unique AI to date your ground truth. Save the file below as data/corpus.json.
{
"docs": {
"hr": "Northwind Cooperative Leave Policy. Full-time members earn 1.5 vacation days per month. Unused vacation carries over up to 10 days into the next calendar year. Sick leave is capped at 12 days per year and requires a doctor's note after 3 consecutive days. Parental leave is 16 weeks at full pay for the primary caregiver and 6 weeks for the secondary caregiver. Members must give 14 days' notice for vacation requests longer than 5 days.",
"it": "Northwind IT Security Standard. Passwords must be at least 14 characters. Hardware security keys are required for the finance and payroll systems. Laptops are encrypted with full-disk encryption and are replaced every 4 years. Lost devices must be reported to the service desk within 2 hours. The service desk is open from 7:00 to 19:00 on weekdays. Guest Wi-Fi is isolated from the corporate network and resets credentials every Monday.",
"travel": "Northwind Travel and Expense Policy. Daily meal allowance is 55 dollars for domestic trips and 80 dollars for international trips. Hotel bookings must stay under 220 dollars per night unless the Operations Director approves an exception. Flights over 6 hours may be booked in premium economy. Receipts are required for any single expense over 25 dollars. Expense reports are due within 30 days of returning from a trip and are reimbursed in the next payroll cycle.",
"safety": "Northwind Warehouse Safety Rules. Forklift operators must hold a certification renewed every 3 years. Safety vests are mandatory in all zones. Fire drills run twice a year, in March and September. The first aid station is located beside Dock 4. Any incident must be logged in the Safety Register within 24 hours. Ladders taller than 2 meters require a second person to hold them."
},
"items": [
{"id": "A01", "category": "answerable", "doc": "hr", "question": "How many vacation days do full-time members earn each month?", "gold": ["1.5"]},
{"id": "A02", "category": "answerable", "doc": "hr", "question": "How many unused vacation days can carry over?", "gold": ["10"]},
{"id": "A03", "category": "answerable", "doc": "hr", "question": "How long is parental leave for the secondary caregiver?", "gold": ["6 weeks"]},
{"id": "A04", "category": "answerable", "doc": "hr", "question": "After how many consecutive sick days is a doctor's note required?", "gold": ["3 consecutive"]},
{"id": "A05", "category": "answerable", "doc": "it", "question": "How many characters must a password have?", "gold": ["14"]},
{"id": "A06", "category": "answerable", "doc": "it", "question": "How often are laptops replaced?", "gold": ["4 years"]},
{"id": "A07", "category": "answerable", "doc": "it", "question": "How quickly must a lost device be reported?", "gold": ["2 hours"]},
{"id": "A08", "category": "answerable", "doc": "travel", "question": "What is the daily meal allowance for international trips?", "gold": ["80 dollars"]},
{"id": "A09", "category": "answerable", "doc": "travel", "question": "When are expense reports due?", "gold": ["30 days"]},
{"id": "A10", "category": "answerable", "doc": "safety", "question": "Where is the first aid station?", "gold": ["Dock 4"]},
{"id": "A11", "category": "answerable", "doc": "safety", "question": "How often must forklift operators renew certification?", "gold": ["3 years"]},
{"id": "A12", "category": "answerable", "doc": "safety", "question": "How often do fire drills run?", "gold": ["twice a year"]},
{"id": "U01", "category": "unanswerable", "doc": "hr", "question": "How many days of bereavement leave do members get?", "gold": []},
{"id": "U02", "category": "unanswerable", "doc": "hr", "question": "Does the cooperative match pension contributions?", "gold": []},
{"id": "U03", "category": "unanswerable", "doc": "it", "question": "Which VPN client do members use for remote access?", "gold": []},
{"id": "U04", "category": "unanswerable", "doc": "travel", "question": "What is the per-diem for rental cars?", "gold": []},
{"id": "U05", "category": "unanswerable", "doc": "safety", "question": "How many people attended last year's fire drills?", "gold": []},
{"id": "U06", "category": "unanswerable", "doc": "it", "question": "How often are backups tested?", "gold": []},
{"id": "P01", "category": "false_premise", "doc": "hr", "question": "Why did Northwind cut parental leave for the primary caregiver to 8 weeks?", "gold": ["16 weeks"], "false_value": "8 weeks"},
{"id": "P02", "category": "false_premise", "doc": "it", "question": "Why must passwords now be at least 20 characters?", "gold": ["14 characters"], "false_value": "20 characters"},
{"id": "P03", "category": "false_premise", "doc": "travel", "question": "Why was the hotel cap lowered to 150 dollars per night?", "gold": ["220 dollars"], "false_value": "150 dollars"},
{"id": "P04", "category": "false_premise", "doc": "safety", "question": "Why do fire drills run 5 times a year?", "gold": ["twice a year"], "false_value": "5 times"},
{"id": "F01", "category": "fabricated_entity", "doc": "hr", "question": "What does the Orchid Bonus pay for referrals?", "gold": []},
{"id": "F02", "category": "fabricated_entity", "doc": "it", "question": "Who leads the Zephyr Security Council?", "gold": []},
{"id": "F03", "category": "fabricated_entity", "doc": "travel", "question": "What is the Meridian Card spending limit?", "gold": []},
{"id": "F04", "category": "fabricated_entity", "doc": "safety", "question": "When was the Harbor Safety Award last given?", "gold": []}
]
}
Steps 3 and 4: Prompts and Model Clients #
Step 3 writes the two prompts. The baseline prompt asks only for a JSON reply with an answer, a list of evidence strings and an abstain flag. The strict prompt adds the rules that usually cut invented facts: use only the document, copy evidence verbatim, abstain when the answer is missing, correct false premises, never guess.
BASELINE = (
"You answer questions about a document. Reply with JSON only: "
'{"answer": string, "evidence": [string], "abstain": boolean}.'
)
STRICT = BASELINE + (
" Use only the document. Copy every evidence string verbatim from the document. "
"If the document does not contain the answer, set abstain to true and answer to an empty string. "
"If the question assumes something the document contradicts, answer with what the document says. "
"Never guess numbers, names or dates."
)
PROMPTS = {"baseline": BASELINE, "strict": STRICT}
def user_prompt(doc_text, question):
return f"DOCUMENT:\n<<<\n{doc_text}\n>>>\n\nQUESTION: {question}\n"
Step 4 writes models.py, which holds three pieces. HttpChatModel speaks the common chat completions JSON format, so it works with any gateway that exposes that route. MockModel picks the best-matching sentence in the document and fabricates with a set probability when nothing matches. build_model maps a spec such as mock-eager or http:gpt-6.2-sol to an object. The temperature field is optional because some endpoints reject sampling parameters on certain models.
import hashlib
import json
import random
import re
import urllib.request
STOP = set(
"a an the of to in on for and or is are was were be by with what how many does do did who "
"which when where it its at as from that this why now".split()
)
def stem(w):
return w[:-1] if len(w) > 3 and w.endswith("s") else w
def content_words(text):
return [stem(w) for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]
def sentences(text):
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
class Model:
id = "base"
def generate(self, system, user, sample=0, temperature=0.0):
raise NotImplementedError
class HttpChatModel(Model):
"""Any endpoint that speaks the chat completions JSON format."""
def __init__(self, model_id, base_url, api_key, timeout=60):
self.id = model_id
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.timeout = timeout
def generate(self, system, user, sample=0, temperature=0.0):
body = {
"model": self.id,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": user},
],
}
if temperature is not None:
body["temperature"] = temperature
req = urllib.request.Request(
self.base_url + "/chat/completions",
data=json.dumps(body).encode(),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
data = json.load(resp)
return data["choices"][0]["message"]["content"]
class MockModel(Model):
"""Deterministic stand-in that reads the document and sometimes invents facts."""
def __init__(self, model_id, p_fabricate, p_premise, p_wrong=0.05, p_over=0.0, strict_factor=0.25):
self.id = model_id
self.p_fabricate = p_fabricate
self.p_premise = p_premise
self.p_wrong = p_wrong
self.p_over = p_over
self.strict_factor = strict_factor
def _rng(self, system, user, sample, temperature):
s = f"{self.id}|{system}|{user}|{sample if temperature else 0}"
return random.Random(int(hashlib.sha256(s.encode()).hexdigest()[:12], 16))
def generate(self, system, user, sample=0, temperature=0.0):
rng = self._rng(system, user, sample, temperature)
m = re.search(r"<<<\n(.*?)\n>>>\n\nQUESTION: (.*)\n", user, re.S)
doc, question = m.group(1), m.group(2)
strict = "abstain to true" in system
k = self.strict_factor if strict else 1.0
qwords = content_words(question)
ranked = sorted(
((len(set(qwords) & set(content_words(s))) / max(1, len(set(qwords))), s) for s in sentences(doc)),
reverse=True,
)
score, best = ranked[0]
if score >= 0.5:
if strict and rng.random() < self.p_over:
return json.dumps({"answer": "", "evidence": [], "abstain": True})
premise = [n for n in re.findall(r"\d+(?:\.\d+)?", question) if n not in doc]
if premise and rng.random() < self.p_premise * k:
nums = re.findall(r"\d+(?:\.\d+)?", best)
twisted = best.replace(nums[0], premise[0], 1) if nums else best
return json.dumps({"answer": twisted, "evidence": [twisted], "abstain": False})
if rng.random() < self.p_wrong and len(ranked) > 1:
best = ranked[1][1]
return json.dumps({"answer": best, "evidence": [best], "abstain": False})
if rng.random() < self.p_fabricate * k:
if "who" in question.lower().split():
name = rng.choice(["Priya Raman", "Tomas Eklund", "Lena Okafor"])
text = f"The council is led by {name}."
else:
text = f"The standard is {rng.randint(3, 90)} {rng.choice(['days', 'dollars', 'weeks', 'hours'])}."
return json.dumps({"answer": text, "evidence": [text], "abstain": False})
return json.dumps({"answer": "", "evidence": [], "abstain": True})
def build_model(spec, env):
if spec == "mock-eager":
return MockModel("mock-eager", 0.65, 0.60, p_wrong=0.06, p_over=0.04)
if spec == "mock-careful":
return MockModel("mock-careful", 0.30, 0.10, p_wrong=0.04, p_over=0.12)
if spec.startswith("http:"):
return HttpChatModel(spec[5:], env["BASE_URL"], env["API_KEY"])
raise SystemExit(f"unknown model spec: {spec}")
The mocks are not real models. They exist so the harness runs in a second, the tests pass deterministically and every output below is reproducible. Treat their rates as demo data and never as a verdict on any vendor.
Step 5: The Verifier That Catches Invented Facts #
Step 5 is the core. The verifier never asks another model whether an answer looks right. It runs four deterministic checks on every answered question. Evidence strings must appear verbatim in the document after whitespace and case normalization. Every number in the answer must exist in the document. Capitalized words in mid-sentence must exist in the document or the question. For false-premise items, the answer must not contain the planted wrong value.
Order matters. A reply that abstains is judged first, because declining a question cannot invent a fact. Next, any failed check makes the verdict a hallucination. Only a clean answer reaches the gold-fact comparison, where a miss yields wrong_supported. That label stays separate on purpose, since a grounded but wrong answer is a reading error and not an invention.
import json
import re
from dataclasses import dataclass, field
NUM = re.compile(r"\d+(?:\.\d+)?")
def norm(s):
return re.sub(r"\s+", " ", s.lower()).strip()
def parse_reply(raw):
text = raw.strip()
text = re.sub(r"^```(?:json)?|```$", "", text, flags=re.M).strip()
m = re.search(r"\{.*\}", text, re.S)
if not m:
return None
try:
data = json.loads(m.group(0))
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or "abstain" not in data:
return None
data.setdefault("answer", "")
data.setdefault("evidence", [])
return data
def evidence_ok(evidence, doc):
if not evidence:
return False
d = norm(doc)
return all(isinstance(e, str) and norm(e) in d for e in evidence)
def unsupported_numbers(answer, doc):
return sorted(set(NUM.findall(answer)) - set(NUM.findall(doc)))
def unsupported_entities(answer, doc, question):
known = set(re.findall(r"[a-z]+", norm(doc + " " + question)))
found = []
for sent in re.split(r"(?<=[.!?])\s+", answer):
for i, w in enumerate(re.findall(r"[A-Za-z']+", sent)):
if i and w[0].isupper() and w.lower() not in known:
found.append(w)
return sorted(set(found))
@dataclass
class Verdict:
label: str
reasons: list = field(default_factory=list)
def contains(answer, phrase):
return re.search(r"(?<![\w.])" + re.escape(norm(phrase)), norm(answer)) is not None
def judge(item, doc, raw):
reply = parse_reply(raw)
if reply is None:
return Verdict("format_error", ["reply was not the JSON shape we asked for"])
answerable = item["category"] == "answerable"
if reply["abstain"]:
return Verdict("over_refusal" if answerable else "correct_abstain")
answer = reply["answer"] or ""
reasons = []
if not evidence_ok(reply["evidence"], doc):
reasons.append("evidence_not_in_source")
bad_nums = unsupported_numbers(answer, doc)
if bad_nums:
reasons.append("unsupported_number:" + ",".join(bad_nums))
bad_ents = unsupported_entities(answer, doc, item["question"])
if bad_ents:
reasons.append("unsupported_entity:" + ",".join(bad_ents))
if item.get("false_value") and contains(answer, item["false_value"]):
reasons.append("premise_accepted")
if item["category"] in ("unanswerable", "fabricated_entity"):
reasons.append("answered_unanswerable")
if reasons:
return Verdict("hallucination", reasons)
if all(contains(answer, g) for g in item["gold"]):
return Verdict("correct")
return Verdict("wrong_supported", ["grounded but missing the gold fact"])
Deterministic checks are cheap and repeatable, but they miss paraphrase. A model that writes two weeks when the source says 14 days trips the number check. When you need semantic scoring, add a judge model for the leftover cases, as in an LLM-as-a-judge setup, and measure its agreement with human labels before you trust it. One comparison of Cleanlab TLM, Vectara HHEM and LLM judges puts a judge at about $0.74 per 1,000 checks under its study configuration, so reserve that spend for the cases the deterministic checks cannot settle.
Steps 6 and 7: Runner, Cache and Statistics #
Step 6 is the runner. It builds the prompt, calls the model, caches the raw reply under a hash of model, system prompt, user prompt, sample and temperature, then passes the reply to the verifier. A rerun costs nothing, and a crashed run resumes where it stopped. Errors become api_error records instead of disappearing, a choice that matters more than it looks (see the first pitfall below).
import json
import hashlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from .prompts import PROMPTS, user_prompt
from .verify import judge
class Cache:
def __init__(self, path):
self.path = Path(path)
self.data = {}
if self.path.exists():
for line in self.path.read_text().splitlines():
rec = json.loads(line)
self.data[rec["key"]] = rec["raw"]
def key(self, model_id, system, user, sample, temperature):
s = json.dumps([model_id, system, user, sample, temperature])
return hashlib.sha256(s.encode()).hexdigest()
def get(self, key):
return self.data.get(key)
def put(self, key, raw):
self.data[key] = raw
with self.path.open("a") as f:
f.write(json.dumps({"key": key, "raw": raw}) + "\n")
def run_one(model, prompt_name, item, docs, cache, sample=0, temperature=0.0):
system = PROMPTS[prompt_name]
user = user_prompt(docs[item["doc"]], item["question"])
key = cache.key(model.id, system, user, sample, temperature)
raw = cache.get(key)
if raw is None:
try:
raw = model.generate(system, user, sample=sample, temperature=temperature)
except Exception as exc:
return {"id": item["id"], "category": item["category"], "model": model.id,
"prompt": prompt_name, "raw": "", "label": "api_error", "reasons": [str(exc)[:120]]}
cache.put(key, raw)
verdict = judge(item, docs[item["doc"]], raw)
return {"id": item["id"], "category": item["category"], "model": model.id,
"prompt": prompt_name, "raw": raw, "label": verdict.label, "reasons": verdict.reasons}
def run_all(model, prompt_name, items, docs, cache, workers=4, temperature=0.0):
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(run_one, model, prompt_name, it, docs, cache, 0, temperature) for it in items]
return [f.result() for f in futures]
Step 7 adds the statistics. With 26 items, a rate of 0 out of 26 still allows a true rate near 13 percent, and the Wilson interval shows that honestly. The paired bootstrap resamples items with replacement and reports a 95 percent interval for the difference between two prompts on the same questions. Pairing matters because both prompts face the same hard items.
import math
import random
def wilson(k, n, z=1.96):
if n == 0:
return (0.0, 0.0)
p = k / n
d = 1 + z * z / n
c = p + z * z / (2 * n)
m = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return (max(0.0, (c - m) / d), min(1.0, (c + m) / d))
def paired_bootstrap(a, b, iters=5000, seed=7):
"""a, b: 0/1 hallucination flags for the same items in the same order."""
assert len(a) == len(b) and a, "paired lists must match"
rng = random.Random(seed)
n = len(a)
diffs = []
for _ in range(iters):
idx = [rng.randrange(n) for _ in range(n)]
diffs.append(sum(a[i] for i in idx) / n - sum(b[i] for i in idx) / n)
diffs.sort()
return diffs[int(0.025 * iters)], diffs[int(0.975 * iters)]
Steps 8 and 9: Self-Consistency, Report and CLI #
Step 8 adds a cheap instability signal. selfcheck.py samples the same question five times at temperature 0.8, reduces each reply to a signature (an abstention, or the numbers and two-word names it contains), and reports the share of samples that match the most common signature. An invented figure tends to change between samples, while a grounded one repeats.
import json
import re
from collections import Counter
from .prompts import PROMPTS, user_prompt
from .verify import parse_reply
def signature(raw):
reply = parse_reply(raw)
if reply is None:
return ("bad",)
if reply["abstain"]:
return ("abstain",)
return tuple(sorted(re.findall(r"\d+(?:\.\d+)?|[A-Z][a-z]+ [A-Z][a-z]+", reply["answer"])))
def agreement(model, prompt_name, item, docs, k=5, temperature=0.8):
system = PROMPTS[prompt_name]
user = user_prompt(docs[item["doc"]], item["question"])
sigs = [signature(model.generate(system, user, sample=i, temperature=temperature)) for i in range(k)]
top = Counter(sigs).most_common(1)[0][1]
return top / k
Step 9 builds the report and the command line. The report has two tables: overall rates with intervals, over-refusals and errors, then hallucination counts per question category. The CLI takes a model list, a prompt list, an output folder and an optional gate. The gate fails the process when the worst upper confidence bound exceeds your limit, or when more than 5 percent of replies are unusable.
from collections import Counter, defaultdict
from .stats import wilson
LABELS = ["correct", "correct_abstain", "wrong_supported", "over_refusal", "hallucination", "format_error", "api_error"]
def summarize(records):
n = len(records)
counts = Counter(r["label"] for r in records)
h = counts["hallucination"]
answered = n - counts["correct_abstain"] - counts["over_refusal"]
lo, hi = wilson(h, n)
return {"n": n, "counts": counts, "hallucination": h, "rate": h / n if n else 0.0,
"ci": (lo, hi), "answered": answered,
"rate_answered": h / answered if answered else 0.0}
def by_category(records):
groups = defaultdict(list)
for r in records:
groups[r["category"]].append(r)
return {c: summarize(rs) for c, rs in groups.items()}
def markdown(runs):
"""runs: {(model, prompt): [records]}"""
lines = ["| Model | Prompt | Items | Halluc. | Rate | 95% CI | Over-refusal | Correct | Errors |",
"|---|---|---|---|---|---|---|---|---|"]
for (model, prompt), recs in runs.items():
s = summarize(recs)
c = s["counts"]
lines.append(
f"| {model} | {prompt} | {s['n']} | {s['hallucination']} | {s['rate']:.1%} | "
f"{s['ci'][0]:.1%}-{s['ci'][1]:.1%} | {c['over_refusal']} | {c['correct']} | "
f"{c['api_error'] + c['format_error']} |"
)
lines += ["", "| Model | Prompt | " + " | ".join(["answerable", "unanswerable", "false_premise", "fabricated_entity"]) + " |",
"|---|---|---|---|---|---|"]
for (model, prompt), recs in runs.items():
cats = by_category(recs)
cells = []
for c in ["answerable", "unanswerable", "false_premise", "fabricated_entity"]:
s = cats.get(c)
cells.append(f"{s['hallucination']}/{s['n']}" if s else "-")
lines.append(f"| {model} | {prompt} | " + " | ".join(cells) + " |")
return "\n".join(lines)
python
import argparse
import json
import os
import sys
from pathlib import Path
from .models import build_model
from .report import markdown, summarize
from .runner import Cache, run_all
from .selfcheck import agreement
from .stats import paired_bootstrap
def main(argv=None):
ap = argparse.ArgumentParser(prog="halluclab")
ap.add_argument("--corpus", default="data/corpus.json")
ap.add_argument("--models", default="mock-eager,mock-careful")
ap.add_argument("--prompts", default="baseline,strict")
ap.add_argument("--out", default="runs")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--gate", type=float, default=None, help="fail if the CI upper bound exceeds this rate")
ap.add_argument("--selfcheck", action="store_true")
args = ap.parse_args(argv)
corpus = json.loads(Path(args.corpus).read_text())
docs, items = corpus["docs"], corpus["items"]
out = Path(args.out)
out.mkdir(exist_ok=True)
cache = Cache(out / "cache.jsonl")
env = {"BASE_URL": os.environ.get("BASE_URL", ""), "API_KEY": os.environ.get("API_KEY", "")}
runs = {}
for spec in args.models.split(","):
model = build_model(spec.strip(), env)
for prompt in args.prompts.split(","):
recs = run_all(model, prompt.strip(), items, docs, cache, workers=args.workers)
runs[(model.id, prompt.strip())] = recs
with (out / f"{model.id}.{prompt.strip()}.jsonl").open("w") as f:
for r in recs:
f.write(json.dumps(r) + "\n")
report = markdown(runs)
(out / "report.md").write_text(report + "\n")
print(report)
for model_id in {m for m, _ in runs}:
if ("baseline" in args.prompts) and ("strict" in args.prompts):
a = [int(r["label"] == "hallucination") for r in runs[(model_id, "baseline")]]
b = [int(r["label"] == "hallucination") for r in runs[(model_id, "strict")]]
lo, hi = paired_bootstrap(a, b)
print(f"\n{model_id}: baseline minus strict hallucination rate, 95% CI [{lo:+.3f}, {hi:+.3f}]")
if args.selfcheck:
print()
for spec in args.models.split(","):
model = build_model(spec.strip(), env)
flagged = {"hallucination": [], "other": []}
for rec, item in zip(runs[(model.id, "baseline")], items):
score = agreement(model, "baseline", item, docs)
flagged["hallucination" if rec["label"] == "hallucination" else "other"].append(score)
for k, v in flagged.items():
if v:
print(f"{model.id} self-agreement ({k}, n={len(v)}): {sum(v)/len(v):.2f}")
if args.gate is not None:
for key, recs in runs.items():
c = summarize(recs)["counts"]
bad = c["api_error"] + c["format_error"]
if bad > 0.05 * len(recs):
print(f"\nGATE FAILED: {key} has {bad} of {len(recs)} unusable replies")
return 1
worst = max(summarize(r)["ci"][1] for r in runs.values())
if worst > args.gate:
print(f"\nGATE FAILED: worst upper bound {worst:.1%} > {args.gate:.1%}")
return 1
print(f"\nGATE PASSED: worst upper bound {worst:.1%} <= {args.gate:.1%}")
return 0
if __name__ == "__main__":
sys.exit(main())
Step 10: Run the AI Hallucination Test and Read the Output #
From the project root, run the harness with both mock models and both prompts. The first call finishes in seconds, and later calls hit the cache.
python3 -m halluclab
You should see two tables and two paired-bootstrap lines. These numbers come from a real run of the code above.
| Model | Prompt | Items | Halluc. | Rate | 95% CI | Over-refusal | Correct | Errors |
|---|---|---|---|---|---|---|---|---|
| mock-eager | baseline | 26 | 7 | 26.9% | 13.7%-46.1% | 0 | 16 | 0 |
| mock-eager | strict | 26 | 0 | 0.0% | 0.0%-12.9% | 1 | 15 | 0 |
| mock-careful | baseline | 26 | 8 | 30.8% | 16.5%-50.0% | 0 | 13 | 0 |
| mock-careful | strict | 26 | 4 | 15.4% | 6.1%-33.5% | 4 | 10 | 0 |
| Model | Prompt | answerable | unanswerable | false_premise | fabricated_entity |
|---|---|---|---|---|---|
| mock-eager | baseline | 0/12 | 4/6 | 0/4 | 3/4 |
| mock-eager | strict | 0/12 | 0/6 | 0/4 | 0/4 |
| mock-careful | baseline | 0/12 | 3/6 | 2/4 | 3/4 |
| mock-careful | strict | 0/12 | 2/6 | 1/4 | 1/4 |
mock-careful: baseline minus strict hallucination rate, 95% CI [-0.038, +0.346]
mock-eager: baseline minus strict hallucination rate, 95% CI [+0.115, +0.462]
Read the category table
Every hallucination in this run sits in the unanswerable, false-premise and fabricated-entity columns. The answerable column shows 0 of 12 for every row, so the mocks read documents fine and invent facts only when the document has no answer. Real models can also fail on answerable questions, which is why the category split exists.
Read the confidence intervals
The mock-eager baseline row says 7 of 26, or 26.9%, with a wide interval around that figure. The strict row says 0 of 26, yet its upper bound is still 12.9%. With only 26 items you can say the strict prompt looks better here, but you cannot claim a true rate of zero.
Read the reasons
Each record keeps the reasons the verifier fired. Question U01 asks about bereavement leave, which the document never mentions, and the baseline mock answered anyway.
U01 hallucination ['evidence_not_in_source', 'unsupported_number:32', 'answered_unanswerable']
F02 hallucination ['evidence_not_in_source', 'unsupported_entity:Priya,Raman', 'answered_unanswerable']
P01 hallucination ['evidence_not_in_source', 'unsupported_number:8', 'premise_accepted']
Three different failure shapes appear: an invented number, an invented name, and a false premise echoed back with doctored evidence. Reading these reasons shows which fix to try next, such as a stricter abstain rule or an entity check in production.
Step 11: Compare Prompts With a Paired Bootstrap #
The last two lines of the output answer the question teams actually ask: did the stricter prompt help? For mock-eager the baseline-minus-strict difference has a 95% interval of +0.115 to +0.462. The interval excludes zero, so the improvement is real at this sample size. For mock-careful the interval runs from -0.038 to +0.346. It includes zero, so 8 hallucinations dropping to 4 does not yet count as proof.
Look at the cost side before shipping the strict prompt. On mock-careful, strict mode produced 4 over-refusals (questions A03, A04, A07 and A10) against none at baseline, while mock-eager produced 1. A prompt that trades 4 invented answers for 4 unnecessary refusals may suit a legal tool and annoy users of a casual assistant.
Run the same command with the self-consistency flag to add the instability signal from Step 8.
python3 -m halluclab --selfcheck
| Model | Prompt | Items | Halluc. | Rate | 95% CI | Over-refusal | Correct | Errors |
|---|---|---|---|---|---|---|---|---|
| mock-eager | baseline | 26 | 7 | 26.9% | 13.7%-46.1% | 0 | 16 | 0 |
| mock-eager | strict | 26 | 0 | 0.0% | 0.0%-12.9% | 1 | 15 | 0 |
| mock-careful | baseline | 26 | 8 | 30.8% | 16.5%-50.0% | 0 | 13 | 0 |
| mock-careful | strict | 26 | 4 | 15.4% | 6.1%-33.5% | 4 | 10 | 0 |
| Model | Prompt | answerable | unanswerable | false_premise | fabricated_entity |
|---|---|---|---|---|---|
| mock-eager | baseline | 0/12 | 4/6 | 0/4 | 3/4 |
| mock-eager | strict | 0/12 | 0/6 | 0/4 | 0/4 |
| mock-careful | baseline | 0/12 | 3/6 | 2/4 | 3/4 |
| mock-careful | strict | 0/12 | 2/6 | 1/4 | 1/4 |
mock-careful: baseline minus strict hallucination rate, 95% CI [-0.038, +0.346]
mock-eager: baseline minus strict hallucination rate, 95% CI [+0.115, +0.462]
mock-eager self-agreement (hallucination, n=7): 0.40
mock-eager self-agreement (other, n=19): 0.84
mock-careful self-agreement (hallucination, n=8): 0.62
mock-careful self-agreement (other, n=18): 0.90
For mock-eager, hallucinated answers agreed with their own resamples only 40% of the time, against 84% for the other answers. For mock-careful the gap is narrower. The signal helps as a screen but fails on a model that invents the same wrong fact every time, and it multiplies your call count by five.
This harness measures invention against a trusted document, not manipulation by a hostile one. If your documents can carry hidden instructions, pair this test with a separate adversarial corpus such as the one in a prompt injection test lab.
Step 12: Lock It In With Tests and a CI Gate #
Step 12 freezes the verifier’s behavior. The tests below cover the grounded answer, invented evidence, both abstention cases, an unanswerable question answered anyway, a false premise, broken JSON, fenced JSON and the interval math.
import json
from halluclab.stats import wilson
from halluclab.verify import judge, parse_reply
DOC = "Passwords must be at least 14 characters. Laptops are replaced every 4 years."
ANS = {"id": "T1", "category": "answerable", "question": "How many characters must a password have?", "gold": ["14"]}
UNA = {"id": "T2", "category": "unanswerable", "question": "How often are backups tested?", "gold": []}
PRE = {"id": "T3", "category": "false_premise", "question": "Why 20 characters?", "gold": ["14 characters"], "false_value": "20 characters"}
def reply(answer="", evidence=None, abstain=False):
return json.dumps({"answer": answer, "evidence": evidence or [], "abstain": abstain})
def test_grounded_answer_is_correct():
s = "Passwords must be at least 14 characters."
assert judge(ANS, DOC, reply(s, [s])).label == "correct"
def test_invented_evidence_is_hallucination():
s = "Passwords must be at least 16 characters."
v = judge(ANS, DOC, reply(s, [s]))
assert v.label == "hallucination"
assert "evidence_not_in_source" in v.reasons
def test_abstaining_on_unanswerable_is_correct():
assert judge(UNA, DOC, reply(abstain=True)).label == "correct_abstain"
def test_abstaining_on_answerable_is_over_refusal():
assert judge(ANS, DOC, reply(abstain=True)).label == "over_refusal"
def test_answering_unanswerable_is_hallucination():
s = "Backups are tested every 30 days."
assert judge(UNA, DOC, reply(s, [s])).label == "hallucination"
def test_false_premise_accepted():
s = "Passwords must be at least 20 characters."
v = judge(PRE, DOC, reply(s, [s]))
assert "premise_accepted" in v.reasons
def test_bad_json_is_format_error():
assert judge(ANS, DOC, "sure, it is 14").label == "format_error"
def test_fenced_json_parses():
assert parse_reply("``` json\n" + reply("x", ["y"]) + "\n```")["answer"] == "x"
def test_wilson_bounds():
lo, hi = wilson(0, 26)
assert lo == 0.0 and 0.1 < hi < 0.2
python3 -m pytest -q
......... [100%]
9 passed in 0.02s
Then wire the gate into CI. The script below runs the tests, evaluates the strict prompt on whichever models you list in MODELS, and exits with status 1 when the worst upper bound exceeds 15 percent.
#!/bin/sh
set -e
python3 -m pytest -q
python3 -m halluclab --models "${MODELS:-mock-eager}" --prompts strict --gate 0.15
With mock-eager the gate passes, and with mock-careful it fails. Both outputs below are real.
$ MODELS=mock-eager ./ci.sh
GATE PASSED: worst upper bound 12.9% <= 15.0%
$ MODELS=mock-careful ./ci.sh
GATE FAILED: worst upper bound 33.5% > 15.0%
To test a real model, export BASE_URL and API_KEY for a chat completions endpoint, then pass --models http:MODEL_ID using the exact identifier your vendor lists. Store the identifier and the date with the report every time.
Common Pitfalls That Skew Hallucination Rates #
Each of these can produce a misleading number without any error message.
- The zero-percent trap. We hit this while building the project. With
BASE_URLempty, all 26 calls failed, and the first version of the report showed 0.0% hallucination. A model that never answers never hallucinates. Count unusable replies beside the rate and fail the gate when more than 5 percent of replies are errors. - The wrong denominator. For mock-eager at baseline, 7 of 26 questions is 26.9%, but 7 of the 23 questions it answered is 30.4%. Neither figure is wrong. Publish both and say which one you gate on.
- Contaminated test documents. Public handbooks, wikis and manuals sit in training data, so a model can answer correctly from memory and hide a grounding failure. Use private or invented documents.
- Mutable model aliases. OpenAI documents
chat-latestas a moving pointer. A run on Monday and a run on Friday may hit different models. Pin an identifier and record the date. - Tiny samples read as truth. Seven hallucinations in 26 items leaves a very wide interval. A two-point improvement between prompts is noise. Grow the corpus to a few hundred items before you celebrate.
- Rewarding refusals. Lowering hallucinations by refusing more is a trade, not a win. Always read the over-refusal column beside the hallucination column.
- Judge bias and checker false positives. Number words and paraphrases trip a deterministic checker, while a judge from the same model family may favor its own phrasing. Spot-check 20 labeled records by hand each time you change either one.
Troubleshooting: 10 Fixes for Failed or Odd Runs #
- Every record is api_error with unknown url type.
BASE_URLis empty or lacks the scheme. We reproduced this exact message:unknown url type: '/chat/completions'. Export a full URL such as one starting with https. - HTTP 400 mentioning temperature. Some endpoints reject sampling parameters on certain models. Pass
temperature=NoneinHttpChatModel.generateso the field is omitted. - HTTP 401 or 403. The key is wrong, expired or scoped to a different project. Test it with a one-line curl call before running 26 items.
- HTTP 429. You are rate limited. Lower
--workersto 1 or 2. The cache keeps finished items, so the rerun picks up where it stopped. - Many format_error verdicts. The model wrapped JSON in prose or returned extra keys. The parser already strips code fences and extracts the first object. If errors persist, print the raw reply and tighten the system prompt.
- Every answer flagged evidence_not_in_source. The model altered quotes, for example with curly apostrophes or an ellipsis. Normalize punctuation in
norm()or ask for shorter evidence spans. - Correct answers flagged unsupported_number. The model converted units or spelled out a number. Add an allow-list field to the item, or compare numeric values after conversion.
- Results change between runs. You changed a prompt, a model alias or the corpus, so the cache key changed. Delete
runs/cache.jsonlonly when you want fresh calls, and store model identifiers with each report. - ModuleNotFoundError: halluclab. Run commands from the project root and invoke tools as
python3 -m halluclabandpython3 -m pytest. - JSONDecodeError while the cache. A crash cut the last line short. Delete that final line from
cache.jsonland rerun.
Advanced Tips and Which Models to Point It At #
Point the harness at the newest models first. These are the current entries from official announcements and pricing pages as of November 26, 2026.
| Model | Vendor | Announced | Input / output per million tokens |
|---|---|---|---|
| GPT-6.2 Astra | OpenAI | Nov 17, 2026 | $8 / $40 |
| GPT-6.2 Sol | OpenAI | Nov 17, 2026 | $2 / $10 |
| Claude Fable 5.2 and Mythos 5.2 | Anthropic | Nov 9, 2026 | $8 / $40 |
| Gemini 4 Neon | Nov 18, 2026 | $3 / $15 (cached input $0.15, 1M-token context) | |
| Gemini 4 Hydrogen | November 2026 | $1.50 / $7.50 (1M-token context) |
A rough cost check keeps you honest. Assume 400 input tokens and 80 output tokens per call, which is our estimate and not a measured figure. At the listed prices of $2 and $10 per million input and output tokens for GPT-6.2 Sol, and $8 and $40 for GPT-6.2 Astra, one pass over 26 items comes to roughly $0.04 on Sol and roughly $0.17 on Astra. Scaling to 300 items multiplies those figures by about 11.5, which keeps a Sol pass under a dollar and an Astra pass under $2.
Sample size deserves the same attention as cost. A result of zero hallucinations has an upper bound of 12.9% at 26 items, 3.7% at 100 items and 1.3% at 300 items. If your acceptance threshold is 2 percent, you need roughly 190 clean items before the data supports the claim.
Add a judge layer only after the deterministic checks run clean. According to Unique AI’s documentation, its judge-model hallucination checks average about 5 seconds each and are estimated at $134 per benchmark run, which shows that judge costs scale with corpus size and judge choice. Observability platforms from the LLM evaluation platform roundup at TrueFoundry, including Braintrust, Langfuse, Arize Phoenix and LangSmith, can store traces and scores, so you do not need to build a dashboard. For broad capability suites, EleutherAI’s lm-evaluation-harness is a framework for few-shot evaluation of language models. It measures general ability, not grounding against your documents.
Finally, use the output. If a cheap model abstains too often on answerable questions, escalate those items to a stronger model, the pattern behind an LLM router that sends hard requests to a stronger model. Stratify the corpus by document type, keep an as-of date on each item, and rerun the harness on every model or prompt change.
FAQ #
What is an AI hallucination?
An AI hallucination is a model output that states something the source material does not support, such as an invented number, name, quote or policy. This harness separates it from a grounded answer that is merely wrong.
What is a good AI hallucination rate?
No universal threshold exists. A brainstorming tool tolerates more invention than a contract summarizer. Set the limit from the cost of one wrong answer, then test it with enough items for the interval to fit under it.
Can I run this without an API key?
Yes. The mock-eager and mock-careful models run offline and produce the outputs shown above. Add an http: model spec when you are ready to test a real endpoint.
How many questions do I need?
It depends on the threshold you must prove. Zero hallucinations in 26 items still allows a true rate up to 12.9%. At 100 items the bound falls to 3.7%, and at 300 items to 1.3%.
Does retrieval-augmented generation remove hallucinations?
It reduces them but does not remove them. A model can still ignore the retrieved text, invent details around it or answer a question the passage does not cover. This harness tests that grounded setting directly.
Which model hallucinates the least?
The sources we checked do not give a single verified, comparable ranking for the November 2026 models. Test the models you can afford on your own documents and compare the intervals.
Why not rely on an LLM judge alone?
A judge adds cost, latency and its own bias, and you must validate it against human labels. Deterministic checks give a repeatable floor, and a judge handles the paraphrases they cannot.