search
HomeTechnology peripheralsAICorrective RAG (CRAG) in Action

Retrieval-Augmented Generation (RAG) empowers large language models (LLMs) by incorporating information retrieval. This allows LLMs to access external knowledge bases, resulting in more accurate, current, and contextually appropriate responses. Corrective RAG (CRAG), an advanced RAG technique, further enhances accuracy by introducing self-reflection and self-assessment mechanisms for retrieved documents.

Key Learning Objectives

This article covers:

  • CRAG's core mechanism and its integration with web search.
  • CRAG's document relevance evaluation using binary scoring and query rewriting.
  • Key distinctions between CRAG and traditional RAG.
  • Hands-on CRAG implementation using Python, LangChain, and Tavily.
  • Practical skills in configuring evaluators, query rewriters, and web search tools to optimize retrieval and response accuracy.

Published as part of the Data Science Blogathon.

Table of Contents

  • CRAG's Underlying Mechanism
  • CRAG vs. Traditional RAG
  • Practical CRAG Implementation
  • CRAG's Challenges
  • Conclusion
  • Frequently Asked Questions

CRAG's Underlying Mechanism

CRAG enhances the dependability of LLM outputs by integrating web search into its retrieval and generation processes (see Figure 1).

Document Retrieval:

  • Data Ingestion: Relevant data is indexed, and web search tools (like Tavily AI) are configured for real-time data retrieval.
  • Initial Retrieval: Documents are retrieved from a static knowledge base based on the user's query.

Relevance Assessment:

An evaluator assesses retrieved document relevance. If over 70% of documents are deemed irrelevant, corrective actions are initiated; otherwise, response generation proceeds.

Web Search Integration:

If document relevance is insufficient, CRAG uses web search:

  • Query Refinement: The original query is modified to optimize web search results.
  • Web Search Execution: Tools like Tavily AI fetch additional data, ensuring access to current and diverse information.

Response Generation:

CRAG synthesizes data from both initial retrieval and web searches to create a coherent, accurate response.

Corrective RAG (CRAG) in Action

CRAG vs. Traditional RAG

CRAG actively verifies and refines retrieved information, unlike traditional RAG, which relies on retrieved documents without verification. CRAG often incorporates real-time web search, providing access to the most up-to-date information, unlike traditional RAG's reliance on static knowledge bases. This makes CRAG ideal for applications requiring high accuracy and real-time data integration.

Practical CRAG Implementation

This section details a CRAG implementation using Python, LangChain, and Tavily.

Step 1: Library Installation

Install necessary libraries:

!pip install tiktoken langchain-openai langchainhub chromadb langchain langgraph tavily-python
!pip install -qU pypdf langchain_community

Step 2: API Key Configuration

Set your API keys:

import os
os.environ["TAVILY_API_KEY"] = ""
os.environ["OPENAI_API_KEY"] = ""

Step 3: Library Imports

Import required libraries (code omitted for brevity, but similar to the original example).

Step 4: Document Chunking and Retriever Creation

(Code omitted for brevity, but similar to the original example, using PyPDFLoader, RecursiveCharacterTextSplitter, OpenAIEmbeddings, and Chroma).

Step 5: RAG Chain Setup

(Code omitted for brevity, but similar to the original example, using hub.pull("rlm/rag-prompt") and ChatOpenAI).

Step 6: Evaluator Setup

(Code omitted for brevity, but similar to the original example, defining the Evaluator class and using ChatOpenAI for evaluation).

Step 7: Query Rewriter Setup

(Code omitted for brevity, but similar to the original example, using ChatOpenAI for query rewriting).

Step 8: Web Search Setup

from langchain_community.tools.tavily_search import TavilySearchResults
web_search_tool = TavilySearchResults(k=3)

Step 9-12: LangGraph Workflow Setup and Execution

(Code omitted for brevity, but conceptually similar to the original example, defining the GraphState, function nodes (retrieve, generate, evaluate_documents, transform_query, web_search), and connecting them using StateGraph.) The final output and comparison with traditional RAG are also conceptually similar.

CRAG's Challenges

CRAG's effectiveness depends heavily on the evaluator's accuracy. A weak evaluator can introduce errors. Scalability and adaptability are also concerns, requiring continuous updates and training. Web search integration introduces the risk of biased or unreliable information, necessitating robust filtering mechanisms.

Conclusion

