self-correcting rag
Self-RAG as a state graph that grades its own documents and answers, and rewrites the question when they fail.
Read the code on GitHub →- Year
- 2024
- Status
- Public on GitHub
- Built with
- Python, LangGraph, LangChain
def decide_to_generate(state):
filtered_documents = state["documents"]
if not filtered_documents:
# All documents have been filtered check_relevance
# We will re-generate a new query
return "transform_query"
return "generate"
workflow = StateGraph(GraphState)
workflow.add_node("retrieve", retrieve)
workflow.add_node("grade_documents", grade_documents)
workflow.add_node("generate", generate)
workflow.add_node("transform_query", transform_query)The Self-RAG paper asks four questions on every turn: should I retrieve, is this passage relevant, is my answer supported by it, and is the answer useful. This project makes each question a node in a LangGraph state machine.
Documents that fail the relevance grade are dropped. If none survive, the question is rewritten and retrieval runs again. An answer that isn't supported by its documents is generated again, and one that's supported but doesn't answer the question sends the graph back to rewrite the question.