Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 3

Grading Evidence and Retrying

Grade retrieved passages for relevance and sufficiency separately, then rewrite the query, search another source or abstain within a fixed budget of attempts; run a loop that fails then recovers, one that falls back to the web and one that abstains, and break the fixture to prove it.

Contentsand lesson path

What you will learn

  • Grade retrieved evidence for relevance and sufficiency, then re-retrieve, search elsewhere or abstain within a bounded number of attempts.

Prerequisites: RAG Foundations, Agent Loops & ReAct

01. Goal and setup

A single pass hands whatever it retrieved to the model. This lab inserts a grader between retrieval and answer, and gives the loop three ways to react when the evidence is not good enough: rewrite the query, search another source, or stop and say so. Two questions are kept apart throughout:

  • Relevance: is the passage about the question at all?
  • Sufficiency: does it actually contain the kind of answer asked for, such as a duration, a number or a command?

A passage about the dead-letter queue is relevant to which command empties it?, but it is not sufficient if it names no command. A loop that checks only relevance answers from on-topic passages that lack the fact, which is how confident wrong answers are made.

How published methods do it. Corrective RAG (CRAG, Yan et al., 2024) fine-tunes a small T5-large model to score each retrieved document against the question, on a scale from −1 to 1. Two thresholds, tuned per dataset (for PopQA the paper uses 0.59 and −0.99), sort a retrieval into three actions. Correct (some document above the upper threshold): the documents are still refined by splitting them into short strips and keeping only the relevant ones. Incorrect (all below the lower threshold): the documents are discarded and a web search runs with the question rewritten as keywords. Ambiguous (in between): both kinds of knowledge are combined. Self-RAG (Asai et al., 2023) instead trains the generator itself to emit reflection tokens that judge whether to retrieve and whether a passage is relevant and supports the answer.

In production the grader is usually a call to a small, fast model with a prompt that asks for both judgements, or a cross-encoder reranker score for relevance plus a model call for sufficiency. A cross-encoder scores each passage separately, while a model grader can judge a batch of hits in one call, as corrective.py below counts it. Either way, measure it: the RAG Foundations reranking lab timed a small cross-encoder on CPU. Read the model name from configuration, for example a GRADER_MODEL environment variable, so that you can change it without touching the code.

In this lab the grader is a FAKE: a few transparent rules, so the runs are reproducible and you can see why each verdict was given. You need: the agentic-lab folder from lessons 2 and 3, with the fixture restored by python make_fixture.py.

New files in agentic-lab/
agentic-lab/
├── grader.py      step 1: FAKE relevance and sufficiency grader
└── corrective.py  step 2: the loop with a budget and an abstain path

02. Step 1: A grader that separates relevance from sufficiency

grade() scores relevance as the share of the question's content words that appear in the passage, after expand() has swapped user words for the words the docs use (the glossary stands in for what a model knows about synonyms). It calls a passage relevant at 0.6 or above. That cut-off is this lab's illustrative value, chosen for a 14-passage fixture; for a real grader, calibrate it on labelled answerable and unanswerable questions as in the Grounding and Citations abstain lab.

Sufficiency needs a relevant passage and one sentence in it that holds the kind of answer the question asks for and shares a content word with the question. How long needs a duration, how many a number, which command something in backticks. The best such sentence becomes the support that the answer quotes; CRAG's refinement step does the same thing, keeping strips rather than whole documents.

Python · grader.py
"""FAKE grader: transparent rules standing in for a model or cross-encoder judge."""
import re

from search import terms

GLOSSARY = {"parked": "dead-letter queue", "kept": "stays",  # stands in for what
            "removed": "deleted", "empties": "purge"}  # a model knows about words
GENERIC = {"larkspur", "job"}
ANSWER_TYPES = [  # (the question asks..., the evidence must contain...)
    (r"^how long", r"\b\d+ (?:seconds|minutes|hours|days)\b"),
    (r"\bcommand\b", r"`[^`]+`"),
    (r"^how many|\bnumber\b", r"\b\d+\b"),
    (r"\bversion\b", r"\b\d+\.\d+\b"),
]


def expand(question: str) -> str:
    """FAKE rewrite: swap user words for the words the docs use."""
    words = re.findall(r"[a-z0-9-]+", question.lower())
    return " ".join(terms(" ".join(GLOSSARY.get(w, w) for w in words)))


