Introduction
In our last lesson, we constructed a complete Retrieval-Augmented Generation pipeline and encapsulated it as a tool for our agent. This was a significant step, but it relied on a critical, simplifying assumption: that our vector search always returns perfectly relevant documents. In any production system, this assumption is a liability. Vector search is a probabilistic process based on semantic similarity, which doesn't always guarantee contextual relevance.
This lesson tackles that challenge head-on, addressing the final learning outcome for our module on RAG: evaluating the relevance of retrieved documents and deciding whether to use them. We will move beyond "naive RAG" and implement a crucial quality gate. You will learn to build a relevance evaluation step that allows your agent to critically assess the information it retrieves, discard irrelevant content, and even take corrective actions when the initial retrieval fails. This capability is a hallmark of more advanced agentic architectures like Corrective RAG (CRAG) and Self-RAG.
The "Garbage In, Garbage Out" Problem in RAG
A retrieval system, no matter how well-tuned, can sometimes fetch documents that are semantically close but contextually wrong. For example, a query about "memory management in Python" might retrieve a document about "managing memory in a C++ application." While both are about memory management, the C++ document is irrelevant and potentially harmful context for answering the Python-specific question.
When irrelevant or contradictory documents are injected into the LLM's context, you invite disaster:
- Factual Inaccuracies: The LLM may synthesize an answer based on incorrect information.
- Hallucinations: Conflicting context can confuse the model, increasing the likelihood of it fabricating details.
- Irrelevant Answers: The model might focus on the irrelevant document and produce an answer that, while plausible, completely misses the user's intent.
To build a reliable system, we cannot blindly trust our retriever. We need to validate its output.
Architectures for Self-Correction: CRAG and Self-RAG
The solution is to add a "quality gate" after retrieval but before generation. This is the central idea behind patterns like Corrective RAG (CRAG) and Self-RAG. These architectures introduce a self-reflection step where the system evaluates its own intermediate results.
Take a look at the following diagram which illustrates this concept.

The workflow is no longer a simple, linear pipe. The Retrieval Evaluator introduces a critical decision point. Based on the quality of the retrieved documents, the system can decide to:
- Proceed: Use the "Correct" documents for generation.
- Refine: Filter or decompose "Ambiguous" documents.
- Correct: Discard "Incorrect" documents and trigger a new action, like searching the web, to find better information.
Another similar architecture, Self-RAG, formalizes this with explicit checks for relevance.

