RAG Hallucination Detection
Catch a RAG pipeline inventing facts — evaluate every answer against the context it actually retrieved.
A RAG system is only as trustworthy as its grounding. When the retriever comes back empty or thin, a model will often fill the gap with a confident invention. In this cookbook you build a small RAG pipeline and have Prisma check every answer against the exact context it retrieved, so a fabricated claim is flagged automatically instead of slipping through.
What you'll build
A minimal RAG pipeline (OpenAI + ChromaDB) where each query emits one trace carrying the question, the generated answer, and the retrieved passages as the reference. Prisma's hallucination evaluator compares the answer to that reference; correctness checks it for accuracy. A deliberately unanswerable question shows the flag firing.
Before you start
- Python 3.10+, a Prisma API key (
pq_prisma_sk_…), and an OpenAI API key. PALQEE_PRISMA_API_KEY,PALQEE_PRISMA_BASE_URL, andOPENAI_API_KEYset — see Installation & Setup.
pip install palqee-prisma-ai openai chromadbchromadb is a local vector store; swap it for a managed one in production without changing the Prisma setup.
Step 1 — Build a knowledge base
Define the documents the retriever can surface. These are the system's source of truth — anything outside them is fair game for a hallucination.
DOCUMENTS = [
{"id": "hr-1", "text": "Acme Corp grants 20 days of paid time off per calendar year. Unused days do not carry over."},
{"id": "hr-2", "text": "Acme Corp employees become eligible for the 401(k) match after 90 days of employment."},
{"id": "sec-1", "text": "Acme Corp deletes all customer data within 90 days of account closure. Audit logs are retained for 7 years."},
{"id": "sec-2", "text": "Acme Corp requires multi-factor authentication for all internal systems handling customer data."},
{"id": "ops-1", "text": "Acme Corp's support team operates 24/7 and targets a first-response time of under one hour."},
]Step 2 — Index the documents
Embed and index them with ChromaDB so the retriever can find the most relevant passages per query.
import chromadb
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
embedding_fn = OpenAIEmbeddingFunction(model_name="text-embedding-3-small")
collection = chromadb.Client().create_collection(
name="knowledge_base",
embedding_function=embedding_fn,
)
collection.add(
ids=[d["id"] for d in DOCUMENTS],
documents=[d["text"] for d in DOCUMENTS],
)Step 3 — Retrieve and generate
Two stages: pull the top passages, then answer using only those. The system prompt tells the model to decline when the context falls short — a well-behaved pipeline obeys; this cookbook is about catching the times it doesn't.
from openai import OpenAI
oai = OpenAI()
SYSTEM_PROMPT = (
"Answer the question using ONLY the context below. If the context does not "
"contain the answer, say 'I don't have enough information to answer that.'\n\n"
"Context:\n{retrieved}"
)
def retrieve(query: str, k: int = 2) -> str:
results = collection.query(query_texts=[query], n_results=k)
return "\n\n".join(results["documents"][0])
def generate(query: str, retrieved: str) -> str:
completion = oai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT.format(retrieved=retrieved)},
{"role": "user", "content": query},
],
temperature=0.7,
)
return completion.choices[0].message.contentStep 4 — Send each answer to Prisma with its context
This is the crux. The hallucination evaluator checks the answer against a reference — and for RAG, the right reference is the context you actually retrieved. The raw LLM call doesn't carry that, so emit one span per query and set it yourself, using the OpenInference attribute names Prisma reads automatically:
input.value— the questionoutput.value— the generated answerinput.reference— the retrieved passages
import palqee_prisma_ai
from opentelemetry import trace
session = palqee_prisma_ai.init(
"rag-hallucination-detection",
run_name="cookbook-run",
evaluators=["hallucination", "correctness"],
)
tracer = trace.get_tracer("rag")
def answer(query: str) -> dict:
retrieved = retrieve(query)
response = generate(query, retrieved)
with tracer.start_as_current_span("rag-answer") as span:
span.set_attribute("input.value", query)
span.set_attribute("output.value", response)
span.set_attribute("input.reference", retrieved) # what to check against
return {"query": query, "retrieved": retrieved, "answer": response}Because the span uses the standard attribute names, traces map automatically — there's nothing to configure. (An input_mapping only applies to the batched-dataset path, not spans.)
Step 5 — Run it, including a question with no answer
The first two queries are answerable from the knowledge base; the third isn't. A grounded pipeline declines the third — if it instead invents an answer, hallucination flags it.
queries = [
"How many paid time off days do Acme employees get?",
"What is Acme Corp's data retention policy for customer data?",
"What is Acme Corp's pricing for enterprise customers?", # not in the KB
]
for q in queries:
result = answer(q)
print(f"Q: {result['query']}\nA: {result['answer']}\n{'-' * 60}")
session.end() # flush buffered spansThe third answer has no support in the retrieved context. With temperature=0.7 the model may invent a pricing tier — exactly the failure that's hard to catch by eye but that Prisma flags every time. LLM output is non-deterministic, so results vary run to run; that variability is the point of validating at full population.
Step 6 — Review results
Open the rag-hallucination-detection project and your run:
- Hallucination pass rate — share of answers grounded in the retrieved context. The invented pricing answer lands as
hallucinated; a correct decline passes. - Correctness pass rate — share factually accurate given the reference.
- Ambiguous — borderline cases queued for human review.
For regulated workflows this is an auditable record: every answer checked against its own source material, stored in your Prisma instance.
Complete script
"""RAG hallucination detection with Prisma — full copy-paste example."""
import chromadb
from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
from openai import OpenAI
from opentelemetry import trace
import palqee_prisma_ai
# -- 1. Knowledge base --------------------------------------------------------
DOCUMENTS = [
{"id": "hr-1", "text": "Acme Corp grants 20 days of paid time off per calendar year. Unused days do not carry over."},
{"id": "hr-2", "text": "Acme Corp employees become eligible for the 401(k) match after 90 days of employment."},
{"id": "sec-1", "text": "Acme Corp deletes all customer data within 90 days of account closure. Audit logs are retained for 7 years."},
{"id": "sec-2", "text": "Acme Corp requires multi-factor authentication for all internal systems handling customer data."},
{"id": "ops-1", "text": "Acme Corp's support team operates 24/7 and targets a first-response time of under one hour."},
]
# -- 2. Vector store ----------------------------------------------------------
embedding_fn = OpenAIEmbeddingFunction(model_name="text-embedding-3-small")
collection = chromadb.Client().create_collection(
name="knowledge_base", embedding_function=embedding_fn
)
collection.add(
ids=[d["id"] for d in DOCUMENTS],
documents=[d["text"] for d in DOCUMENTS],
)
# -- 3. RAG pipeline ----------------------------------------------------------
oai = OpenAI()
SYSTEM_PROMPT = (
"Answer the question using ONLY the context below. If the context does not "
"contain the answer, say 'I don't have enough information to answer that.'\n\n"
"Context:\n{retrieved}"
)
def retrieve(query: str, k: int = 2) -> str:
results = collection.query(query_texts=[query], n_results=k)
return "\n\n".join(results["documents"][0])
def generate(query: str, retrieved: str) -> str:
completion = oai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT.format(retrieved=retrieved)},
{"role": "user", "content": query},
],
temperature=0.7,
)
return completion.choices[0].message.content
# -- 4. Prisma: one span per answer, retrieved context as the reference --------
session = palqee_prisma_ai.init(
"rag-hallucination-detection",
run_name="cookbook-run",
evaluators=["hallucination", "correctness"],
)
tracer = trace.get_tracer("rag")
def answer(query: str) -> dict:
retrieved = retrieve(query)
response = generate(query, retrieved)
with tracer.start_as_current_span("rag-answer") as span:
span.set_attribute("input.value", query)
span.set_attribute("output.value", response)
span.set_attribute("input.reference", retrieved)
return {"query": query, "retrieved": retrieved, "answer": response}
# -- 5. Run -------------------------------------------------------------------
queries = [
"How many paid time off days do Acme employees get?",
"What is Acme Corp's data retention policy for customer data?",
"What is Acme Corp's pricing for enterprise customers?", # not in the KB
]
for q in queries:
result = answer(q)
print(f"Q: {result['query']}\nA: {result['answer']}\n{'-' * 60}")
session.end()Extend it
- Make the reference richer. Include passage IDs or scores alongside the text so reviewers can see which document an answer should have used.
- Add a policy metric. Layer a custom evaluator — e.g. "did the answer cite a source?" — on top of
hallucination. - Tighten retrieval. When hallucination spikes, the fix is often upstream: better chunking or more retrieved passages, not a different prompt.
Next steps
- Instrumentation & Tracing — custom spans and the attributes Prisma reads
- Policy Metrics — author your own checks
- Call Center QA — validate a batch of human-agent transcripts
Policy Compliance in CI/CD
Gate merges on AI quality — validate a golden dataset on every pull request and block compliance regressions before they ship.
Call Center QA
Validate a backlog of contact-center transcripts against correctness, hallucination, and a custom policy metric — at full-population coverage.