def grade(question: str, passage: str) -> dict:
    """Relevant: on topic. Sufficient: a sentence holds the kind of answer asked."""
    need = set(terms(expand(question))) - GENERIC
    relevance = len(need & set(terms(passage))) / max(len(need), 1)
    wanted = next((a for q, a in ANSWER_TYPES if re.search(q, question.lower())),
                  r"\w")
    support = sorted((s for s in re.split(r"(?<=\.) ", passage)
                      if re.search(wanted, s) and need & set(terms(s))),
                     key=lambda s: -len(need & set(terms(s))))  # best first
    relevant = relevance >= 0.6  # this lab's cut-off; calibrate yours on labels
    return {"relevance": round(relevance, 2), "relevant": relevant,
            "sufficient": relevant and bool(support),
            "support": support[0] if relevant and support else None}


if __name__ == "__main__":  # self-check: the same passage, two questions
    passage = ("After the last retry, the job moves to the dead-letter queue. It stays"
               " there for 14 days and is then deleted.")
    for question in ("How long is a parked run kept before it is removed?",
                     "Which command empties the parked jobs queue?"):
        g = grade(question, passage)
        print(f"{question}\n  relevance {g['relevance']:.2f}, relevant {g['relevant']},"
              f" sufficient {g['sufficient']}")

The self-check grades the dead-letter passage against two questions. It is relevant to both, but sufficient only for the one that asks for a duration.

Terminal
python grader.py
Expected output
How long is a parked run kept before it is removed?
  relevance 0.71, relevant True, sufficient True
Which command empties the parked jobs queue?
  relevance 0.60, relevant True, sufficient False

03. Step 2: The loop with a budget

corrective() follows a fixed plan of at most three attempts, which is the default budget max_retries=2:

  1. the document index with the question as asked;
  2. the document index with the rewritten query;
  3. web search with the rewritten query: another source, as in CRAG's Incorrect action.

After each attempt it grades every hit. The first sufficient passage ends the loop, and the answer quotes its support sentence with the source; an answer from the web says that it comes from a public page. If no attempt is sufficient, the loop abstains and lists every query it ran, so a person can see what was tried. The function also counts calls: one tool call and one grading call per attempt, one rewrite call reused by later attempts, and one answer call.

Python · corrective.py
"""Retrieve, grade, then rewrite, search elsewhere or abstain, within a budget."""
import sys
import textwrap

from grader import expand, grade
from tools import fetch

SCOPE = "acme:staff"
PLAN = [("search_docs", "as asked"), ("search_docs", "rewritten"),  # attempt 1, 2
        ("web_search", "rewritten")]  # attempt 3: another source


def corrective(question: str, max_retries: int = 2, log=print) -> dict:
    calls = {"tool": 0, "model": 0}
    tried, rewritten = [], None
    for attempt, (tool, form) in enumerate(PLAN[: 1 + max_retries], start=1):
        if form == "rewritten" and rewritten is None:
            rewritten = expand(question)
            calls["model"] += 1  # one rewrite call, reused by later attempts
        query = question if form == "as asked" else rewritten
        hits = fetch(tool, {"query": query, "k": 3} if tool == "search_docs"
                     else {"query": query}, SCOPE).get("hits", [])
        calls["tool"] += 1
        calls["model"] += 1  # one grading call for the whole batch of hits
        log(f"attempt {attempt}: {tool} {query!r}")
        tried.append(f"{tool} {query!r}")
        for hit in hits:
            g = grade(question, hit["text"])
            verdict = ("SUFFICIENT" if g["sufficient"] else
                       "relevant, insufficient" if g["relevant"] else "irrelevant")
            log(f"  {hit['id']}: relevance {g['relevance']:.2f}, {verdict}")
            if g["sufficient"]:
                calls["model"] += 1  # the answer call
                web = " (public web page, not our docs)" if tool == "web_search" else ""
                return {"answer": f"{g['support']} [{hit['id']}]{web}",
                        "attempts": attempt, "calls": calls}
        if not hits:
            log("  no results")
    return {"answer": "ABSTAIN: no sufficient evidence after "
                      f"{len(tried)} attempts ({'; '.join(tried)})",
            "attempts": len(tried), "calls": calls}


