Corrective RAG Chatbot

A LangGraph CRAG loop: grade every retrieved doc, rewrite weak queries and fall back to Tavily web search.

LLM / RAG2025All work

Fig. 01CRAG chatbot, the loop times each run and shows elapsed seconds.
CRAG chatbot, the loop times each run and shows elapsed seconds.

What it is

What it does

Standard RAG trusts whatever its retriever coughs up. This chatbot implements the Corrective RAG pattern end to end on a local model: every retrieved document gets graded for relevance, any miss triggers a semantic query rewrite, and the rewritten question drives a Tavily web search whose fresh results join the context before generation.

Why it exists

I kept getting confident RAG answers built on irrelevant chunks. That kills trust faster than 'I don't know.' I wanted a system that grades what it retrieved first, and if it's weak, rewrites the question and searches the web before it dares to answer.

Gemma-2-9B
Local generation
CRAG
Grade → rewrite → search
1
Miss triggers web

Repo Amit-kr26/Powerful-RAG-Chatbot-with-Corrective-Retrieval-and-Local-LLMsStack LangGraph · Gemma-2-9B · ChromaDB · Tavily · LangChain · Flask

Build6decisions

How it is built

Five-node state machine

lang.py defines retrieve → grade_documents → conditional branch → transform_query → web_search → generate as GraphState transitions; a single irrelevant grade flips run_web_search to Yes.

Fully local generation

google/gemma-2-9b loads through transformers (temperature 0.5, top_k 30, top_p 0.8, max_length 512); answers split out on the 'Answer:' marker for clean extraction.

Per-document grading

A binary yes/no relevance grader runs over each candidate individually, so one bad chunk reroutes the whole flow instead of poisoning the context silently.

Semantic query rewriting

transform_query reasons about underlying intent and emits a retrieval-optimised question used for BOTH the Tavily lookup and final generation.

Curated corpus ingest

URLs listed in url.txt load via WebBaseLoader, chunk at 500/100 with a tiktoken encoder splitter and embed (all-MiniLM-L6-v2) into a persistent rag-chroma collection.

Measured responses

The Flask demo times each full loop and displays elapsed seconds next to the answer.

How the pieces connect

Index and retrieve Grade, correct, answer url.txt corpus list WebBaseLoader scrape pages Splitter 500/100 tiktoken chunks Chroma rag-chroma mpnet embeddings retrieve top 4 docs Flask question POST / grade_documents one 'no' reroutes transform_query rewrite the query Tavily search web results generate Gemma-2-9B, local all relevant any irrelevant