RAG · Lesson 75 of 120
Faithfulness
Is it grounded.
Now we check the answer itself. Faithfulness asks, is every claim in the answer supported by the context? An unfaithful answer adds facts that weren't there. That's a hallucination.

- Check the answer
- Every claim supported?
- Or hallucinated?
A faithfulness judge
Verdict holds one true or false field. The judge model reads the context and an answer, and decides if every claim is supported. We try a faithful answer, and one with invented facts. Run it. The first passes. The second fails.
faithfulness.pypython
from pydantic import BaseModel
from llm import llm
class Verdict(BaseModel):
faithful: bool
judge = llm.with_structured_output(Verdict)
context = "Refunds go back to the original payment method within 7 working days."
for ans in ["Refunds take up to 7 working days.",
"Refunds take 30 days, and return postage is always free."]:
v = judge.invoke(f"Context: {context}\nAnswer: {ans}\n"
"Is every claim in the answer supported by the context?")
print(v.faithful, "|", ans)Output
True | Refunds take up to 7 working days. False | Refunds take 30 days, and return postage is always free.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Using faithfulness
Low faithfulness with good retrieval means the model is ignoring the context. Tighten the prompt, or try a stronger model. Faithfulness doesn't check if the answer is useful, only if it's grounded.
| key | value |
|---|---|
| Measures | grounded claims |
| Low score | model ignores context |
| Fix | prompt or model |
| Doesn't check | usefulness |
Summary
Faithfulness checks that every claim in the answer comes from the context. Next, answer relevance.
Key takeaways- Every claim
- Supported?
- No hallucination
Next up: Answer Relevance — did it answer