AI Hints
Home›RAG Tutorial›Self-Correcting RAG
RAG · Lesson 86 of 120

Checking the Answer

Self-check.

⏱ 2 min read▶ Video at 1:24:40🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Even with good chunks, a model can add something that isn't there. A self check runs a faithfulness test on every answer before the customer sees it. If it fails, we send a safe reply instead.

Checking the Answer
From the video: Checking the Answer
  • Good chunks
  • Still may add things
  • Check before sending

A safe answer

Safe answer gets an answer as usual. Then a checker asks if every claim is supported by the chunks. If not, we return a safe message instead. Run it. The answer passes the check, and is returned.

self_check.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm, answer

class Check(BaseModel):
    supported: bool

index = Index(make_chunks(load_docs()))
checker = llm.with_structured_output(Check)

def safe_answer(q):
    chunks = [c for s, c in index.search(q)]
    a = answer(q, chunks)
    context = "\n".join(c["text"] for c in chunks)
    ok = checker.invoke(f"Context: {context}\nAnswer: {a}\nIs every claim supported?").supported
    return a if ok else "Sorry, I'm not sure. Please contact our team."

print(safe_answer("How much is the Basic service?"))
Output
Based on the provided context, the Basic service costs £49.
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()

The cost of checking

A self check doubles the model calls. Use a small, fast model for checking. Check only important answers, like prices and policies. And log every failed check, because each one is a bug to study.

keyvalue
Costdouble the calls
Checkersmall, fast model
Checkimportant answers
Logevery failure

Summary

A self check tests each answer for faithfulness, and falls back to a safe reply if it fails. Next, RAG with LangGraph.

Key takeaways
  • Answer
  • Check it
  • Safe fallback
Next up: RAG with LangGraph — a small graph