Agentic AI

Self-RAG vs Corrective RAG (CRAG): How They Evaluate, Correct & Trust Evidence

Self-RAG vs Corrective RAG (CRAG) explained. Reflection tokens, retrieval evaluation, knowledge refinement, and how both architectures make RAG evaluate and correct its own evidence.

1. The Grounding Illusion: High Similarity Does Not Mean a Correct Answer

Imagine a SaaS company running an AI-powered customer support assistant. It handles thousands of technical questions every week.

A customer asks:

“I am using the Enterprise v2 plan. What is the API rate limit, and does the limit change for burst requests?”

The RAG pipeline retrieves three documents:

  • Developer v1 API documentation: 100 requests per minute.
  • Enterprise v2 billing documentation: details about subscription limits.
  • Enterprise v1 API documentation: burst-request configuration.

The retrieved documents contain the right terminology: API, rate limit, Enterprise, requests per minute.

The vector database returns high similarity scores. A reranker places these documents near the top.

The generator receives them and responds:

“Your Enterprise v2 plan supports 100 requests per minute, with burst requests enabled by default.”

Sounds convincing.

But the answer is not established by the retrieved evidence. The 100-request limit belongs to Developer v1, while the burst configuration belongs to Enterprise v1. The system has combined facts from different plans and versions.

This is a classic RAG failure: the retrieved content is topically similar, but it does not establish the answer to the actual question.

1.1 Why does this happen?

A conventional RAG pipeline looks like this:

User Query
    ↓
Query Embedding
    ↓
Vector Database
    ↓
Top-K Retrieved Chunks
    ↓
Reranking
    ↓
LLM Generation
    ↓
Final Answer

Let’s understand what each component actually guarantees.

Vector similarity measures how close two embeddings are according to a selected mathematical metric. It helps identify semantically similar content.

Top-K retrieval returns a fixed number of candidates. If k=10, the retriever attempts to return ten candidates, even when the corpus contains no exact answer.

Reranking reorders those candidates according to a stronger query-document relevance model.

None of these operations guarantees that a retrieved document contains the exact answer.

A document about Enterprise v1 may be more semantically similar to an Enterprise v2 question than a document that uses different terminology but contains the correct v2 information.

This creates three distinct questions:

CheckActual question
Semantic similarityIs this content about a similar topic?
Context relevanceDoes this content help answer this exact query?
Answer supportDoes the retrieved evidence establish the generated claim?

There is also a fourth question: is the final response useful and complete?

A response can be relevant but incomplete. It can be fluent but unsupported. It can even be supported by one document while silently contradicting another.

That is why production RAG needs an evaluation layer between retrieval and generation—and, in stronger architectures, another evaluation layer after generation.

This brings us to two important approaches: Self-RAG and Corrective RAG.


2. Reflection: What Does It Actually Mean?

Before understanding Self-RAG, let’s clear up one confusing term.

Reflection means evaluating the system’s own intermediate results or generated output before deciding what should happen next.

For example, after retrieval, the system asks:

  • Did we retrieve useful evidence?
  • Does the evidence apply to the requested product version?
  • Is the evidence sufficient to answer every part of the question?

After generation, it asks:

  • Is every factual claim supported by the retrieved evidence?
  • Did the model invent a configuration value?
  • Did it ignore an important condition?
  • Does the response actually answer the original question?

Reflection is an architectural activity, not a specific model or Python library.

There are multiple ways to implement it:

  1. A similarity-score threshold.
  2. A cross-encoder or reranker.
  3. A trained classification model.
  4. An LLM evaluating another model’s output.
  5. A model trained to emit specialised reflection signals.

The fifth approach is central to the original Self-RAG research.

2.1 Reflection vs. LLM-as-a-Judge

These two terms are related, but they are not interchangeable.

  • Reflection describes the evaluation process: the system checks its own retrieval or answer.
  • LLM-as-a-Judge describes one way to perform that evaluation: an LLM receives a question, evidence, answer, and evaluation rules, then returns a judgement.

Think of reflection as the inspection task and LLM-as-a-Judge as one possible inspector.

You can implement reflection without an LLM judge. A deterministic rule or a trained classifier can also perform an evaluation.

Likewise, LLM-as-a-Judge can be used beyond Self-RAG and CRAG—for example, to evaluate answer quality, classify queries, or inspect whether a generated response follows a required policy.


3. Self-RAG: The Model Learns to Reflect on Retrieval and Generation

3.1 What is Self-RAG?

Self-RAG stands for Self-Reflective Retrieval-Augmented Generation. It was introduced in research published in 2023, with the work commonly associated with the 2024 ICLR publication.

Its central idea is to make the model evaluate its retrieval and generation decisions rather than blindly generating an answer from whatever context happens to be available.

Traditional RAG follows a fixed sequence:

Retrieve -> Generate -> Return

Self-RAG introduces reflection signals into this process:

Decide Whether to Retrieve
          ↓
     Retrieve Evidence
          ↓
   Evaluate Relevance
          ↓
     Generate Answer
          ↓
   Evaluate Support
          ↓
   Evaluate Usefulness

The original research uses special reflection tokens and a model trained to produce and use them.

Let’s understand those tokens properly.

3.2 The four reflection-token categories

The original Self-RAG approach introduces four important categories of special tokens. The bracketed names below are readable representations of specialised token IDs.

1. [Retrieve] — Should the model retrieve information?

In standard RAG, retrieval usually happens for every query.

But consider two questions:

  • “What is a vector embedding?”
  • “What is the current API rate limit for Enterprise v2?”

The first may be answerable using general model knowledge. The second depends on specific documentation.

Self-RAG learns to decide whether retrieval is needed.

Its retrieval decision can represent:

  • [Retrieve: Yes] — External evidence is needed.
  • [Retrieve: No] — The model can answer without retrieval.
  • [Retrieve: Continue] — Additional retrieval may be needed.

The decision is influenced by patterns learned during training.

2. [IsRel] — Is the retrieved passage relevant?

After retrieval, the model evaluates whether a passage is useful for answering the query.

For our Enterprise v2 question:

  • A Developer v1 rate-limit table is not directly applicable.
  • An Enterprise v2 API documentation page is relevant.
  • An Enterprise v1 burst configuration page may provide background but cannot establish the v2 behaviour.

This is more than checking whether the words match. The model must consider the question’s actual requirements, including plan, version, date, and deployment conditions.

3. [IsSupp] — Is the generated claim supported by evidence?

Suppose the retrieved Enterprise v2 documentation says:

“The standard request quota is defined by the active subscription configuration.”

The generated answer says:

“Enterprise v2 allows 500 requests per minute.”

Where did 500 come from?

If no retrieved evidence establishes that number, the claim is unsupported. The supportedness signal evaluates whether generated content follows from the retrieved evidence. It can distinguish fully supported, partially supported, and unsupported content.

4. [IsUse] — Is the answer useful?

An answer can be supported but still be unhelpful.

For example:

“The request quota depends on the active subscription configuration.”

This may be factually supported, but the customer also asked about burst requests.

The utility evaluation considers whether the response actually helps the user, rather than merely containing a supported sentence.

These four categories evaluate different stages:

TokenStageWhat it evaluates
[Retrieve]Before retrievalIs retrieval necessary?
[IsRel]After retrievalIs the retrieved evidence relevant?
[IsSupp]During/after generationAre generated claims supported?
[IsUse]Answer evaluationIs the response useful?

3.3 What does “special control tokens emit” mean?

A normal LLM generates a sequence of tokens.

For example:

The Enterprise plan supports API access.

A Self-RAG-trained model can generate specialised reflection tokens within its output sequence, conceptually like:

[Retrieve: Yes]

[IsRel: Relevant]

The Enterprise v2 documentation establishes the
subscription-specific API quota.

[IsSupp: Fully Supported]

[IsUse: 5]

The special tokens act as signals that represent decisions or evaluations.

The important difference is that, in the original approach, the model is trained to produce these signals as part of its learned generation behaviour. They are not simply decorative tags inserted into an ordinary prompt. The model learns how these decisions relate to retrieval and generation through specialised training data and objectives.

3.4 How does the original Self-RAG use these signals?

The original approach goes beyond printing a relevance label. It uses reflection-token probabilities to help evaluate candidate generation paths.

At a high level:

  1. The model considers whether retrieval is needed.
  2. If retrieval is selected, it receives candidate passages.
  3. It evaluates the relevance of those passages.
  4. It generates answer segments with support-related reflection.
  5. It evaluates the usefulness of candidate responses.
  6. Reflection signals contribute to selecting stronger generation paths.

The paper uses segment-level generation and decoding strategies, including beam-search-style candidate evaluation.

Why?

Because the model should not simply generate the first fluent answer. It should favour answer paths that are better supported and more useful according to the learned reflection signals.

This is one reason the original Self-RAG is more than a prompt template.


4. Native Self-RAG vs. Prompted Self-RAG: Two Different Implementations

This distinction is extremely important when moving from research to production.

4.1 Native Self-RAG: The research approach

In the original research approach:

  • Special reflection tokens are added to the model’s vocabulary.
  • Training examples are prepared with retrieval and critique annotations.
  • The model is fine-tuned to generate these signals.
  • Its generation and decoding process uses the reflection signals.

This requires a specialised training pipeline, labelled data, and model infrastructure.

You cannot take any random commercial LLM, write [IsRel] inside a prompt, and claim that you have implemented the original Self-RAG architecture.

4.2 Prompted Self-RAG-style implementation

A more modular production approach uses ordinary LLM calls.

For example:

  1. A retrieval-decision prompt checks whether external information is needed.
  2. A relevance evaluator checks retrieved chunks.
  3. The generator writes an answer using accepted evidence.
  4. A support evaluator checks the generated answer.
  5. Python code decides whether to continue, retry, or refuse.

The workflow looks like this:

             USER QUERY
                  ↓
        Retrieval Decision LLM
                  |
          +-------+-------+
          |               |
         NO              YES
          ↓               ↓              v
      Direct Answer    Vector Search
                          ↓
                   Relevance Judge
                          |
                    Programmatic Gate
                          ↓
                    Answer Generator
                          ↓
                     Support Judge
                          |
                    Programmatic Gate
                          ↓
                     Final Answer

This is a prompted, modular implementation inspired by Self-RAG. It does not reproduce the original trained-token architecture.

The advantage is that you can implement it using an existing LLM API without training a specialised generator.

The trade-off is additional evaluator calls, latency, and the possibility that the judge itself makes mistakes.


5. Building a Self-RAG-Style Pipeline in Python

Let’s use the same Enterprise v2 API scenario. The retriever returns twenty candidate chunks. We want to filter them before the expensive generation model receives them.

5.1 First, understand why there are two prompts

There are two different evaluation stages.

RELEVANCE_PROMPT runs after retrieval and before answer generation.

It asks:

“Do these retrieved chunks actually help answer the user’s question?”

SUPPORT_PROMPT runs after answer generation.

It asks:

“Does the generated answer’s every factual claim follow from the accepted evidence?”

A document can be relevant while the model still invents a number that the document never mentioned.

RELEVANCE_PROMPT = """
You are a strict retrieval evaluator.

Question:
{query}

Retrieved chunk:
{chunk_text}

Metadata:
{metadata}

Determine whether this chunk provides direct evidence for answering the exact question. Check product
tier, version, dates, and conditions. Topical similarity alone is not sufficient.

Return JSON:
{
    "relevant": true,
    "reason": "Short explanation"
}
"""

SUPPORT_PROMPT = """
You are a strict answer-grounding evaluator.

Question:
{query}

Generated answer:
{answer}

Accepted evidence:
{chunks}

Check every factual claim in the answer.

A claim is supported only if the evidence establishes it. Do not use your own external 
knowledge to fill gaps.

Return JSON:
{
    "supported": true,
    "unsupported_claims": []
}
"""

5.2 What does .format() do?

The prompt contains placeholders:

{query}
{chunk_text}
{metadata}

At runtime, Python replaces them with actual values.

prompt = RELEVANCE_PROMPT.format(
    query=user_query,
    chunk_text=chunk.text,
    metadata=chunk.metadata
)

The resulting string contains the real question and retrieved document. That complete string is sent to the evaluator model.

5.3 Why does the LLM return JSON?

Suppose the evaluator replies:

“This looks somewhat relevant, but I am unsure because it refers to an older plan.”

A human can interpret this. Your Python program needs a predictable decision.

Compare:

This chunk seems relevant, but there is some uncertainty.

with:

{
  "relevant": false,
  "reason": "The document describes Enterprise v1."
}

The second output gives Python a field it can inspect:

if result["relevant"]:
    ...

This is called structured output or structured prompting: asking the model to return information in a predefined machine-readable format. It is useful because software needs explicit values to make deterministic routing decisions.

5.4 json.loads() and json.dumps()

These functions perform opposite operations.

import json

raw = '{"relevant": true, "reason": "Version matches"}'

# JSON text -> Python dictionary
result = json.loads(raw)

print(result["relevant"])  # True

json.loads() converts a JSON string into a Python object.

The reverse:

decision = {
    "relevant": True,
    "reason": "Version matches"
}

# Python dictionary -> JSON string
payload = json.dumps(decision, indent=2)

json.dumps() serialises a Python object into JSON text. The indent=2 argument simply makes the JSON easier to read by adding two spaces of indentation.

In these workflows:

  • loads() commonly parses an evaluator’s JSON response.
  • dumps() can serialise chunks, metadata, or structured results before passing them into a prompt or API.

5.5 The actual relevance-filtering function

import json
from pydantic import BaseModel

class RelevanceDecision(BaseModel):
    relevant: bool
    reason: str

def assess_chunks(query, chunks, judge_llm):
    relevant_chunks = []

    for chunk in chunks:
        prompt = RELEVANCE_PROMPT.format(
            query=query,
            chunk_text=chunk.text,
            metadata=chunk.metadata
        )

        raw = judge_llm.complete(
            prompt,
            response_format="json"
        )

        decision = RelevanceDecision.model_validate_json(raw)

        if decision.relevant:
            relevant_chunks.append(chunk)

    return relevant_chunks

The function evaluates each candidate and retains only the chunks approved by the evaluator.

model_validate_json() parses the JSON and validates it against the Pydantic schema. It rejects malformed output or incorrect field types.

5.6 Why is Pydantic validation necessary?

Imagine the model returns:

{
  "relevant": "probably",
  "reason": "Seems okay"
}

The value "probably" is not a Boolean. Your application expects True or False. A strict schema helps reject malformed decisions before they enter the control flow.

But remember: Pydantic validates structure, not truth.

It can verify that relevant is a Boolean. It cannot prove that the document is actually relevant. That is why structured validation and evaluator-quality testing must work together.

5.7 Why do we need a programmatic gate?

Suppose the evaluator returns:

{
  "relevant": false,
  "reason": "The document describes Developer v1."
}

The application must not send that document to the generator simply because the model has also written a confident paragraph elsewhere.

The Python program must enforce the decision.

def retrieval_gate(query, chunks, judge_llm):
    approved = assess_chunks(
        query,
        chunks,
        judge_llm
    )

    if not approved:
        return {
            "proceed": False,
            "reason": "No relevant evidence found."
        }

    return {
        "proceed": True,
        "chunks": approved
    }

This is a hard programmatic intercept: the application controls whether generation is allowed to continue.

The model does not get to overrule the application simply by generating another sentence.


6. The Production Trap: Why Can a Model Ignore Its Own Criticism?

Suppose a model produces:

[IsRel: Irrelevant]

The Enterprise v2 rate limit is 500 requests per minute.

It has declared the evidence irrelevant and still generated an answer.

Why?

There are two very different situations.

Native Self-RAG

The reflection tokens participate in a trained generation and decoding process. Their influence depends on the learned model and the decoding strategy.

Prompted Self-RAG-style implementation

If you merely tell an ordinary LLM to print [IsRel: Irrelevant] and then continue, the text itself does not automatically stop generation.

It is a soft instruction unless the application explicitly interprets it and controls the next step.

6.1 Completion bias

An instruction-following LLM is generally trained to produce a useful continuation. If the prompt contains a question and some context, the model may continue generating an answer even after expressing uncertainty.

This is one reason a negative reflection statement should not be treated as an execution-level stop command.

6.2 How do we debug it?

Inspect the complete generation trace.

Check:

  • What relevance decision was produced?
  • Was the decision actually parsed?
  • Did the Python code execute the rejection branch?
  • Did the generator receive rejected chunks anyway?
  • Did the support evaluator run?
  • Was its negative result ignored?

If the trace shows a negative decision followed by successful generation, the problem may be the application routing—not necessarily the model’s reflection mechanism.

6.3 Hard intercept with Pydantic and a threshold

from pydantic import BaseModel, Field

class RelevanceCritique(BaseModel):
    is_relevant: bool
    confidence_score: float = Field(ge=0.0, le=1.0)
    reason: str

def evaluate_and_intercept(query, chunks, judge_llm):
    prompt = f"""
    Evaluate whether these documents directly support
    the user's exact question.

    Query: {query}

    Chunks:
    {[c.text for c in chunks]}

    Return strict JSON with:
    is_relevant, confidence_score, reason.
    """

    raw = judge_llm.complete(
        prompt,
        response_format="json"
    )

    critique = RelevanceCritique.model_validate_json(raw)

    THRESHOLD = 0.80

    if (
        not critique.is_relevant
        or critique.confidence_score < THRESHOLD
    ):
        return {
            "proceed": False,
            "reason": critique.reason
        }

    return {
        "proceed": True,
        "reason": "Evidence passed the configured gate."
    }

The Boolean decision and configured score threshold are enforced by Python. A failed decision can stop generation or route to another retrieval strategy.0.80 is an illustrative starting value, not a universal Self-RAG threshold.


7. Reranker vs. Relevance Evaluator: Aren’t They Doing the Same Job?

This is another important engineering distinction. A reranker and an evaluator both operate after initial retrieval, but their objectives differ.

Reranker

A cross-encoder receives a query and a candidate document together and produces a relevance score.

It helps rank candidates:

Query + Chunk A -> 0.91
Query + Chunk B -> 0.76
Query + Chunk C -> 0.32

The system can reorder them:

Chunk A
Chunk B
Chunk C

A reranker generally answers:

“Which candidates look more relevant to this query?”

Evaluator

A relevance evaluator asks a stricter question:

“Does this evidence actually support answering the user’s question under the required conditions?”

For example:

  • Chunk A mentions Enterprise v1.
  • Chunk B mentions Enterprise v2.
  • Chunk C describes the general API architecture.

A reranker may rank A highly because its terminology is very similar. An evaluator can reject A because the

requested plan is v2.

DimensionRerankerEvaluator
Primary jobRank candidatesJudge evidence quality or sufficiency
Typical outputRelevance scoreBoolean, category, or structured verdict
Main useImprove candidate orderingFilter, reject, or route retrieval
Can be used together?YesYes

A strong pipeline can use both:

Vector Retrieval
      ↓
Cross-Encoder Reranking
      ↓
Relevance / Sufficiency Evaluation
      ↓
Generation

The reranker improves ordering. The evaluator decides whether the evidence should be used at all.


8. LLM-as-a-Judge: What Is It, Why Do We Need It, and How Does It Work?

Now let’s look at the evaluator itself.

An LLM-as-a-Judge is an LLM used to assess the output or behaviour of another component.

The judge is not primarily writing the user-facing answer. It is checking whether the system has met specified criteria.

8.1 Why not use ordinary Python comparisons?

Consider these two answers:

Answer A

“Your refund will be processed within 72 hours.”

Answer B

“The money should be returned within three days.”

Their wording differs, but the meaning may be equivalent. A simple exact-string comparison would treat them as different.

LLM-as-a-Judge can assess meaning, evidence support, and completeness using a defined evaluation rubric. It is especially useful when correctness cannot be measured by matching exact words.

8.2 What does the judge receive?

A retrieval judge generally receives:

  1. The original user question.
  2. The retrieved document chunks.
  3. Relevant metadata.
  4. An evaluation rubric.

An answer-support judge additionally receives the generated answer.

The judge evaluates the material against explicit rules and returns a structured result.

User Question
     |
     +----------------------+
     |                      |
     v                      v
Retrieved Evidence     Generated Answer
     |                      |
     +----------+-----------+
                |
                v
          Judge Prompt
                |
                v
          LLM Evaluator
                |
                v
       Structured Decision
                |
                v
        Python / Graph Router

8.3 What is an evaluation rubric?

A rubric is simply a written set of criteria telling the judge what counts as acceptable.

For our API example:

  • Exact product tier must match.
  • Exact version must match.
  • A numerical rate limit must be explicitly supported.
  • A statement about burst requests must have its own evidence.
  • Missing information must not be invented.
  • Conflicting documents must be reported.

Without a rubric, the evaluator may simply reward an answer that sounds plausible.

8.4 A CRAG-style LLM judge

from pydantic import BaseModel
from typing import Literal
import json

class RetrievalVerdict(BaseModel):
    status: Literal[
        "confident",
        "ambiguous",
        "incorrect"
    ]
    reason: str
    missing_information: list[str]

CRAG_JUDGE_PROMPT = """
You are a strict retrieval-quality evaluator.

User question:
{query}

Retrieved evidence:
{chunks}

Classify the complete retrieval result.

CONFIDENT:
Evidence directly answers the required question
and satisfies its important conditions.

AMBIGUOUS:
Evidence is partially useful, incomplete,
mixed, or uncertain.

INCORRECT:
Evidence is unrelated, outdated, or does not
support the requested information.

Check product tier, version, dates,
and deployment conditions.

Return strict JSON with:
status, reason, missing_information.
"""

def llm_as_judge(query, chunks, judge_llm):
    prompt = CRAG_JUDGE_PROMPT.format(
        query=query,
        chunks=json.dumps(
            [c.text for c in chunks],
            indent=2
        )
    )

    raw = judge_llm.complete(
        prompt,
        response_format="json"
    )

    verdict = RetrievalVerdict.model_validate_json(raw)

    return verdict

The judge returns one of three semantic categories. Pydantic validates that the returned category belongs to the allowed set.

8.5 Does an LLM judge need a numerical threshold?

Not necessarily.

There are two common approaches.

Approach A: Score-based evaluation

The evaluator produces a score, and Python compares it against configured thresholds.

For example:

if score >= 0.80:
    status = "confident"
elif score >= 0.60:
    status = "ambiguous"
else:
    status = "incorrect"

These values are illustrative. Real thresholds must be calibrated for the evaluator, domain, and dataset.

Approach B: Categorical evaluation

The LLM returns a label:

{
  "status": "ambiguous",
  "reason": "The evidence mentions the Enterprise plan but not burst limits.",
  "missing_information": [
    "Burst request policy"
  ]
}

Python routes according to the label:

if verdict.status == "confident":
    proceed_to_generation()

elif verdict.status == "ambiguous":
    expand_retrieval()

else:
    discard_local_results()
    trigger_fallback()

Here, no explicit numerical score threshold is required for the routing decision.

But the application still needs strict rules for invalid responses, timeouts, missing fields, and evaluator failures.

8.6 Can we inspect the judge’s confidence?

Some APIs expose token probabilities or log probabilities. Where available, these can provide additional signals about the model’s selected label.

However, a high token probability does not prove that the judgement is factually correct.

A model can be confidently wrong.

Log probabilities should therefore be treated as one diagnostic signal, not a replacement for labelled evaluation.

8.7 Can the judge itself hallucinate?

Absolutely.

This is the evaluator reliability problem: who checks the checker?

Imagine the judge accepts an Enterprise v1 document for an Enterprise v2 question because both contain the same API terminology.

The judge has made the same mistake as the original generator.

Ways to reduce this risk include:

  • Explicitly including version, tier, and date in the evaluation rubric.
  • Using deterministic metadata checks alongside semantic judgement.
  • Testing the judge against labelled positive and negative examples.
  • Using a separate model for high-risk evaluation when justified.
  • Comparing multiple evaluations for uncertain cases.
  • Escalating when the evidence or evaluation remains ambiguous.
  • Monitoring false acceptance and false rejection rates.

Running three judges and taking a majority vote can help in some cases, but it is not a guarantee. Three models can share the same bias or misunderstanding.


9. CRAG: Corrective Retrieval Instead of Blind Generation

Self-RAG evaluates retrieval and generation using reflection.

But consider what happens when the local knowledge base itself does not contain the answer.

The system rejects the irrelevant chunks. Now only one incomplete document remains.

Should it generate anyway?

No.

The system needs to decide what to do next.

This is the central idea behind Corrective RAG (CRAG), introduced by Shi-Qi Yan and colleagues in 2024.

CRAG makes retrieval-quality evaluation an explicit decision point and associates each verdict with a corrective action.

9.1 The CRAG architecture

                 USER QUERY
                      ↓
               LOCAL RETRIEVAL
                      ↓
              RETRIEVAL EVALUATOR
                      |
          +-----------+-----------+
          |           |           |
       CORRECT    AMBIGUOUS    INCORRECT
          ↓           ↓           ↓                   
       Refine      Expand       Discard
       Local       Retrieval    Local Results
       Evidence       |             |
          |           v             v
          |       Query Rewrite   Web / Trusted
          |       + More Search   Alternative Source
          |           |             |
          +-----------+-------------+
                      ↓
              KNOWLEDGE REFINEMENT
                      ↓
                GENERATION
                      ↓
             ANSWER VALIDATION
                      ↓
                FINAL RESPONSE

The exact fallback strategy depends on the application. The key idea is that poor retrieval must trigger an explicit corrective action instead of silently flowing into generation.

9.2 The three retrieval verdicts

1. Correct / Confident

The retrieved evidence is sufficiently relevant and complete.

Example:

The local Enterprise v2 documentation explicitly contains the API rate-limit table and burst-request conditions.

Action:

  • Keep the local evidence.
  • Apply knowledge refinement if useful.
  • Generate the answer.

2. Ambiguous

The retrieved evidence is partially useful, but important information is missing.

Example:

The Enterprise v2 documentation establishes the standard API quota but says nothing about burst requests.

Action:

  • Preserve the useful local evidence.
  • Identify the missing information.
  • Transform the query to target the missing detail.
  • Search again.
  • Use a trusted external source when the local corpus cannot answer the question.
  • Combine the evidence only after evaluation.

3. Incorrect

The retrieved evidence is unsuitable.

Example:

All retrieved documents describe Developer v1 or Enterprise v1, while the question explicitly asks about Enterprise v2.

Action:

  • Discard the unsuitable local results.
  • Search a trusted alternative source, if appropriate.
  • If no reliable source exists, refuse or escalate.
VerdictWhat it meansAction
CorrectSufficient usable evidenceRefine and generate
AmbiguousPartial or mixed evidenceExpand retrieval and combine
IncorrectEvidence does not support the queryDiscard and use alternative source or refuse

A critical distinction: the verdict evaluates retrieval quality. It does not prove that the final answer will be correct.


10. Does CRAG Always Need a Trained Classifier?

No. This is one of the most important implementation choices.

The original CRAG research uses a trained retrieval evaluator. Production implementations can use different evaluation mechanisms depending on available data, latency, and cost.

There are three practical options.

Option 1: Similarity-score thresholds

The vector database or retrieval system may return similarity scores.

A simple implementation can use them as an initial signal:

def score_based_verdict(top_score):
    if top_score >= 0.80:
        return "confident"

    if top_score >= 0.60:
        return "ambiguous"

    return "incorrect"

This requires no classifier training.

But there is a serious limitation: similarity scores are not universal probabilities of answer correctness.

A score of 0.85 does not mean there is an 85% chance that the document contains the correct answer.

Thresholds depend on the embedding model, corpus, distance metric, chunking strategy, and query distribution.

Use score-based routing as a baseline, then validate it against labelled examples.

Option 2: Prompt-based LLM-as-a-Judge

Use a smaller or cheaper LLM to evaluate the retrieved evidence. It receives the query and retrieved chunks and returns one of the three CRAG verdicts.

Advantages:

  • No custom classifier training required.
  • Handles nuanced language and conditions.
  • Easy to update through the evaluation rubric.

Trade-offs:

  • Additional inference latency.
  • Additional token cost.
  • Possible judge hallucination.
  • More complex monitoring than a simple deterministic rule.

This is a practical option when labelled training data is not yet available.

Option 3: A custom retrieval classifier

This is where the term classifier often causes confusion.

A classifier does not have to be an LLM. An LLM is a generative model designed to produce sequences of tokens. A classifier is designed to assign a category or score to an input.

Examples include:

  • Logistic Regression.
  • SVM (Support Vector Machine).
  • Random Forest.
  • XGBoost.
  • DistilBERT.
  • DeBERTa.

A classifier might receive features such as:

  • Query-document similarity score.
  • Reranker score.
  • Query and document embedding features.
  • Version-match indicator.
  • Product-tier match indicator.
  • Document freshness.
  • Number of relevant passages.
  • Metadata mismatch signals.

It predicts a category:

0 = Confident
1 = Ambiguous
2 = Incorrect

A text classifier such as DistilBERT can learn directly from labelled query-document pairs. A traditional model such as SVM or XGBoost can use engineered features.

10.1 How is the classifier trained?

The process is:

Step 1: Collect examples

Gather real queries and their retrieved documents from the application.

Step 2: Label them

Domain experts or trained reviewers classify retrieval outcomes as confident, ambiguous, or incorrect.

Step 3: Prepare features

For an SVM or XGBoost model, create numerical features such as similarity, reranker scores, and metadata-match indicators.

For a transformer classifier, prepare labelled text pairs such as:

[Question]
What is the Enterprise v2 API limit?

[Retrieved Document]
Developer v1 supports 100 requests per minute.

[Label]
Incorrect

Step 4: Train and validate

Split examples into training, validation, and test sets. Avoid letting near-duplicate documents leak across the splits.

Step 5: Evaluate

Measure how often the classifier accepts bad evidence, rejects good evidence, and confuses ambiguous retrieval with incorrect retrieval.

Step 6: Deploy and monitor

Use it as a lightweight evaluator in the retrieval pipeline. Continue collecting errors and retrain when the domain or documentation changes.

You do not need to train such a classifier for every CRAG implementation. Start with a score-based baseline or prompted judge, and consider custom training when sufficient labelled data and scale justify it.


11. CRAG Knowledge Refinement: Why Is It Necessary?

Suppose the external search returns an official documentation page containing 3,000 words.

Only four sentences directly answer the user’s question.

The rest includes:

  • Navigation text.
  • Product introductions.
  • Unrelated examples.
  • Old configuration details.
  • Marketing statements.
  • Copyright and footer text.

Sending the entire page to the generator increases context size and introduces noise.

CRAG’s knowledge-refinement stage addresses this by extracting and evaluating smaller pieces of retrieved knowledge.

These pieces are often called knowledge strips.

11.1 A practical example

Original document:

“Enterprise v2 supports configurable API quotas. The default quota is determined by the active subscription. Burst requests are subject to a separate policy. Developer v1 uses a fixed limit of 100 requests per minute. Multi-tenant deployments may have additional restrictions.”

The question:

“What determines the Enterprise v2 API quota, and are burst requests covered by the same policy?”

Useful strips:

  1. Enterprise v2 supports configurable API quotas.
  2. The default quota depends on the active subscription.
  3. Burst requests are subject to a separate policy.

The Developer v1 sentence should not be used to answer the Enterprise v2 question.

The multi-tenant restriction may be relevant if the user is operating a multi-tenant deployment.

11.2 Why can knowledge refinement become dangerous?

Consider this original sentence:

“The 100 requests-per-minute limit applies only to Developer v1, not Enterprise v2.”

An aggressive extractor might retain:

“The 100 requests-per-minute limit applies.”

The extraction has removed the exact condition that prevents the sentence from being misused.

This is called qualifier loss.

A reliable refinement step must preserve:

  • Negations.
  • Version numbers.
  • Plan restrictions.
  • Conditions.
  • Exceptions.
  • Dates.
  • Units and numerical values.
  • Source references.

11.3 A query-directed extraction prompt

KNOWLEDGE_STRIP_PROMPT = """
Question:
{query}

Document:
{document}

Extract only sentences that directly help answer
the question.

Preserve the original meaning.

Never remove:
- Negations
- Version numbers
- Product tiers
- Conditions
- Exceptions
- Dates
- Units
- Numerical values

Return the original sentence wherever possible.

Include the source ID for every extracted strip.

If the document contains no useful evidence,
return an empty list.
"""

This is safer than a generic prompt such as “Summarize this document.”

11.4 Implementing extraction

import json

def extract_knowledge_strips(query, document, llm):
    prompt = KNOWLEDGE_STRIP_PROMPT.format(
        query=query,
        document=document.text
    )

    raw = llm.complete(
        prompt,
        response_format="json"
    )

    result = json.loads(raw)

    return result["knowledge_strips"]

The function extracts query-relevant evidence. In a production implementation, each strip should retain the original document ID, section, and text so that the final answer remains traceable.


12. Web Fallback: Why Internet Search Can Make CRAG Worse

When local retrieval is incorrect or incomplete, CRAG-style systems may use external search.

But the internet is not a verified knowledge base.

For our Enterprise v2 API question, imagine the search returns:

  1. Official Enterprise v2 documentation.
  2. A technical engineering article.
  3. A forum post describing an old workaround.
  4. An SEO page repeating API keywords.
  5. A copied Developer v1 tutorial.

If all five are passed directly to the generator, the fallback may introduce more errors than it fixes.

The solution is a controlled web-ingestion pipeline.

12.1 Strict domain allowlists

Define which sources are allowed to provide authoritative information.

For example:

TRUSTED_DOMAINS = {
    "docs.company.example",
    "engineering.company.example"
}

def is_trusted_source(domain):
    return domain in TRUSTED_DOMAINS

A production implementation should parse hostnames properly, account for approved subdomains, and avoid insecure substring matching.

A domain allowlist is only the first filter. An official page can still be outdated or irrelevant.

12.2 Boilerplate removal with Trafilatura or BeautifulSoup

Web pages contain large amounts of non-content HTML:

  • Navigation bars.
  • Menus.
  • Advertisements.
  • Footers.
  • Cookie notices.
  • Repeated links.

Libraries such as Trafilatura and BeautifulSoup can help extract the actual article or documentation content.

Example with Trafilatura:

import trafilatura

def extract_page_text(html):
    text = trafilatura.extract(html)

    if not text:
        return ""

    return text

This reduces page noise before chunking and evaluation.

12.3 Aggressive chunk and sentence discarding

Consider this retrieved page:

“Welcome to our API platform. We provide modern cloud services. Enterprise v2 uses configurable quotas. Burst requests follow a separate policy. Developer v1 supports 100 requests per minute. Contact our team for more details.”

For the user’s Enterprise v2 question, the Developer v1 sentence must not be used as the answer.

The system should retain useful evidence and discard irrelevant material.

However, keyword matching alone is not enough. A sentence can contain the word “Enterprise” and still fail to answer the question.

Use a combination of:

  • Domain and source validation.
  • Metadata checks.
  • Reranking.
  • Semantic evaluation.
  • Query-directed strip extraction.
  • Provenance preservation.

Only accepted evidence should reach generation.

12.4 Internal knowledge vs. public web: Who wins?

Suppose the internal company knowledge base says:

“The Enterprise v2 API migration will take place in March.”

A public blog claims:

“The migration has been delayed until May.”

Which source should the assistant trust?

It depends on what the user is asking.

For internal company policy, confidential configuration, internal roadmaps, or official company decisions, the authoritative internal source should take priority.

For public product behaviour, current external documentation may be the authoritative source.

Therefore, define an explicit epistemic source hierarchy—a policy describing which source has authority for which kind of claim.

A simplified example:

SourceAuthority
Approved internal policy or roadmapAuthoritative for internal company decisions
Official current product documentationAuthoritative for published product behaviour
Verified engineering documentationSupporting technical evidence
Public blog or forumSupplementary evidence
Unverified SEO contentReject or heavily restrict

Do not blindly declare that every internal document always overrides every public source. A stale internal document should not automatically defeat a newer official public release note.

The hierarchy must account for source type, ownership, freshness, version, and the question being answered.

12.5 Tag evidence before synthesis

def format_chunks_with_metadata(internal_chunks, web_chunks):
    formatted = []

    for chunk in internal_chunks:
        formatted.append({
            "source": "Internal KB",
            "authority": "Internal authoritative",
            "text": chunk.text,
            "source_id": chunk.id
        })

    for chunk in web_chunks:
        formatted.append({
            "source": "Public Web",
            "authority": "External supplementary",
            "text": chunk.text,
            "source_id": chunk.id
        })

    return formatted

The final generation prompt should explain how to resolve conflicts and require source attribution.

For example:

SOURCE_HIERARCHY_PROMPT = """
Answer using the supplied evidence.

Rules:
1. Internal approved policies govern internal company decisions.
2. Current official documentation governs published product behaviour.
3. Public blogs and forums are supplementary, not authoritative.
4. Do not silently combine contradictory claims.
5. Identify unresolved conflicts.
6. Preserve dates, versions, and source IDs.

Question:
{query}

Evidence:
{evidence}
"""

12.6 Privacy before external fallback

A query may contain customer names, account IDs, internal hostnames, or confidential configuration.

Before sending it to an external search API:

  • Remove or mask personally identifiable information.
  • Avoid exposing confidential internal identifiers.
  • Rewrite the query using only the information required for public search.
  • Apply access-control and data-loss-prevention rules.

A corrective retrieval mechanism must not create a data-leakage problem while trying to fix an evidence problem.


13. Multi-Part Questions: Retrieval Can Be Correct and the Final Answer Can Still Be Wrong

Consider:

“Compare Enterprise v1 and v2 API limits, explain the burst-request differences, and identify the migration conditions for multi-tenant deployments.”

This question requires several pieces of evidence. A single search may not retrieve everything.

The system can decompose it into smaller sub-questions:

sub_queries = [
    "What are the Enterprise v1 API limits?",
    "What are the Enterprise v2 API limits?",
    "How do burst-request policies differ?",
    "What are the multi-tenant migration conditions?"
]

Each sub-question is evaluated independently.

This is called multi-hop decomposition: breaking a complex information request into smaller retrieval tasks whose evidence must later be combined.

13.1 The synthesis problem

Imagine all four sub-questions return correct documents.

The final generator can still make mistakes:

  • It may assign the v1 limit to v2.
  • It may combine two different burst policies.
  • It may drop the multi-tenant restriction.
  • It may state a migration condition without preserving its version.

Correct individual retrievals do not guarantee correct synthesis.

13.2 Preserve provenance during aggregation

evidence = [
    {
        "sub_query": "Enterprise v1 API limit",
        "source_id": "enterprise-v1-api",
        "text": "..."
    },
    {
        "sub_query": "Enterprise v2 API limit",
        "source_id": "enterprise-v2-api",
        "text": "..."
    }
]

Each piece of evidence should retain the sub-query it answers and its original source.

13.3 Add a synthesis prompt

SYNTHESIS_PROMPT = """
Original question:
{original_query}

Evidence:
{evidence}

Write a coherent comparative answer.

Rules:
- Keep v1 and v2 facts separate.
- Preserve all conditions and exceptions.
- Do not infer missing numerical limits.
- Identify conflicting evidence.
- Cite source IDs for important claims.
"""

13.4 Add a synthesis-validation node

The final answer must be checked against the original question and the evidence—not merely against the sub-query summaries.

from pydantic import BaseModel

class SynthesisCheck(BaseModel):
    valid: bool
    missing_parts: list[str]
    unsupported_claims: list[str]
    reason: str

SYNTHESIS_VALIDATION_PROMPT = """
Original question:
{query}

Final answer:
{answer}

Available evidence:
{evidence}

Check:
1. Does the answer address every part of the original question?
2. Are version and plan restrictions preserved?
3. Are all factual claims supported?
4. Were contradictory sources handled explicitly?

Return JSON:
{
  "valid": true,
  "missing_parts": [],
  "unsupported_claims": [],
  "reason": "..."
}
"""

The validation step catches failures introduced during synthesis.

It should not automatically trust a summary just because an earlier evaluator accepted it.


14. Map-Reduce vs. Aggressive Pruning: Two Different Ways to Control Context

These techniques are useful when retrieval produces a large amount of evidence. They solve related but different problems.

Aggressive pruning removes irrelevant portions of retrieved material.

Map-Reduce processes large collections of evidence in smaller groups and combines the extracted results.

Aggressive pruning

Suppose a retrieved paragraph contains:

  • A product introduction.
  • A configuration key.
  • A version-specific warning.
  • A copyright notice.
  • An unrelated billing example.

Pruning removes irrelevant material while preserving the useful sentences.

Map-Reduce

Suppose ten documents contain information relevant to a complex migration question.

Instead of sending all ten documents directly into one generation prompt:

  • Map: extract query-relevant facts from each document separately.
  • Reduce: combine the extracted facts into one final evidence set or answer.

A query-directed extraction prompt should preserve exact values, conditions, and source IDs.

The summary-loss problem

A generic summary can silently remove the most important detail.

For example:

Original:

“The Enterprise v2 burst limit is 200 requests for 10 seconds, except for multi-tenant deployments, where the limit is 100.”

Bad summary:

“Enterprise v2 supports 200 burst requests.”

The summary has lost the exception.

The safer prompt is:

Extract facts that answer the original query.

Preserve exact numbers, units, versions,
conditions, exceptions, and negations.

Do not produce a generic summary.

Return source IDs with every extracted fact.

The final validation step should compare the synthesis against the original evidence, not only the compressed summaries.


15. How Do You Implement These Decisions in LangGraph?

LangGraph is useful here because it lets you represent the evaluation and correction workflow as explicit nodes and conditional routes.

The important point is that the graph controls execution. An LLM’s negative judgement does not automatically stop another node unless the graph routes accordingly.

15.1 Self-RAG-style graph

A simplified graph:

START
  |
  v