From a systems architecture perspective, this is a powerful pattern. You are moving from a static data-processing chain to a dynamic, stateful workflow with conditional branching—a core tenet of the agentic systems we are building.
Implementing a Relevance Grader
The most common way to implement this relevance check is using the "LLM-as-a-Judge" pattern. We use a separate, lightweight LLM call to act as a "grader." Its sole job is to assess whether a single document is relevant to the user's original query.
The article "Enhance RAG Accuracy with Corrective-RAG (CRAG)" provides a clear, from-scratch implementation of this concept.
Enhance RAG Accuracy with Corrective-RAG (CRAG)
This article explains the CRAG framework and provides a simple, practical Python implementation of the evaluation step.
First, read the section describing the evaluation step. This introduces the core concepts of confidence scoring and contextual validation. Next, focus on the code implementation in the section Building CRAG. Pay close attention to the grade_document function. It's a perfect, minimal implementation of an LLM-as-a-Judge for this task. Notice how it constructs a prompt with the query and the document, then instructs the model to return a simple binary answer.
The grade_document function you just reviewed is our core building block. It takes a query and a document and returns a simple "yes" or "no".
But what prompt should we use for this grader? The prompt needs to be clear and focused. The video "Building a Self-RAG" offers an excellent example.
Building a Self-RAG | Making your Agentic workflows critique through Self-Reflection | LangChain
This video walks through building a Self-RAG system and details the prompts used for each self-reflection step.
Watch the segment from here, where the presenter reveals the document_grader_prompt. The prompt is instructive: "You are a grader assessing relevance... It does not need to be a stringent test. The goal is to filter out erroneous retrievals." This highlights that the grader's role is not deep analysis, but a quick, effective filter.
The prompt is key: it's not asking for a detailed critique, but a fast, binary classification. This makes the grading step efficient and cost-effective.
Integrating the Grader and Making Decisions
Now we can integrate our grade_document function into the main RAG workflow. The process is as follows:
- Retrieve a set of candidate documents from the vector store.
- Iterate through each candidate document.
- For each document, call the
grade_documentfunction with the original query and the document's content. - Collect only the documents that receive a "yes" grade.
- Decide the next action based on the outcome of the grading process.
The "Corrective RAG (CRAG)" article from Meilisearch provides a great code walkthrough of this entire process.
Corrective RAG (CRAG): Workflow, implementation, and more
This article provides a comprehensive implementation guide for CRAG, including code for retrieval, reranking, validation, and correction.
Please read the code examples in the section How to implement corrective RAG. First, look at the llm_validate function under "Retrieve candidates and rerank...". This is another example of a relevance grader, similar to the one we saw before, but it returns a score. Then, analyze the logic in "Evaluate and correct the context". Notice how the code checks if more evidence is needed (needs_more_evidence) and then triggers a corrective action (expand_query) if the initial retrieval was insufficient.
This leads us to the final, crucial part: what action does the agent take after grading?
Case 1: Relevant Documents Found
If the grading process yields one or more relevant documents, the agent filters out the irrelevant ones and proceeds to the final generation step. The context provided to the generator is now "clean"—it contains only verified, relevant information. The make_context function in the Meilisearch article is a good example of how to assemble this final, cleaned prompt.
Case 2: No Relevant Documents Found
This is where the agent's intelligence truly shines. If all retrieved documents are graded as "no," the initial retrieval has failed. A simple RAG pipeline would either proceed with garbage context or fail silently. An intelligent agent can decide on a corrective action.
Option A: Halt and Report
The simplest, safest action is to recognize that the knowledge base does not contain the answer and terminate the process gracefully. The system can then inform the user, "I could not find enough information to answer your question."
The video on Self-RAG demonstrates this exact scenario.
Building a Self-RAG | Making your Agentic workflows critique through Self-Reflection | LangChain
This video shows how a conditional edge in the agent's control flow handles the case of no relevant documents.
First, watch the conceptual explanation of the conditional edge. The decide_to_generate function checks if the list of filter_documents is empty. If it is, it returns an "end" signal to the workflow. Next, see this in action starting at this timestamp. The presenter asks a question that is irrelevant to the knowledge base. The document grader correctly marks all documents as "not relevant," the conditional edge fires, and the workflow terminates without attempting to generate a nonsensical answer.
This demonstrates a robust failure mode. Instead of hallucinating, the agent correctly identifies its own knowledge gap.
Option B: Corrective Action (e.g., Web Search)
A more advanced approach, central to the CRAG pattern, is to trigger a fallback mechanism. If the internal knowledge base fails, the agent can try to find the information elsewhere. A common fallback is a web search.
The article from nb-data.com that we reviewed earlier shows a perfect, minimal implementation of this.
Enhance RAG Accuracy with Corrective-RAG (CRAG)
Let's revisit this article to see the full corrective loop.
Examine the corrective_rag function presented in the final code block. Look at the if not relevant_docs: condition. When the grading step results in an empty list of documents, it calls supplementary_retrieval(query), which performs a web search to find new context. This new context is then used for generation.
This fallback mechanism dramatically increases the robustness and resourcefulness of your agent. It can now reason about the state of its own knowledge and dynamically switch strategies to accomplish its goal—a core principle of advanced agentic design.
Conclusion
This lesson completes our exploration of Retrieval-Augmented Generation by adding the final layer of intelligence and reliability. By moving beyond naive RAG, you've learned to build a system that critically evaluates its own retrieved information before acting on it.
Here are the key takeaways:
- Don't Trust, Verify: Standard RAG is vulnerable to the "garbage in, garbage out" problem. Always add a quality gate to validate retrieved documents.
- LLM-as-a-Judge: A simple, effective pattern for implementing a relevance grader is to use a focused LLM call that returns a binary score or simple classification.
- Conditional Control Flow: The output of the grading step creates a crucial decision point. This allows the agent to intelligently decide whether to proceed with generation, halt gracefully, or trigger a corrective action like a web search.
- Robustness through Correction: Architectures like CRAG and Self-RAG, which incorporate these evaluation and correction loops, are fundamentally more robust and reliable for production use cases.
With this, we conclude our module on integrating knowledge into your agent. You now have the first-principles understanding to build a sophisticated, self-correcting RAG system from scratch.
In our next module, we will shift our focus from a single capability like RAG to the broader challenge of managing a whole suite of tools. The first lesson will tackle a foundational engineering problem: how to design a flexible and scalable tool registry for dynamic registration, discovery, and validation of agent capabilities.