RAG · Lesson 85 of 120
Corrective RAG
Grade, then retry.
What if retrieval returns nothing useful? Corrective RAG checks. A grader looks at the chunks first. If none are relevant, we rewrite the question and search again, before answering.

- Check the chunks
- None relevant?
- Rewrite and retry
Grade, then retry
Relevant asks the model if a chunk helps answer the question. If no chunk passes, we ask for a better search query, and search again. Run it. The first search finds nothing useful. The retry finds the charging chunk.
corrective.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm
class Grade(BaseModel):
relevant: bool
index = Index(make_chunks(load_docs()))
grader = llm.with_structured_output(Grade)
relevant = lambda q, c: grader.invoke(f"Does this text help answer '{q}'?\n{c['text']}").relevant
q = "How many hours until my e-bike is full again?"
good = [c for s, c in index.search(q) if relevant(q, c)]
print("first try:", len(good), "relevant")
if not good:
better = llm.invoke(f"Write a better search query for an e-bike help centre: {q}\n"
"Reply with the query only.").text
good = [c for s, c in index.search(better) if relevant(q, c)]
print("retry: ", len(good), "relevant |", good[0]["text"][:40] if good else "none")Output
first try: 0 relevant retry: 1 relevant | ## Charging The Volt 500 battery charges
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()When retry fails
If the retry still finds nothing, say you don't know, or hand over to a person. Limit retries to one or two. Some systems fall back to a web search instead.
| key | value |
|---|---|
| Still nothing | say I don't know |
| Retries | one or two |
| Fallback | a person |
| Or | web search |
Summary
Corrective RAG grades the chunks, and retries with a better query when none are relevant. Next, checking the answer.
Key takeaways- Grade chunks
- Rewrite query
- Retry
Next up: Checking the Answer — self-check