| 1 | **Corrective RAG ✅** |
| 2 | ==================================================================== |
| 3 | |
| 4 | Corrective-RAG (CRAG) is a strategy for Retrieval-Augmented Generation (RAG) that includes self-reflection and self-grading of retrieved documents. Here’s a simplified breakdown of the steps involved: |
| 5 | |
| 6 | 1. **Relevance Check**: If at least one document meets the relevance threshold, the process moves forward to the generation phase. |
| 7 | 2. **Knowledge Refinement**: Before generating an answer, the process refines the knowledge by dividing the document into smaller segments called "knowledge strips." |
| 8 | 3. **Grading and Filtering**: Each "knowledge strip" is graded, and irrelevant ones are filtered out. |
| 9 | 4. **Additional Data Source**: If all documents are below the relevance threshold, or if the system is unsure about their relevance, it will seek additional information by performing a web search to supplement the retrieved data. |
| 10 | |
| 11 | Above steps are mentioned in |
| 12 | **[Official Paper](https://arxiv.org/abs/2401.15884)** |
| 13 | |
| 14 | <figure markdown="span"> |
| 15 |  |
| 16 | <figcaption>Corrective RAG: <a href="https://github.com/HuskyInSalt/CRAG">Source</a> |
| 17 | </figcaption> |
| 18 | </figure> |
| 19 | |
| 20 | Corrective Retrieval-Augmented Generation (CRAG) is a method that works like a **built-in fact-checker**. |
| 21 | |
| 22 | **[Offical Implementation](https://github.com/HuskyInSalt/CRAG)** |
| 23 | |
| 24 | [](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Corrective-RAG-with_Langgraph/CRAG_with_Langgraph.ipynb) |
| 25 | |
| 26 | Here’s a code snippet for defining a table with the [Embedding API](https://lancedb.github.io/lancedb/embeddings/embedding_functions/), and retrieves the relevant documents. |
| 27 | |
| 28 | ```python |
| 29 | import pandas as pd |
| 30 | import lancedb |
| 31 | from lancedb.pydantic import LanceModel, Vector |
| 32 | from lancedb.embeddings import get_registry |
| 33 | |
| 34 | db = lancedb.connect("/tmp/db") |
| 35 | model = get_registry().get("sentence-transformers").create(name="BAAI/bge-small-en-v1.5", device="cpu") |
| 36 | |
| 37 | class Docs(LanceModel): |
| 38 | text: str = model.SourceField() |
| 39 | vector: Vector(model.ndims()) = model.VectorField() |
| 40 | |
| 41 | table = db.create_table("docs", schema=Docs) |
| 42 | |
| 43 | # considering chunks are in list format |
| 44 | df = pd.DataFrame({'text':chunks}) |
| 45 | table.add(data=df) |
| 46 | |
| 47 | # as per document feeded |
| 48 | query = "How Transformers work?" |
| 49 | actual = table.search(query).limit(1).to_list()[0] |
| 50 | print(actual.text) |
| 51 | ``` |
| 52 | |
| 53 | Code snippet for grading retrieved documents, filtering out irrelevant ones, and performing a web search if necessary: |
| 54 | |
| 55 | ```python |
| 56 | def grade_documents(state): |
| 57 | """ |
| 58 | Determines whether the retrieved documents are relevant to the question |
| 59 | |
| 60 | Args: |
| 61 | state (dict): The current graph state |
| 62 | |
| 63 | Returns: |
| 64 | state (dict): Updates documents key with relevant documents |
| 65 | """ |
| 66 | |
| 67 | state_dict = state["keys"] |
| 68 | question = state_dict["question"] |
| 69 | documents = state_dict["documents"] |
| 70 | |
| 71 | class grade(BaseModel): |
| 72 | """ |
| 73 | Binary score for relevance check |
| 74 | """ |
| 75 | |
| 76 | binary_score: str = Field(description="Relevance score 'yes' or 'no'") |
| 77 | |
| 78 | model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True) |
| 79 | # grading using openai |
| 80 | grade_tool_oai = convert_to_openai_tool(grade) |
| 81 | llm_with_tool = model.bind( |
| 82 | tools=[convert_to_openai_tool(grade_tool_oai)], |
| 83 | tool_choice={"type": "function", "function": {"name": "grade"}}, |
| 84 | ) |
| 85 | |
| 86 | parser_tool = PydanticToolsParser(tools=[grade]) |
| 87 | prompt = PromptTemplate( |
| 88 | template="""You are a grader assessing relevance of a retrieved document to a user question. \n |
| 89 | Here is the retrieved document: \n\n {context} \n\n |
| 90 | Here is the user question: {question} \n |
| 91 | If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n |
| 92 | Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""", |
| 93 | input_variables=["context", "question"], |
| 94 | ) |
| 95 | |
| 96 | chain = prompt | llm_with_tool | parser_tool |
| 97 | |
| 98 | filtered_docs = [] |
| 99 | search = "No" |
| 100 | for d in documents: |
| 101 | score = chain.invoke({"question": question, "context": d.page_content}) |
| 102 | grade = score[0].binary_score |
| 103 | if grade == "yes": |
| 104 | filtered_docs.append(d) |
| 105 | else: |
| 106 | search = "Yes" |
| 107 | continue |
| 108 | |
| 109 | return { |
| 110 | "keys": { |
| 111 | "documents": filtered_docs, |
| 112 | "question": question, |
| 113 | "run_web_search": search, |
| 114 | } |
| 115 | } |
| 116 | ``` |
| 117 | |
| 118 | Check Colab for the Implementation of CRAG with Langgraph |
| 119 | |
| 120 | [](https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Corrective-RAG-with_Langgraph/CRAG_with_Langgraph.ipynb) |