A LangGraph-based Corrective RAG pipeline that grades retrieval quality, falls back to web search when needed, refines context, and generates grounded answers.
This project implements a corrective retrieval flow:
- Retrieve relevant chunks from local PDFs.
- Score each chunk for relevance using an LLM.
- Route based on retrieval quality:
CORRECT: answer from local context.INCORRECT: rewrite query and use web search.AMBIGUOUS: combine local and web context.
- Refine context at sentence level with a strict relevance filter.
- Generate the final answer using only refined context.
Corrective RAG.ipynb- main implementation notebook.Documents/book1.pdf,Documents/book2.pdf,Documents/book3.pdf- local knowledge base.Corrective RAG.png- workflow image.
- LangChain
- LangGraph
- OpenAI (
text-embedding-3-large,gpt-4o-mini) - FAISS
- Tavily Search
- Python 3.11+
python -m venv .venv
source .venv/bin/activate
pip install -U langchain langchain-community langchain-openai langgraph faiss-cpu pypdf python-dotenv tavily-pythonCreate a .env file in the project root:
OPENAI_API_KEY=your_openai_key
TAVILY_API_KEY=your_tavily_key- Open
Corrective RAG.ipynbin Jupyter Notebook or VS Code. - Run all cells to load PDFs, build FAISS index, and compile the graph.
- Change the
questionin the example invocation cell. - Execute the final cell to get:
- retrieval verdict (
CORRECT,INCORRECT,AMBIGUOUS) - reason
- web query (if used)
- generated answer
- retrieval verdict (
UPPER_TH = 0.7- confident relevance threshold.LOWER_TH = 0.3- low relevance threshold.- Retriever default:
k = 4.
- The generator is instructed to answer only from provided context.
- If context is insufficient, it returns:
I don't know. - Web search is only used when local retrieval is weak or uncertain.
