Most hallucination content on the internet is about chatbots saying wrong things: a fake citation, an invented statistic, an API method that doesn't exist.
That's a real problem. But once your model can call tools, it's no longer the worst one.
Consider these two failures:
Agent: "Our refund window is 60 days." # policy says 30
Agent → refund_order(order_id="ORD-44718", amount=82.00)
# ORD-44718 never appeared anywhere in the conversation.
# It belongs to a different customer.
The first gives a user wrong information. The second moves real money to the wrong place. And the second one is, conveniently, much easier to catch. You don't need a judge model or a research paper. You need the trace and about forty lines of Python.
This is Part 1 of a two-part series:
- Part 1 (this post): action and outcome hallucinations, and the cheap checks that run on every request
- Part 2: content hallucinations, judge models, semantic entropy, and a layered production pipeline
Three kinds of agent hallucination
This breakdown of hallucination detection for production agents splits agent hallucinations into three types, and the split is the key to detecting them cheaply:
| Type | What it looks like | Example | Damage |
|---|---|---|---|
| Content | A claim not supported by sources | "Refund window is 60 days" (policy says 30) | User gets wrong info |
| Action | An invented tool, argument or value |
refund_order with an ID that appears nowhere earlier |
A real action on the wrong thing |
| Outcome | Saying something happened when it didn't | "I've cancelled your subscription" with no cancel call | User thinks the problem is solved |
Content hallucinations need semantic judgment, which is expensive (that's Part 2).
Action and outcome hallucinations are structural. They leave evidence in the trace: an argument with no origin, a claim with no matching tool call. Structural problems get structural checks, and structural checks cost almost nothing.
Check 1: Argument provenance
The idea: every ID, amount or identifier passed into a write tool should have come from somewhere earlier in the trace: the user's message, a tool result, or retrieved context. If it didn't, the model typed it from thin air.
import re
from dataclasses import dataclass
# Things that should never be invented
IDENTIFIER_PATTERNS = {
"order_id": re.compile(r"\bORD-\d{5,}\b"),
"account_id": re.compile(r"\bACC-[A-Z0-9]{6,}\b"),
"email": re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+"),
}
@dataclass
class ProvenanceIssue:
tool: str
arg: str
value: str
def seen_values(spans: list[dict]) -> str:
"""Concatenate everything the agent legitimately saw before acting."""
parts = []
for s in spans:
a = s["attributes"]
for key in ("app.user_message", "app.tool.response", "app.retrieved_context"):
if key in a:
parts.append(str(a[key]))
return "\n".join(parts)
def check_provenance(spans: list[dict], write_tools: set[str]) -> list[ProvenanceIssue]:
issues = []
for i, s in enumerate(spans):
a = s["attributes"]
tool = a.get("gen_ai.tool.name")
if tool not in write_tools:
continue
history = seen_values(spans[:i]) # only what came BEFORE this call
for arg, value in a.get("app.tool.args_dict", {}).items():
value = str(value)
is_identifier = any(p.fullmatch(value) for p in IDENTIFIER_PATTERNS.values())
if is_identifier and value not in history:
issues.append(ProvenanceIssue(tool, arg, value))
return issues
Running it on the trace from the intro:
>>> check_provenance(spans, write_tools={"refund_order", "cancel_subscription", "send_email"})
[ProvenanceIssue(tool='refund_order', arg='order_id', value='ORD-44718')]
A few details that matter:
-
Only look backwards.
spans[:i]means the value must appear before the tool call. An ID that shows up later (say, in the tool's own response) doesn't count. - Focus on write tools. Read-only lookups with a bad ID usually just fail. Write tools are where invented arguments cause damage.
-
Amounts need care.
82.00vs82vs$82is a normalisation problem. For money, compare against parsed numeric values from earlier spans, and flag any amount that doesn't match one.
def amounts_in(text: str) -> set[float]:
return {float(m.replace(",", "")) for m in re.findall(r"\$?(\d[\d,]*\.?\d*)", text)}
def check_amount(value: float, history: str, tolerance=0.01) -> bool:
return any(abs(value - seen) <= tolerance for seen in amounts_in(history))
Run it as a guardrail before the tool executes, not just as a post-hoc check. Then a provenance failure blocks the action instead of just logging it.
Check 2: Claim vs. trace
The idea: compare what the agent says it did in its final reply with what the trace shows it actually did.
A regex lookup table works as a first pass, but it misses paraphrases ("all sorted, you won't be charged next month" is a cancellation claim). A sturdier approach: have a small, cheap model extract structured claims, then match them deterministically.
import json
EXTRACT_PROMPT = """List every action the assistant claims to have COMPLETED in
the message below. Return only JSON: a list of objects with keys
"action" (one of: refund, cancel_subscription, send_email, reset_password,
update_address, none) and "target" (the ID or email mentioned, or null).
Message:
{reply}"""
ACTION_TO_TOOL = {
"refund": "refund_order",
"cancel_subscription": "cancel_subscription",
"send_email": "send_email",
"reset_password": "reset_password",
"update_address": "update_address",
}
def extract_claims(reply: str, small_model) -> list[dict]:
raw = small_model.complete(EXTRACT_PROMPT.format(reply=reply))
try:
return [c for c in json.loads(raw) if c["action"] != "none"]
except (json.JSONDecodeError, KeyError, TypeError):
return [{"action": "unparseable", "target": None}]
def successful_calls(spans: list[dict]) -> list[dict]:
return [
{"tool": s["attributes"]["gen_ai.tool.name"],
"args": s["attributes"].get("app.tool.args_dict", {})}
for s in spans
if s["attributes"].get("gen_ai.operation.name") == "execute_tool"
and s["status"] == "OK"
]
def outcome_hallucinations(reply: str, spans: list[dict], small_model) -> list[dict]:
calls = successful_calls(spans)
problems = []
for claim in extract_claims(reply, small_model):
tool = ACTION_TO_TOOL.get(claim["action"])
matching = [c for c in calls if c["tool"] == tool]
if not matching:
problems.append({**claim, "reason": "no successful tool call"})
elif claim["target"] and not any(claim["target"] in map(str, c["args"].values())
for c in matching):
problems.append({**claim, "reason": "tool called on a different target"})
return problems
reply: "Done! I've cancelled your subscription and emailed you a confirmation."
>>> outcome_hallucinations(reply, spans, small_model)
[{'action': 'send_email', 'target': None, 'reason': 'no successful tool call'}]
The cancellation was real. The confirmation email wasn't. The user will now wait for an email that never comes, then contact support, annoyed.
Notes:
-
Only count successful calls. A tool that was called and errored didn't do anything. Filtering on
status == "OK"is what catches "I've refunded you" after the payment API returned a 500. - Check the target, not just the tool. "I've refunded order 4471" when the refund went to 4417 is an outcome hallucination too.
- The extractor is a small model on a narrow task. Cheap, fast, and easy to test. You're not asking it to judge truth, only to list claims.
Check 3: Rule-based output validation
The boring one, and it still catches a lot. Validate formats, schemas and value ranges on every tool argument and every structured output.
from pydantic import BaseModel, Field, field_validator
from typing import Literal
class RefundArgs(BaseModel):
order_id: str = Field(pattern=r"^ORD-\d{5,}$")
amount: float = Field(gt=0, le=500)
reason: Literal["damaged", "not_received", "wrong_item", "other"]
@field_validator("order_id")
@classmethod
def must_exist_and_belong(cls, v, info):
order = orders.get(v)
if order is None:
raise ValueError("order does not exist")
if order.customer_id != info.context["customer_id"]:
raise ValueError("order belongs to a different customer")
return v
Enums are underrated here. If reason can only be one of four values, the model can't invent a fifth.
Prevention beats detection: three design patterns
Detection tells you how often action and outcome hallucinations happen. These patterns make them happen less:
1. Let the agent pick, not type
Don't let the model type IDs from memory. Have it select from tool results.
# Instead of: refund_order(order_id: str)
# Give it: refund_order(order_ref: int) -- an index into the last lookup result
def refund_order(order_ref: int, amount: float, ctx):
order = ctx.last_lookup_results[order_ref] # the model can only point at real rows
return payments.refund(order.id, amount)
2. Confirm before acting
For high-impact actions, have the agent restate the target, then check the restatement against the trace before the tool runs.
Agent (internal): CONFIRM refund order=ORD-44171 amount=82.00
Guardrail: ORD-44171 seen in lookup_orders response ✅ amount matches line total ✅
→ execute
3. Build the reply from tool results
The surest way to make claims match actions: generate the final message from tool results, not from the model's plan.
def final_reply(calls: list[dict], llm) -> str:
facts = [
f"- {c['tool']} succeeded with {c['args']}" for c in calls
] or ["- No actions were completed."]
return llm.complete(
"Write a short, friendly reply to the customer. Mention ONLY the actions "
"listed below as completed. Do not claim anything else was done.\n\n"
+ "\n".join(facts)
)
It's still worth running claim vs. trace on the output; this just shrinks the gap.
Where these checks sit
All three checks are near-zero cost, so they run on every request:
tool call requested
├─ schema / enum validation ← block on failure
├─ argument provenance ← block on failure (write tools)
└─ execute tool
final reply drafted
└─ claim vs. trace ← flag, or regenerate reply from tool results
Tie every flag to its trace, so whoever investigates can see which step produced the invented value. For more on structuring those traces, see this guide to AI agent observability.
TL;DR
- Agents hallucinate content, actions and outcomes. The last two touch real systems.
- Action and outcome hallucinations are structural, so they're cheap to catch on every run.
- Argument provenance: every ID and amount in a write tool must appear earlier in the trace.
- Claim vs. trace: every action the reply claims must match a successful tool call on the right target.
- Prevent them by design: pick don't type, confirm before acting, build replies from tool results.
In Part 2, we'll tackle the harder kind: content hallucinations. We'll build a groundedness judge, calibrate it against human labels, implement semantic entropy, and wire everything into a cost-layered pipeline, following the layered approach in this guide to detecting hallucinations in AI agents.
Has an agent of yours ever confidently "done" something it never did? How did you find out? 👻
Post 2
markdown
title: "Detecting Content Hallucinations in Production: Groundedness Judges, Semantic Entropy and a Layered Pipeline"
published: false
description: "Judge models, consistency sampling and semantic entropy, implemented in Python, plus how to calibrate a judge against human labels and route traffic so expensive detectors only run where they matter."
tags: ai, llm, python, machinelearning
canonical_url: https://www.botgauge.com/blog/hallucination-detection
In Part 1 we caught the structural hallucinations: invented tool arguments and claims of actions that never happened. Those leave fingerprints in the trace, so cheap deterministic checks find them.
Content hallucinations don't leave fingerprints.
Context retrieved: "Refunds are available within 30 days of delivery."
Agent reply: "No problem! Our refund window is 60 days, so you're covered."
The trace looks fine. A retrieval happened, a model call happened, a reply went out. Nothing structural is wrong. The only way to know the reply is false is to compare its meaning against the evidence, and that takes a model.
This post covers:
- A groundedness judge that checks each claim against retrieved context
- How to calibrate that judge against human labels (skip this and your scores are fiction)
- Consistency sampling and semantic entropy for catching confabulation
- A layered pipeline that runs cheap checks everywhere and expensive ones only where needed
- Turning every confirmed hallucination into a regression test
Detection vs. prevention
Quick framing first. Prevention tries to stop hallucinations happening: better retrieval, better prompts, guardrails. Detection assumes some will slip through and catches them before or soon after they reach a user.
You need both, but they're different jobs. This post is about detection: getting hallucinations onto a dashboard instead of into a customer complaint.
Method 1: The groundedness judge
Judge models are the production workhorse for content hallucinations, and for a good reason: they work without a reference answer. They check the output against the input and context already recorded on the trace.
The trick is to not ask "is this answer grounded?" in one shot. Break the answer into atomic claims and judge each one. You get more consistent scores, and you get which claim failed.
import json
JUDGE_PROMPT = """You are checking an AI assistant's answer against the context
it was given. Do not use outside knowledge.
1. Split the ANSWER into short, atomic factual claims.
2. For each claim, decide:
- "supported": the CONTEXT states or directly implies it
- "contradicted": the CONTEXT says something incompatible
- "unsupported": the CONTEXT does not address it
Return only JSON:
{{"claims": [{{"claim": "...", "verdict": "supported|contradicted|unsupported",
"evidence": "quote from context or null"}}]}}
CONTEXT:
{context}
ANSWER:
{answer}"""
def judge_groundedness(answer: str, context: str, judge) -> dict:
raw = judge.complete(JUDGE_PROMPT.format(context=context, answer=answer))
claims = json.loads(raw)["claims"]
n = len(claims) or 1
return {
"claims": claims,
"groundedness": sum(c["verdict"] == "supported" for c in claims) / n,
"has_contradiction": any(c["verdict"] == "contradicted" for c in claims),
}
>>> judge_groundedness(reply, context, judge)
{'claims': [
{'claim': 'The refund window is 60 days', 'verdict': 'contradicted',
'evidence': 'Refunds are available within 30 days of delivery.'},
{'claim': 'The customer is covered', 'verdict': 'unsupported', 'evidence': None}],
'groundedness': 0.0,
'has_contradiction': True}
Treat contradicted and unsupported differently. A contradiction is almost always a real problem. "Unsupported" can be harmless filler ("Happy to help!") or a genuine invention, so it needs a looser threshold.
Calibrate the judge, or don't trust it
Judges are only as good as their prompt and calibration. They can be lenient, inconsistent, or biased toward long answers. Before you put a judge's score on a dashboard, check it against human labels.
Collect 100–200 real traces, have someone who knows the domain label each as grounded / hallucinated, then measure agreement:
from sklearn.metrics import precision_score, recall_score, cohen_kappa_score
def calibrate(examples: list[dict], judge, threshold=0.8) -> dict:
human, model = [], []
for ex in examples:
r = judge_groundedness(ex["answer"], ex["context"], judge)
flagged = r["has_contradiction"] or r["groundedness"] < threshold
model.append(int(flagged))
human.append(int(ex["human_label"] == "hallucinated"))
return {
"precision": precision_score(human, model), # of flags, how many are real
"recall": recall_score(human, model), # of real ones, how many caught
"kappa": cohen_kappa_score(human, model), # agreement beyond chance
}
for t in (0.6, 0.7, 0.8, 0.9):
print(t, calibrate(labelled_set, judge, threshold=t))
0.6 {'precision': 0.91, 'recall': 0.58, 'kappa': 0.63}
0.7 {'precision': 0.87, 'recall': 0.71, 'kappa': 0.72}
0.8 {'precision': 0.79, 'recall': 0.83, 'kappa': 0.74}
0.9 {'precision': 0.62, 'recall': 0.90, 'kappa': 0.61}
(Illustrative numbers. Yours will differ, which is the point of running it.)
Pick the threshold based on cost: for refund or medical answers you probably want recall; for low-stakes FAQ answers, precision keeps alert fatigue down. Rerun calibration whenever you change the judge model or prompt, and keep feeding it new human labels from the review queue.
Method 2: Consistency sampling
If a model actually knows something, it tends to give the same answer when asked repeatedly. If it's making something up, the answers wander.
def consistency(question: str, context: str, llm, n=5, temperature=0.8) -> float:
answers = [llm.complete(question, context=context, temperature=temperature)
for _ in range(n)]
# naive version: exact-match agreement with the most common answer
from collections import Counter
top_count = Counter(a.strip().lower() for a in answers).most_common(1)[0][1]
return top_count / n
The naive version has an obvious flaw: "30 days" and "You have thirty days to request a refund" are the same answer in different words. Exact matching calls them a disagreement. Which brings us to the better version.
Method 3: Semantic entropy
Semantic entropy comes from Oxford researchers, published in Nature in 2024 (Farquhar et al.). The idea:
- Ask the model the same question several times
- Group the answers by meaning, not wording
- Measure how spread out those meaning-groups are
If all samples land in one meaning cluster, entropy is low and the model is probably on solid ground. If they scatter across many clusters, entropy is high and the model is likely confabulating: producing arbitrary, wrong answers. Notably, the method worked across tasks without task-specific training data.
Grouping by meaning uses bidirectional entailment: two answers belong together if each one implies the other. An off-the-shelf NLI model can decide that.
import math
from transformers import pipeline
nli = pipeline("text-classification", model="microsoft/deberta-large-mnli")
def entails(a: str, b: str, question: str) -> bool:
out = nli({"text": f"{question} {a}", "text_pair": f"{question} {b}"})
label = out[0]["label"] if isinstance(out, list) else out["label"]
return label.upper() == "ENTAILMENT"
def cluster_by_meaning(answers: list[str], question: str) -> list[list[str]]:
clusters: list[list[str]] = []
for ans in answers:
for c in clusters:
rep = c[0]
if entails(ans, rep, question) and entails(rep, ans, question):
c.append(ans)
break
else:
clusters.append([ans])
return clusters
def semantic_entropy(question: str, context: str, llm, n=10) -> float:
answers = [llm.complete(question, context=context, temperature=1.0) for _ in range(n)]
clusters = cluster_by_meaning(answers, question)
probs = [len(c) / n for c in clusters]
return -sum(p * math.log(p) for p in probs)
"What is the refund window?" → 1 cluster → entropy 0.00
"Who approved the 2019 pricing change?" → 6 clusters → entropy 1.70 ⚠️
This is the discrete version (counting samples per cluster); the paper also describes a variant using token probabilities.
The catch: it needs many generations per question, plus pairwise NLI calls. That makes it a poor fit for every live request. Use it offline on test sets, and on the questions that produce the most flags, to find the topics where your agent is least reliable.
Putting it together: a layered pipeline
No single method catches everything. Run detectors in order of cost, so the cheap ones filter traffic for the expensive ones.
| Layer | Runs on | Methods | Cost |
|---|---|---|---|
| 1 | Every run | Rules, argument provenance, claim vs. trace (Part 1) | ~0 |
| 2 | A steady sample (e.g. 5–10%) | Groundedness judge | 1 model call |
| 3 | Every high-risk answer | Groundedness judge, always | 1 model call |
| 4 | Flagged or low-confidence | Human review | High |
| 5 | Offline / top-flagged topics | Consistency sampling, semantic entropy | Many calls |
As a router:
import random
HIGH_RISK_TASKS = {"refund", "billing", "medical", "legal", "account_change"}
def detect(run, judge, sample_rate=0.07):
flags = []
# Layer 1: structural checks, every run
flags += check_provenance(run.spans, WRITE_TOOLS)
flags += outcome_hallucinations(run.reply, run.spans, small_model)
# Layers 2 + 3: judge on a sample, or always for high-risk
if run.task_type in HIGH_RISK_TASKS or random.random() < sample_rate:
g = judge_groundedness(run.reply, run.context, judge)
record_metric("groundedness", g["groundedness"], task_type=run.task_type)
if g["has_contradiction"] or g["groundedness"] < THRESHOLDS[run.task_type]:
flags.append({"type": "content", **g})
# Layer 4: route to humans
if flags:
review_queue.put({"trace_id": run.trace_id, "flags": flags})
return flags
Two habits make this useful:
- Track groundedness over time, split by task type. A blended average hides the one flow that's quietly getting worse.
- Tie every flag to its trace. The investigator should see which retrieval, tool result or step led to the false claim, not just the bad sentence.
Turn every detection into a test
Every confirmed hallucination is a ready-made test case: the input, the context the agent had, and the wrong output.
def to_regression_case(trace, reviewer_note: str) -> dict:
return {
"id": f"HALL-{trace.trace_id[:8]}",
"input": trace.user_message,
"context": trace.context,
"bad_output": trace.reply,
"must_not_claim": reviewer_note, # e.g. "refund window is 60 days"
"check": "groundedness >= 0.8 and not has_contradiction",
"source": "production",
}
Add it to your regression set and rerun the set on every model, prompt and retrieval change, so the same failure can't come back unnoticed. This is where hallucination detection turns into evals.
Reducing content hallucinations
Detection measures the problem. These changes shrink it:
- Fix retrieval first. Many content hallucinations start with missing or irrelevant context. Track empty and low-relevance retrievals, and fix those before tuning prompts.
- Let the agent say "I don't know." Tell it to escalate or ask when the context doesn't contain the answer, and reward that in your evals, or it'll learn that guessing scores better.
- Test the edges on purpose. Hallucinations cluster around ambiguous requests, missing data, and users applying pressure ("my last agent said it was 60 days…"). Attack those edges before launch.
TL;DR
- Content hallucinations need semantic checks; there's no structural fingerprint.
- Use a claim-level groundedness judge, and calibrate it against human labels before trusting it.
- Semantic entropy catches confabulation by clustering sampled answers by meaning; run it offline or on hot spots.
- Layer by cost: structural checks on every run, judges on a sample plus all high-risk answers, humans on flags, deep methods offline.
- Every confirmed hallucination becomes a regression test.
That wraps the series. For the full method comparison table and the reduction checklist in one place, see this guide to hallucination detection methods for AI agents.
*Are you using a judge model in production yet? How did you decide whether to trust its sco
Top comments (0)