Grade the Retrieval, Then Correct It
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.
decidereturns"correct"if any score is aboveupper, else"incorrect"if every score is belowlower, else"ambiguous". Both comparisons are strict. An empty list is"incorrect".- Grade each document once, with the question, and
decideon those scores. - Refine passages: split each with
split_strips(text), grade every strip with the question, keep the strips scoring abovekeep. - correct: refine every retrieved document, whatever its own score. No search.
- incorrect: discard the documents, call
searchonce withrewrite_query(question)and refine what it returns. - ambiguous: the refined documents of rule 4, then the refined web passages of rule 5.
- 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.