CRAG significantly improves LLM output accuracy and reliability. Its ability to evaluate and supplement retrieved information with real-time web data makes it valuable for applications demanding high precision and up-to-date information. However, continuous refinement is crucial to address the challenges related to evaluator accuracy and web data reliability.

Key Takeaways (similar to the original, but rephrased for conciseness)

  • CRAG enhances LLM responses using web search for current, relevant information.
  • Its evaluator ensures high-quality information for response generation.
  • Query transformation optimizes web search results.
  • CRAG dynamically integrates real-time web data, unlike traditional RAG.
  • CRAG actively verifies information, reducing errors.
  • CRAG is beneficial for applications needing high accuracy and real-time data.

Frequently Asked Questions (similar to the original, but rephrased for conciseness)

  • Q1: What is CRAG? A: An advanced RAG framework integrating web search for improved accuracy and reliability.
  • Q2: CRAG vs. Traditional RAG? A: CRAG actively verifies and refines retrieved information.
  • Q3: The evaluator's role? A: Assessing document relevance and triggering corrections.
  • Q4: Insufficient documents? A: CRAG supplements with web search.
  • Q5: Handling unreliable web content? A: Advanced filtering methods are needed.

(Note: The image remains unchanged and is included as in the original input.)

The above is the detailed content of Corrective RAG (CRAG) in Action. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
A Business Leader's Guide To Generative Engine Optimization (GEO)A Business Leader's Guide To Generative Engine Optimization (GEO)May 03, 2025 am 11:14 AM

Google is leading this shift. Its "AI Overviews" feature already serves more than one billion users, providing complete answers before anyone clicks a link.[^2] Other players are also gaining ground fast. ChatGPT, Microsoft Copilot, and Pe

This Startup Is Using AI Agents To Fight Malicious Ads And Impersonator AccountsThis Startup Is Using AI Agents To Fight Malicious Ads And Impersonator AccountsMay 03, 2025 am 11:13 AM

In 2022, he founded social engineering defense startup Doppel to do just that. And as cybercriminals harness ever more advanced AI models to turbocharge their attacks, Doppel’s AI systems have helped businesses combat them at scale— more quickly and

How World Models Are Radically Reshaping The Future Of Generative AI And LLMsHow World Models Are Radically Reshaping The Future Of Generative AI And LLMsMay 03, 2025 am 11:12 AM

Voila, via interacting with suitable world models, generative AI and LLMs can be substantively boosted. Let’s talk about it. This analysis of an innovative AI breakthrough is part of my ongoing Forbes column coverage on the latest in AI, including

May Day 2050: What Have We Left To Celebrate?May Day 2050: What Have We Left To Celebrate?May 03, 2025 am 11:11 AM

Labor Day 2050. Parks across the nation fill with families enjoying traditional barbecues while nostalgic parades wind through city streets. Yet the celebration now carries a museum-like quality — historical reenactment rather than commemoration of c

The Deepfake Detector You've Never Heard Of That's 98% AccurateThe Deepfake Detector You've Never Heard Of That's 98% AccurateMay 03, 2025 am 11:10 AM

To help address this urgent and unsettling trend, a peer-reviewed article in the February 2025 edition of TEM Journal provides one of the clearest, data-driven assessments as to where that technological deepfake face off currently stands. Researcher

Quantum Talent Wars: The Hidden Crisis Threatening Tech's Next FrontierQuantum Talent Wars: The Hidden Crisis Threatening Tech's Next FrontierMay 03, 2025 am 11:09 AM

From vastly decreasing the time it takes to formulate new drugs to creating greener energy, there will be huge opportunities for businesses to break new ground. There’s a big problem, though: there’s a severe shortage of people with the skills busi

The Prototype: These Bacteria Can Generate ElectricityThe Prototype: These Bacteria Can Generate ElectricityMay 03, 2025 am 11:08 AM

Years ago, scientists found that certain kinds of bacteria appear to breathe by generating electricity, rather than taking in oxygen, but how they did so was a mystery. A new study published in the journal Cell identifies how this happens: the microb

AI And Cybersecurity: The New Administration's 100-Day ReckoningAI And Cybersecurity: The New Administration's 100-Day ReckoningMay 03, 2025 am 11:07 AM

At the RSAC 2025 conference this week, Snyk hosted a timely panel titled “The First 100 Days: How AI, Policy & Cybersecurity Collide,” featuring an all-star lineup: Jen Easterly, former CISA Director; Nicole Perlroth, former journalist and partne

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft