Skip to main contentSkip to footer
PatternscriptintermediateRunnableguided-flow

Corrective RAG: grade what you retrieved before you answer

Every retrieved passage is graded for relevance, the failures are discarded, and the answer is written only from what survived. If nothing survives, the pattern refuses to answer rather than inferring from unrelated context.

Key Facts

Level
intermediate
Runtime
Python • OpenAI API
Pattern
Inspectable flow with visible system boundaries
Interaction
Live sandbox • Script
Updated
27 July 2026

Navigate this example

High-level flow

How this example moves from input to execution and reviewable output

Corrective RAG: grade what you… -> Retrieve relevant context -> Load environment keys -> Initialize OpenAI client -> Send chat request -> Constrain output schema

Start

Corrective RAG: grade what you…

Checkpoint

Retrieve relevant context

Outcome

Load environment keys

Why this page exists

This example is shown as both real source code and a product-facing interaction pattern so learners can connect implementation, UX, and doctrine without leaving the library.

Visual flowReal sourceSandbox or walkthroughMCP access

Doctrine relations

These are reasoning shapes: how an agent decides, when it acts, what it remembers. For how to compose the interface around it, see the AI Pattern Blueprint. For triggers, scheduling, context loading and recovery, see Agent runtime architecture.

Default gap

The textbook form of this pattern violates these by default. Each one carries the fix.

  • P5 · Replace implied magic with clear mental models

    Passages are dropped silently by default, so the user cannot tell that retrieval happened, that it was filtered, or what governed the filtering. The answer looks like recall rather than a governed process. Fix: state the retrieval and grading outcome alongside the answer, and make the refusal path explicit so 'I could not ground this' is a visible outcome rather than an absence.

    corrective_rag.py:run

Depends on the wrapper

Your implementation decides these, not the pattern. No verdict is asserted.

  • P6 · Expose meaningful operational state, not internal complexity

    '3 of 5 sources discarded as irrelevant' is meaningful operational state, and the data for it is produced on every run. Whether it reaches the operator is a wrapper decision, not a property of the pattern.

    corrective_rag.py:run

  • P7 · Establish trust through inspectability

    The grading verdicts and the discarded set exist inside the pattern, but nothing in the pattern requires showing them. A wrapper that surfaces 'kept 2 of 4, here is why each was dropped' is inspectable; one that returns only the answer is not. The pattern does not decide this, so no verdict is asserted.

    corrective_rag.py:grade

Doctrine relations are first-party analysis, not the output of a validation run. Run the validator on your own code to get a scored verdict.

How should this example be used in the platform?

Use the sandbox to understand the experience pattern first, then inspect the source to see how the product boundary, model boundary, and doctrine boundary are actually implemented.

UX pattern: Inspectable flow with visible system boundaries
Replace implied magic with clear mental models
Expose meaningful operational state, not internal complexity
Establish trust through inspectability

Source references

Library entry
pattern-corrective-rag
Source path
content/patterns/retrieval/corrective-rag/corrective_rag.py
Libraries
openai, pydantic, python-dotenv
Runtime requirements
OPENAI_API_KEY
Related principles
Replace implied magic with clear mental models, Expose meaningful operational state, not internal complexity, Establish trust through inspectability

corrective_rag.py

python
"""
Corrective RAG: grade what you retrieved before you answer from it

Plain RAG trusts the retriever. Corrective RAG does not: every retrieved
passage is graded for relevance, the ones that fail are discarded, and the
answer is written only from what survived.

    Retrieve -> Grade each passage -> Discard failures -> Answer from survivors

The point is not better retrieval. The point is that a keyword-ish retriever
returns plausible-looking passages that are about the wrong thing, and those
passages will otherwise be summarised into a confident, wrong answer.

If nothing survives grading, this refuses to answer. That refusal is the
feature. An agent that answers anyway is the failure mode the pattern exists
to prevent.

Run: python corrective_rag.py
"""

from typing import Literal

from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel, Field

load_dotenv()

client = OpenAI()

MODEL = "gpt-5.4-mini"
TOP_K = 4

# --------------------------------------------------------------
# Corpus. Deliberately seeded with near-miss distractors: several
# passages share vocabulary with the questions but answer something else.
# --------------------------------------------------------------

CORPUS: dict[str, str] = {
    "retry-policy": (
        "Failed jobs retry three times with exponential backoff starting at 2s. "
        "After the third failure the job moves to the dead-letter queue."
    ),
    "retry-ui-copy": (
        "The retry button in the dashboard is labelled 'Try again' and appears "
        "only after a job has finished failing. Copy is owned by the design team."
    ),
    "queue-limits": (
        "The dead-letter queue holds 10,000 messages. Beyond that, the oldest "
        "messages are dropped and a PagerDuty alert fires."
    ),
    "auth-tokens": (
        "Service tokens expire after 24 hours. Refresh happens automatically on "
        "the next authenticated call; there is no background refresh loop."
    ),
    "token-budget": (
        "Each tenant has a monthly token budget. Exceeding it does not block "
        "requests; it raises a soft warning on the billing page."
    ),
}


