Vai al contenuto principaleVai al footer
PatternscriptintermediateEseguibileguided-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.

Fatti chiave

Livello
intermediate
Runtime
Python • API OpenAI
Pattern
Flusso ispezionabile con confini di sistema visibili
Interazione
Sandbox live • Script
Aggiornato
27 luglio 2026

Naviga questo esempio

Vista rapida del flusso

Come questo esempio si muove tra input, esecuzione e risultato rivedibile

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

Avvio

Corrective RAG: grade what you…

Checkpoint

Retrieve relevant context

Esito

Load environment keys

Perché esiste questa pagina

Questo esempio è mostrato sia come codice sorgente reale che come pattern di interazione orientato al prodotto, così i discenti possono collegare implementazione, UX e doctrine senza lasciare la libreria.

Flusso visivoCodice realeSandbox o walkthroughAccesso MCP

Relazioni con la doctrine

Queste sono forme di ragionamento: come un agente decide, quando agisce, cosa ricorda. Per comporre l'interfaccia intorno a esso, vedi l'AI Pattern Blueprint. Per trigger, pianificazione, caricamento del contesto e ripristino, vedi Agent runtime architecture.

Gap predefinito

La forma classica di questo pattern li viola per impostazione predefinita. Ognuno riporta la correzione.

  • P5 · Sostituire la magia implicita con modelli mentali chiari

    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

Dipende dall'implementazione

Lo decide la tua implementazione, non il pattern. Nessun verdetto.

  • P6 · Esporre uno stato operativo significativo, non la complessità interna

    '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 · Stabilire fiducia attraverso l'ispezionabilità

    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

Le relazioni con la doctrine sono analisi di prima parte, non il risultato di una validazione. Esegui il validatore sul tuo codice per ottenere un verdetto con punteggio.

Come dovrebbe essere usato questo esempio nella piattaforma?

Usa prima la sandbox per comprendere il pattern di esperienza, poi ispeziona il sorgente per vedere come il confine del prodotto, il confine del modello e il confine della doctrine sono effettivamente implementati.

UX pattern: Flusso ispezionabile con confini di sistema visibili
Sostituire la magia implicita con modelli mentali chiari
Esporre uno stato operativo significativo, non la complessità interna
Stabilire fiducia attraverso l'ispezionabilità

Riferimenti sorgente

Voce di libreria
pattern-corrective-rag
Percorso sorgente
content/patterns/retrieval/corrective-rag/corrective_rag.py
Librerie
openai, pydantic, python-dotenv
Requisiti di runtime
OPENAI_API_KEY
Principi correlati
Sostituire la magia implicita con modelli mentali chiari, Esporre uno stato operativo significativo, non la complessità interna, Stabilire fiducia attraverso l'ispezionabilità

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)

Cosa dovrebbe ispezionare il discente nel codice?

Cerca il punto esatto in cui lo scope del sistema è delimitato: definizioni di schema, impostazione del prompt, configurazione di runtime e il punto di chiamata che trasforma l'intenzione dell'utente in un'azione concreta del modello o del workflow.

Cerca i contratti di output e la validazione
Cerca la chiamata di esecuzione esatta
Cerca cosa il prodotto potrebbe esporre all'utente

Come si relaziona la sandbox al sorgente?

La sandbox dovrebbe rendere leggibile l'UX: cosa vede l'utente, cosa sta decidendo il sistema e come il risultato diventa revisionabile. Il sorgente mostra poi come quel comportamento è effettivamente implementato.

Leggi il riepilogo dell'implementazione.
Esplora gli stati utente e di sistema.
Ispeziona il codice sorgente tenendo a mente le decisioni di doctrine evidenziate.
SandboxFlusso ispezionabile con confini di sistema visibili

Guida all'interazione

Usa la sandbox per esplorare l'esperienza visibile all'utente, il lavoro del sistema e la scelta di doctrine che l'esempio sta facendo.

Spiegazione UX

La sandbox spiega cosa dovrebbe vedere l'utente, cosa sta facendo il sistema e dove il controllo o l'ispezionabilità devono rimanere espliciti.

Spiegazione AI Design

La pagina trasforma il codice sorgente in un pattern orientato al prodotto: cosa può decidere il modello, cosa dovrebbe esporre il prodotto e dove il codice deterministico o la revisione devono subentrare.

Guida all'interazione

  1. 1Leggi il riepilogo dell'implementazione.
  2. 2Esplora gli stati utente e di sistema.
  3. 3Ispeziona il codice sorgente tenendo a mente le decisioni di doctrine evidenziate.

Visibile all'utente

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.

Lavoro del sistema

Il prodotto prepara un task delimitato per il modello o il workflow.

Perché è importante

L'interfaccia dovrebbe rendere il task delegato leggibile prima che avvenga l'automazione.

Usato in corsi e percorsi

Questo esempio attualmente è indipendente nella libreria, ma si connette comunque al sistema dei principi e alla famiglia di esempi più ampia.

Principi correlati

Runtime architecture

Usa questo esempio nei tuoi agenti

Questo esempio è disponibile anche tramite il layer agent-ready del blueprint. Usa la pagina Per agenti per recuperare MCP pubblico, export deterministici e setup per Claude o Cursor.

Definisci trigger, contesto e confini prima di aumentare l'autonomia
Rendi espliciti controllo, osservabilita e recovery nel runtime
Scegli i pattern operativi giusti prima di delegare ai workflow