QUESTIONS = ["How long is a parked run kept before it is removed?",
             "Which command empties the parked jobs queue?",
             "Can Larkspur run jobs on a GPU?"]
if __name__ == "__main__":
    for q in sys.argv[1:] or QUESTIONS:
        print(f"Q: {q}")
        result = corrective(q)
        print(textwrap.fill(f"A: {result['answer']}", 86, subsequent_indent="   "))
        print(f"   attempts: {result['attempts']}, calls: {result['calls']}\n")

Try it on a question the docs answer directly; it should stop after one attempt:

Terminal
python corrective.py "How many requests per minute may each token make?"
Expected output
Q: How many requests per minute may each token make?
attempt 1: search_docs 'How many requests per minute may each token make?'
  api#rate-limits: relevance 1.00, SUFFICIENT
A: Each token may make 60 requests per minute. [api#rate-limits]
   attempts: 1, calls: {'tool': 1, 'model': 2}

04. Step 3: Run three questions

Terminal
python corrective.py
Expected output
Q: How long is a parked run kept before it is removed?
attempt 1: search_docs 'How long is a parked run kept before it is removed?'
  configuration#workers: relevance 0.14, irrelevant
  retries#timeouts: relevance 0.14, irrelevant
  install#upgrading: relevance 0.14, irrelevant
attempt 2: search_docs 'long dead letter queue run stay deleted'
  retries#dead-letter-queue: relevance 0.71, SUFFICIENT
A: It stays there for 14 days and is then deleted. [retries#dead-letter-queue]
   attempts: 2, calls: {'tool': 2, 'model': 4}

Q: Which command empties the parked jobs queue?
attempt 1: search_docs 'Which command empties the parked jobs queue?'
  retries#dead-letter-queue: relevance 0.60, relevant, insufficient
  configuration#workers: relevance 0.00, irrelevant
  retries#timeouts: relevance 0.00, irrelevant
attempt 2: search_docs 'command purge dead letter queue job queue'
  retries#dead-letter-queue: relevance 0.60, relevant, insufficient
  configuration#workers: relevance 0.00, irrelevant
  retries#timeouts: relevance 0.00, irrelevant
attempt 3: web_search 'command purge dead letter queue job queue'
  https://example.org/larkspur-3-2: relevance 1.00, SUFFICIENT
A: Larkspur 3.2 release notes: adds the `larkspur dlq purge` command to empty the
   dead-letter queue. [https://example.org/larkspur-3-2] (public web page, not our
   docs)
   attempts: 3, calls: {'tool': 3, 'model': 5}

Q: Can Larkspur run jobs on a GPU?
attempt 1: search_docs 'Can Larkspur run jobs on a GPU?'
  configuration#workers: relevance 0.50, irrelevant
  install#upgrading: relevance 0.50, irrelevant
  retries#timeouts: relevance 0.50, irrelevant
attempt 2: search_docs 'larkspur run job gpu'
  configuration#workers: relevance 0.50, irrelevant
  install#upgrading: relevance 0.50, irrelevant
  retries#timeouts: relevance 0.50, irrelevant
attempt 3: web_search 'larkspur run job gpu'
  https://example.net/larkspur-tips: relevance 0.50, irrelevant
  https://example.org/larkspur-3-2: relevance 0.00, irrelevant
A: ABSTAIN: no sufficient evidence after 3 attempts (search_docs 'Can Larkspur run
   jobs on a GPU?'; search_docs 'larkspur run job gpu'; web_search 'larkspur run job
   gpu')
   attempts: 3, calls: {'tool': 3, 'model': 4}

Each question takes a different path:

  • Fail, then recover. The first search for a parked run kept before it is removed matches only the word run, and every hit is irrelevant. The rewrite uses the docs' words, dead-letter queue, stays and deleted; the second attempt finds the passage, and 14 days is the duration asked for. Two attempts: two tool calls and four model calls.
  • Relevant but insufficient. For which command empties the parked jobs queue? the dead-letter passage is on topic (0.60) but names no command, so it is never used as an answer. The rewrite returns the same passages, and the third attempt searches the web, where a release note names larkspur dlq purge. The answer is flagged as coming from a public page: the docs do not confirm it, and a reader should know that.
  • Nothing anywhere. Nothing mentions GPUs. Three attempts (three tool calls, four model calls), then an abstention that lists all three queries. This is the loop working as designed, not a failure of it.

05. Step 4: Remove the evidence and watch it abstain

A loop that always ends in an answer may be answering from somewhere you did not intend. Remove the dead-letter passage from the index and ask the first question again. Every attempt should fail, and the run should stop after the third.

Terminal
python break_fixture.py retries#dead-letter-queue
python corrective.py "How long is a parked run kept before it is removed?"
Expected output
13 passages left
Q: How long is a parked run kept before it is removed?
attempt 1: search_docs 'How long is a parked run kept before it is removed?'
  configuration#workers: relevance 0.14, irrelevant
  retries#timeouts: relevance 0.14, irrelevant
  install#upgrading: relevance 0.14, irrelevant
attempt 2: search_docs 'long dead letter queue run stay deleted'
  configuration#workers: relevance 0.14, irrelevant
  retries#timeouts: relevance 0.14, irrelevant
  install#upgrading: relevance 0.14, irrelevant
attempt 3: web_search 'long dead letter queue run stay deleted'
  https://example.net/larkspur-tips: relevance 0.57, irrelevant
  https://example.org/larkspur-3-2: relevance 0.43, irrelevant
A: ABSTAIN: no sufficient evidence after 3 attempts (search_docs 'How long is a parked
   run kept before it is removed?'; search_docs 'long dead letter queue run stay
   deleted'; web_search 'long dead letter queue run stay deleted')
   attempts: 3, calls: {'tool': 3, 'model': 4}

The web pages mention the dead-letter queue, so they reach 0.57 and 0.43, but neither clears the 0.6 cut-off or holds a duration, and the loop abstains instead of quoting them. Restore the passage before lesson 5.

Terminal
python make_fixture.py
Expected output
docs: 14 passages, web: 2 pages
people 3
teams 4
runs 93
payroll 2

06. Choosing the budget and the stopping rule

The budget bounds the worst case: here at most three tool calls and five model calls per question, whatever the question. Without it, a question with no answer in any source keeps the loop running until a timeout, and the time and money spent are highest exactly where the result is a refusal. Some rules that keep the budget useful:

  • Count attempts, not opinions. Stop on a counter or a time limit, never because the model feels it has enough; that judgement is what failed in the first place.
  • Stop early when a retry cannot help. In the purge question the rewrite returned the same passages as the first attempt. A loop can notice that and move on to the next source, saving a grading call.
  • Answer the part you can. For a two-part question with evidence for one part, answer that part with its citation and say what is missing. A full refusal discards grounded work; filling the gap from model memory adds an unsupported claim.
  • Log every attempt. The queries, verdicts and sources of each attempt are what you need to debug a wrong answer or to tune the cut-off.

Choose the budget from measurements: on your labelled questions, look at how many attempts the questions that were eventually answered needed. If almost every success comes on attempt 1 or 2, a third attempt mostly adds cost to questions that end in a refusal anyway.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Grading and retrying

Use the three runs and the code to answer.

Q1. The purge run printed `calls: {'tool': 3, 'model': 5}`. You add the early switch from "Stop early when a retry cannot help": when an attempt returns the same hits as the one before, the loop moves on to the next source. What does the purge run print now?
Q2. What is the main risk of the loop's third attempt, which searches the public web?
Q3. In the CRAG paper, what happens when at least one retrieved document scores above the upper threshold?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the practice project, the agent must grade relevance and retry at most twice:

  1. Replace grade() with a model call that returns, per passage, a relevance verdict, a sufficiency verdict and the supporting sentence. Reject a sufficiency verdict whose sentence is not in the passage.
  2. Label 20 question and passage pairs by hand (relevant or not, sufficient or not) and measure how often your grader agrees with you before you trust it.
  3. Keep the budget of three attempts, add the early switch when a rewrite returns the same passages, and record the attempt number of every answer.
  4. Add a partial-answer path for two-part questions, and a test that removes a passage and expects an abstention.

10. Review prompt

Without looking back:

  1. Define relevance and sufficiency, and give a passage that is one but not the other.
  2. Describe CRAG's three actions and what decides between them.
  3. What does the loop do on each of its three attempts, and what does its abstention contain?
  4. Why should a loop stop on a counter rather than on the model's judgement?
  5. How would you choose the retry budget for your own system?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check