def retrieve(question: str, k: int = TOP_K) -> list[str]:
    """Deliberately naive term-overlap retrieval, so grading has real work."""
    terms = {t for t in question.lower().replace("?", "").split() if len(t) > 3}
    scored = [
        (len(terms & set(f"{key} {text}".lower().split())), key)
        for key, text in CORPUS.items()
    ]
    return [key for score, key in sorted(scored, reverse=True) if score > 0][:k]


# --------------------------------------------------------------
# Grade: one call per passage, so a bad passage cannot hide in a batch
# --------------------------------------------------------------


class Grade(BaseModel):
    verdict: Literal["relevant", "irrelevant"]
    why: str = Field(description="One sentence. Required for both verdicts.")


def grade(question: str, passage_id: str, passage: str) -> Grade:
    completion = client.beta.chat.completions.parse(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": (
                    "Decide whether the passage contains information that helps "
                    "answer the question. Sharing vocabulary is not relevance. "
                    "If it is about a neighbouring topic, mark it irrelevant."
                ),
            },
            {
                "role": "user",
                "content": f"Question: {question}\n\n[{passage_id}] {passage}",
            },
        ],
        response_format=Grade,
    )
    return completion.choices[0].message.parsed


# --------------------------------------------------------------
# Answer: only from what survived
# --------------------------------------------------------------


def answer_from(question: str, kept: list[tuple[str, str]]) -> str:
    context = "\n".join(f"[{pid}] {text}" for pid, text in kept)
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": (
                    "Answer using ONLY the passages provided. Cite the passage id "
                    "in square brackets for each claim. If the passages do not "
                    "contain the answer, say so plainly instead of inferring."
                ),
            },
            {"role": "user", "content": f"Question: {question}\n\n{context}"},
        ],
    )
    return completion.choices[0].message.content or ""


def run(question: str) -> str:
    retrieved = retrieve(question)
    print(f"  retrieved: {retrieved or '(nothing)'}")

    if not retrieved:
        return "No passage matched the question. Not answering from memory."

    kept: list[tuple[str, str]] = []
    for passage_id in retrieved:
        # Printed before the call so a slow grading pass reads as work in
        # progress rather than a stall.
        print(f"  grading  : {passage_id}...")
        verdict = grade(question, passage_id, CORPUS[passage_id])
        print(f"      {verdict.verdict:<10} {verdict.why}")
        if verdict.verdict == "relevant":
            kept.append((passage_id, CORPUS[passage_id]))

    if not kept:
        # The whole point of the pattern. Answering here would be the bug.
        message = (
            f"All {len(retrieved)} retrieved passages were graded irrelevant. "
            "Refusing to answer rather than inferring from unrelated context."
        )
        print(f"  REFUSED  : {message}")
        return message

    print(f"  kept     : {[pid for pid, _ in kept]}")
    result = answer_from(question, kept)
    print(f"  answer   : {result}")
    return result


if __name__ == "__main__":
    for question in [
        "How many times does a failed job retry before it is dead-lettered?",
        "What is our policy on refunding annual subscriptions?",
    ]:
        print(f"\n> {question}")
        run(question)

What should the learner inspect in the code?

Look for the exact place where system scope is bounded: schema definitions, prompt framing, runtime configuration, and the call site that turns user intent into a concrete model or workflow action.

Look for output contracts and validation
Look for the exact execution call
Look for what the product could expose to the user

How does the sandbox relate to the source?

The sandbox should make the UX legible: what the user sees, what the system is deciding, and how the result becomes reviewable. The source then shows how that behavior is actually implemented.

Read the implementation summary.
Step through the user and system states.
Inspect the source code with the highlighted doctrine decisions in mind.
SandboxInspectable flow with visible system boundaries

Interaction walkthrough

Use the sandbox to step through the user-visible experience, the system work behind it, and the doctrine choice the example is making.

UX explanation

The sandbox explains what the user should see, what the system is doing, and where control or inspectability must remain explicit.

AI design explanation

The page turns raw source into a product-facing pattern: what the model is allowed to decide, what the product should expose, and where deterministic code or review should take over.

Interaction walkthrough

  1. 1Read the implementation summary.
  2. 2Step through the user and system states.
  3. 3Inspect the source code with the highlighted doctrine decisions in mind.

Visible to the user

Every retrieved passage is graded for relevance, the failures are discarded, and the answer is written only from what survived. If nothing survives, the pattern refuses to answer rather than inferring from unrelated context.

System work

The product prepares a bounded model or workflow task.

Why it matters

The interface should make the delegated task legible before automation happens.

Used in courses and paths

This example currently stands on its own in the library, but it still connects to the principle system and the broader example family.

Related principles

Runtime architecture

Use this example in your agents

This example is also available through the blueprint’s agent-ready layer. Use the For agents page for the public MCP, deterministic exports, and Claude/Cursor setup.

Define triggers, context, and boundaries before increasing autonomy
Make control, observability, and recovery explicit in the runtime
Choose the right operational patterns before delegating to workflows