retrieval_decision
  |
  +---- No Retrieval ----> direct_answer
  |
  +---- Retrieve --------> retrieve_documents
                              |
                              v
                        relevance_judge
                              |
                              v
                        relevance_gate
                              |
                    +---------+---------+
                    |                   |
                  Pass                Fail
                    |                   |
                    v                   v
                generate             retry / refuse
                    |
                    v
                support_judge
                    |
                    v
                support_gate
                    |
              +-----+------+
              |            |
            Pass          Fail
              |            |
              v            v
             END       regenerate / refuse

The judge nodes evaluate. The gate nodes make programmatic decisions.

15.2 CRAG-style graph

START
  |
  v
local_retrieval
  |
  v
retrieval_evaluator
  |
  +---- Correct ------> knowledge_refinement
  |
  +---- Ambiguous ----> query_expansion
  |                         |
  |                         v
  |                    local + web search
  |                         |
  |                         v
  |                    evidence_evaluation
  |
  +---- Incorrect ----> discard_local
                            |
                            v
                       trusted_fallback
                            |
                            v
                       evidence_evaluation
                            |
                            v
                     knowledge_refinement
                            |
                            v
                        generation
                            |
                            v
                    support_validation
                            |
                            v
                           END

15.3 A practical conditional-routing function

def route_after_retrieval(state):
    status = state["retrieval_verdict"]

    if status == "confident":
        return "refine_local"

    if status == "ambiguous":
        return "expand_retrieval"

    if status == "incorrect":
        return "trusted_fallback"

    return "safe_refusal"

The routing function is ordinary Python. It makes the graph’s next step explicit.

15.4 Where exactly does LLM-as-a-Judge fit?

It can be used at several points:

Graph positionWhat the judge evaluates
Entry / routingQuery category or whether retrieval is needed
After retrievalContext relevance and evidence sufficiency
After generationFaithfulness and unsupported claims
After synthesisWhether all parts of the original question are answered
Before a sensitive actionWhether the proposed action satisfies defined safety rules

For a Self-RAG-style workflow, relevance and support judges are natural evaluation points.

For CRAG, the retrieval evaluator is the key decision point that chooses Correct, Ambiguous, or Incorrect.

A judge can be implemented using an LLM, a classifier, or a deterministic scoring mechanism. LangGraph does not require it to be an LLM.


16. Golden Evaluation Datasets: How Do We Know the System Is Actually Better?

Suppose you change the relevance prompt. The new evaluator rejects more documents.

Does that mean the system improved?

Not necessarily. It might have rejected outdated documents—but it might also have rejected valid documents that use different terminology. You need a reliable test set.

This is the purpose of a Golden Evaluation Dataset.

16.1 What is it?

A curated collection of representative user questions, expected evidence, correct answers, and evaluation labels.

A dataset entry might look like:

{
  "query": "What is the Enterprise v2 API limit?",
  "expected_sources": [
    "enterprise-v2-api-guide"
  ],
  "expected_answer": "Defined by active subscription configuration.",
  "retrieval_required": true,
  "relevant_document_ids": [
    "enterprise-v2-api-guide"
  ],
  "irrelevant_document_ids": [
    "developer-v1-api-guide"
  ]
}

This gives the team a reference against which retrieval, evaluation, and generation can be tested.

16.2 How is it created?

A practical process:

  1. Collect real support questions and historical failures.
  2. Include common, ambiguous, multi-part, and version-specific questions.
  3. Identify the authoritative documents for each question.
  4. Mark which retrieved chunks are relevant or irrelevant.
  5. Record expected answer claims and important qualifiers.
  6. Include examples where the correct action is to refuse or escalate.
  7. Have domain experts review difficult cases.
  8. Keep a separate test set for measuring generalisation.

LLM-generated synthetic questions can help expand coverage, but they should be reviewed. Synthetic labels are not automatically ground truth.

16.3 What do teams test with it?

Retrieval evaluation

Did the retriever find the expected documents?

  • Precision.
  • Recall.
  • Ranking quality.
  • Version and metadata match.

Evaluator evaluation

Did the judge make the correct decision?

  • False acceptance: bad evidence was accepted.
  • False rejection: good evidence was rejected.
  • Correct vs. Ambiguous confusion.
  • Precision and recall for each class.

Answer evaluation

  • Faithfulness / groundedness.
  • Answer relevance.
  • Completeness.
  • Preservation of conditions.
  • Unsupported claims.

Threshold calibration

Suppose a score threshold changes from 0.70 to 0.85.

Does this reduce false acceptance?

Does it also increase false rejection?

The Golden Dataset lets the team measure the trade-off rather than guessing.

16.4 Tools that can help

Ragas, DeepEval, and TruLens provide evaluation capabilities for RAG systems.

They can help measure retrieval and answer quality, but they do not automatically create a trustworthy ground-truth dataset.

The quality of the labels and examples matters more than the name of the evaluation framework.


17. Production Architecture: Latency, Cost, and Adaptive Routing

There is one final engineering constraint.

A company may have a strict p99 latency budget of 1.2 seconds.

Running several LLM evaluators and an external web search for every query can easily exceed that budget.

Neither Self-RAG nor CRAG should be applied blindly to every request.

17.1 Why Self-RAG can be expensive

The original Self-RAG architecture can involve:

  • Additional reflection-token generation.
  • More evaluation steps.
  • Candidate-path scoring.
  • Specialised model training and decoding.
  • Increased inference computation.

The prompted production version can also add multiple LLM calls:

  • Retrieval decision.
  • Relevance evaluation.
  • Answer generation.
  • Support evaluation.

The actual cost depends on the implementation and model sizes.

17.2 Why CRAG can be expensive

CRAG can be relatively quick when local retrieval is sufficient.

But fallback can add:

  • Query rewriting.
  • External search latency.
  • Page extraction.
  • Additional retrieval.
  • Relevance evaluation.
  • Knowledge refinement.

The external network call is often the largest unpredictable component.

17.3 Adaptive routing

A sensible architecture uses different paths depending on query complexity and retrieval confidence.

                  USER QUERY
                       |
                       v
                 FAST ROUTER
                       |
             +---------+---------+
             |                   |
        SIMPLE QUERY       UNCERTAIN QUERY
             |                   |
             v                   v
       STANDARD RAG       TARGETED EVALUATION
        Fast Path                 |
       < 0.4s target              v
                           CRAG CORRECTION
                                  |
                         +--------+--------+
                         |                 |
                      Local OK         Fallback
                         |                 |
                         +--------+--------+
                                  |
                                  v
                            FINAL CHECK
                                  |
                                  v
                              RESPONSE

The latency numbers shown are illustrative design targets, not guaranteed performance. They must be benchmarked on the actual infrastructure.

A simple query should not automatically pay for a full reflection pipeline.

An uncertain query should receive stronger evaluation.

A query that requires fresh public information may justify the extra cost of external fallback.

17.4 Hard budgets and structured refusal

Correction loops must be bounded.

MAX_ITERATIONS = 3

