Skip to content

< all problems123 · Level 03, RAG

Grade the Retrieval, Then Correct It

medium · implement · RAG

Retrieval returns passages whether or not they answer the question. Implement the knowledge step of Corrective RAG: grade what came back, then keep it, repair it, or replace it with a web search. Write decide(scores, upper=0.5, lower=-0.5) and corrective_rag(question, docs, grade, search, upper=0.5, lower=-0.5, keep=0.0). docs are the retrieved passages; grade(question, text) is the retrieval evaluator (a score from -1 to 1); search(query) returns a list of web passages.

  1. decide returns "correct" if any score is above upper, else "incorrect" if every score is below lower, else "ambiguous". Both comparisons are strict. An empty list is "incorrect".
  2. Grade each document once, with the question, and decide on those scores.
  3. Refine passages: split each with split_strips(text), grade every strip with the question, keep the strips scoring above keep.
  4. correct: refine every retrieved document, whatever its own score. No search.
  5. incorrect: discard the documents, call search once with rewrite_query(question) and refine what it returns.
  6. ambiguous: the refined documents of rule 4, then the refined web passages of rule 5.
  7. Return {"action": the decision, "query": the search query, or None if there was no search, "knowledge": the kept strips}. A strip already in the knowledge is not added again.

The catch. Refining is a filter, not a reranker. Kept strips stay in the order they were written, passage by passage, even when a later strip scored higher: the generator reads sentences in the order their author put them. And the web gets the keywords from rewrite_query, never the question as asked.