def run_corrective_loop(query, retrieve, evaluate, rewrite):
    current_query = query

    for attempt in range(MAX_ITERATIONS):
        chunks = retrieve(current_query)
        verdict = evaluate(current_query, chunks)

        if verdict == "confident":
            return chunks

        if verdict == "incorrect":
            return None

        current_query = rewrite(current_query)

    return None

This demonstrates a bounded correction loop. A production implementation also needs an overall deadline, tool-call limits, timeout handling, and a cost budget.

If the system cannot establish a reliable answer, it should return a structured refusal or escalate.

For example:

“I couldn’t verify the Enterprise v2 burst-request policy from the available authoritative documentation. I won’t infer a limit from another plan or version. Please consult the API support team.”

That is a much safer outcome than inventing a number.


18. Self-RAG vs. CRAG: The Architectural Differences That Matter

Now that both approaches are clear, let’s compare their architecture rather than just their definitions.

DimensionSelf-RAGCorrective RAG (CRAG)
Primary objectiveReflection during retrieval and generationEvaluate retrieval and correct inadequate evidence
Core mechanismSpecial reflection signals and self-evaluationRetrieval evaluator and explicit corrective actions
Retrieval decisionExplicitly evaluates whether retrieval is neededEvaluates the quality of retrieved results
Relevance evaluation[IsRel]Correct / Ambiguous / Incorrect verdict
Answer support[IsSupp]Can be added as a separate post-generation check
Utility evaluation[IsUse]Not its defining mechanism
Retrieval failureCan reject, retrieve again, or abstain depending on implementationRoutes to refinement, expanded retrieval, alternative source, or refusal
Knowledge refinementNot the defining contributionExplicit knowledge-refinement stage
Web fallbackNot required by the methodCommon corrective strategy
Model dependencyOriginal approach requires specialised trainingEvaluator can be a classifier or prompted judge
ModularityNative model is more tightly coupled to its reflection mechanismEvaluator, retriever, and generator can be modular
Main riskReflection or critic decisions may be wrongRetrieval evaluator may misclassify evidence
Best fitSystems that need model-level retrieval and answer reflectionSystems with incomplete, stale, or unreliable local knowledge

18.1 Coupling vs. modularity

Native Self-RAG trains the generator to use specialised reflection tokens.

Changing the base model may require adapting or retraining the specialised model.

CRAG’s evaluator can be separate from the generator.

You can replace the generator without necessarily retraining the retrieval evaluator, provided the evaluation interface remains compatible.

This makes CRAG-style orchestration more modular.

18.2 Internal evaluation vs. corrective retrieval

Self-RAG’s defining idea is to evaluate retrieval and generation through reflection.

CRAG’s defining idea is to evaluate retrieved knowledge and select an explicit recovery strategy.

CRAG does not mean “always use the internet.”

Self-RAG does not mean “never use external retrieval.”

The architectural distinction is about what the system evaluates and what corrective mechanism it uses.

18.3 Privacy and compliance

A native Self-RAG deployment can keep retrieval and reflection within a private environment.

A CRAG implementation that uses public search must consider whether user queries expose confidential information.

CRAG does not inherently require public internet access. Its alternative retrieval source can be another approved internal index or trusted service.

18.4 Context-window pollution

Self-RAG-style relevance evaluation can filter unsuitable chunks, but partially relevant passages may still contain unnecessary text.

CRAG’s knowledge-refinement stage explicitly focuses on extracting answer-relevant evidence before generation.

Both approaches can benefit from reranking, pruning, and provenance preservation.


19. The Practical Choice: Self-RAG, CRAG, or a Hybrid?

Consider three requirements.

Requirement A: The system must decide when retrieval is necessary and verify that its generated claims are supported.

A Self-RAG-style reflection workflow is appropriate.

Requirement B: The local knowledge base is incomplete or frequently outdated, and the system must recover when retrieval is insufficient.

A CRAG-style retrieval evaluator and corrective fallback are appropriate.

Requirement C: The system must both verify answers and recover from bad retrieval.

Use a hybrid:

             LOCAL RETRIEVAL
                    |
                    v
            CRAG-STYLE EVALUATOR
                    |
             Correct / Ambiguous /
                 Incorrect
                    |
                    v
            KNOWLEDGE REFINEMENT
                    |
                    v
             ANSWER GENERATION
                    |
                    v
           SELF-RAG-STYLE SUPPORT
                 EVALUATION
                    |
             +------+------+
             |             |
           Pass          Fail
             |             |
             v             v
           Return       Retry / Refuse

The hybrid does not need the full original Self-RAG decoding architecture.

A practical implementation can use CRAG-style retrieval evaluation before generation and a separate prompted support evaluator afterward.

This provides a modular architecture without requiring every query to run a heavy reflection process.


20. Production Metrics: How Do You Know the Architecture Is Working?

Do not judge the system only by whether the final answer sounds better. Track both answer quality and internal routing behaviour.

MetricWhat it tells you
Context relevanceAre retrieved chunks useful?
FaithfulnessAre generated claims supported by evidence?
Answer relevanceDoes the response answer the question?
Retrieval precisionHow much of the accepted evidence is relevant?
Retrieval recallHow much relevant evidence was found?
Evaluator precisionHow often does the judge correctly accept relevant evidence?
Evaluator recallHow much useful evidence does the judge retain?
Retrieval bypass rateHow often does the system skip retrieval?
Corrective fallback rateHow often does CRAG need an alternative source?
Refusal rateHow often is the system unable to establish a safe answer?
p95 / p99 latencyHow does the system behave under real load?
Cost per queryWhat does each evaluation and fallback path cost?

A high fallback rate may indicate that the local knowledge base is incomplete or outdated.

A very low fallback rate is not automatically good. The evaluator may be too lenient and accept weak evidence.

A high refusal rate may indicate a strict evaluator, poor retrieval, or missing documentation.

Metrics must be interpreted together.


Conclusion: Retrieval Is Not Proof

The central lesson behind Self-RAG and Corrective RAG is simple:

A system should not generate a confident answer merely because a retriever returned something.

Self-RAG introduces reflection into retrieval and generation. It teaches the model to decide whether retrieval is needed, assess relevance, evaluate support, and consider answer usefulness.

CRAG makes retrieval evaluation and corrective action explicit. It distinguishes sufficient evidence from ambiguous or incorrect retrieval and determines whether to refine, expand, replace, or reject the evidence.

LLM-as-a-Judge is one way to implement these evaluation steps, not the definition of reflection itself. A classifier, reranker, deterministic rule, or trained evaluator may also play a role.

And no evaluator should be trusted blindly.

Use structured outputs so software can interpret decisions. Use hard programmatic gates so negative decisions actually stop execution. Use domain rules to catch version and metadata mismatches. Use Golden Evaluation Datasets to calibrate thresholds and measure evaluator errors. Use source hierarchy and provenance to prevent conflicting evidence from being silently combined.

The goal is not to make a RAG system answer every question.

The goal is to make it distinguish between what it knows, what its evidence supports, what it still needs to retrieve, and what it must refuse to guess.

Logic Lama
Neural Ninjas
// Continuing from this article

Your Neural Path

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
// STILL BROWSING?
Build along, don't just read.
Get labs & articles matched to what you're into — free, takes 30 seconds.
Start building free