Corrective, Self- and Adaptive RAG¶
RAGAgent lets the model decide when to search and trusts what comes back. These three algorithms put the checking in the algorithm: passages are graded or judged before they are used, a poor result triggers a rewritten query, and the amount of retrieval is matched to the question. All three read your documents through the normal tool pipeline, exactly like RAGAgent:
rag = CorrectiveRAG(index, k=5, web_tool=my_web_search)
ToolHandler(rag.tools).attach(engine) # the search tool (and the fallback tool) live in rag.tools
Like every algorithm, each is a fold of the run's log: parallel grading calls may finish in any order without changing the result, a recorded run replays to the same outcome, and max_calls is the most model calls one run can make. Retrieved text is shown to the model only as quoted data (<passage>...</passage>), and a passage cannot close its own quote.
"""Retrieval that checks itself: CorrectiveRAG grades passages and falls back to a web tool, SelfRAG answers per passage and judges support,
AdaptiveRAG matches retrieval to the question. Scripted model, offline."""
import asyncio
import json
import re
from aaa.algos import AdaptiveRAG, CorrectiveRAG, SelfRAG
from aaa.data import Doc, InMemoryIndex
from aaa.llm import FakeLLMClient, LLMHandler
from aaa.llm.fake import text
from aaa.runtime import Engine
from aaa.tools import ToolHandler, tool
def system_of(request) -> str:
return next((m.content or "" for m in request.messages if m.role == "system"), "")
def user_of(request) -> str:
return next((m.content or "" for m in reversed(request.messages) if m.role == "user"), "")
def between(source: str, tag: str) -> str:
return source.split(f"<{tag}>")[1].split(f"</{tag}>")[0].strip()
async def index_of(*docs: Doc) -> InMemoryIndex:
index = InMemoryIndex()
await index.upsert(list(docs))
return index
FRANCE = Doc(id="fr", text="Paris is the capital of France.")
GERMANY = Doc(id="de", text="Berlin is the capital of Germany.")
BANANAS = Doc(id="bn", text="Bananas are yellow.")
@tool
def web_search(query: str) -> list:
"""Search the web."""
return [{"id": "w1", "text": "France's capital city is Paris."}]
async def run(algorithm, model, task):
async with Engine() as engine:
LLMHandler(FakeLLMClient(model)).attach(engine)
ToolHandler(algorithm.tools).attach(engine)
return await engine.run(algorithm, {"task": task})
def model(request):
s = system_of(request)
if "Judge whether the passage helps" in s:
return text(json.dumps({"relevant": "France" in between(user_of(request), "passage")}))
if "Judge the candidate answer" in s:
ok = "France" in between(user_of(request), "passage")
return text(
json.dumps(
{"relevant": ok, "supported": "full" if ok else "none", "useful": 5 if ok else 1}
)
)
if "Does answering this question need passages" in s:
return text(json.dumps({"retrieve": True}))
if "Choose how to answer" in s:
return text(json.dumps({"route": "iterative"}))
if "You may search the knowledge base" in s:
evidence = user_of(request)
if "Berlin" in evidence:
action = {"action": "answer"}
elif "Paris" in evidence:
action = {"action": "search", "query": "capital of Germany"}
else:
action = {"action": "search", "query": "capital of France"}
return text(json.dumps(action))
ids = re.findall(r"\[([\w:]+)\]", between(user_of(request), "passages"))
return text("Answered from " + ", ".join(ids))
async def corrective() -> None:
out = await run(
CorrectiveRAG(await index_of(GERMANY, BANANAS), web_tool=web_search, max_rewrites=0),
model,
"What is the capital of France?",
)
print(
"corrective:",
out.value["text"],
"| route",
out.value["route"],
"| sources",
out.value["sources"],
)
out = await run(
CorrectiveRAG(await index_of(FRANCE, GERMANY, BANANAS), k=3),
model,
"What is the capital of France?",
)
print(
"corrective:",
out.value["text"],
"| route",
out.value["route"],
"| graded",
out.value["graded"],
"passages",
)
async def self_rag() -> None:
out = await run(
SelfRAG(await index_of(FRANCE, GERMANY), adaptive=True, max_candidates=2),
model,
"What is the capital of France?",
)
print(
"self-rag:",
out.value["text"],
"| supported",
out.value["supported"],
"| from",
out.value["source"],
)
async def adaptive() -> None:
out = await run(
AdaptiveRAG(await index_of(FRANCE, GERMANY), k=1),
model,
"Compare the capitals of France and Germany.",
)
print(
"adaptive:", out.value["route"], "with", out.value["hops"], "searches;", out.value["text"]
)
async def main() -> None:
await corrective()
await self_rag()
await adaptive()
asyncio.run(main())
corrective: Answered from web:w1 | route web | sources ['web:w1']
corrective: Answered from fr | route index | graded 2 passages
self-rag: Answered from fr | supported full | from fr
adaptive: iterative with 2 searches; Answered from fr, de
CorrectiveRAG¶
CorrectiveRAG(index, k=5, web_tool=None, min_relevant=1, max_rewrites=1):
- Search the index; grade each passage (
{"relevant": bool}, one call per passage, in parallel). - At least
min_relevantrelevant: answer from those passages only, with citations. - Otherwise rewrite the query and search again (up to
max_rewrites). - Still not enough and a
web_toolwas given: call it with the last query, grade its results the same way (their ids are prefixedweb:), and answer from the relevant ones plus any relevant index passages. - Nothing relevant anywhere: the run ends
NO_SOLUTIONwith the queries tried. It never answers without evidence.
web_tool is your fallback: any Tool that takes a query argument and returns a list of {"id", "text"} dicts (or text). It is called through the tool pipeline, so approval, timeouts and guards apply, and it only ever receives the rewritten question as its query. Result {"text", "sources", "queries", "route", "graded"} with route index, rewritten or web.
SelfRAG¶
SelfRAG(index, adaptive=True, max_candidates=3, max_rewrites=1):
- With
adaptive, a first call decides whether the question needs retrieval at all (route: "direct"answers without it). - Search; write one candidate answer per passage, so no answer mixes sources.
- Judge every candidate with reflection fields: is the passage
relevant, is the answersupportedby it (full,partial,none), howusefulis it (1 to 5). The best supported, relevant candidate wins (ties go to the earlier passage). - Nothing supported: rewrite the query and repeat (
max_rewrites), then endNO_SOLUTIONcarrying the best candidate, so an unsupported answer is never passed off as grounded.
Result {"text", "source", "supported", "useful", "queries", "rounds", "route"}.
AdaptiveRAG¶
AdaptiveRAG(index, k=5, max_hops=3): a routing call picks how much retrieval the question deserves.
direct: common knowledge, answered without searching.single: one search, then answer from those passages.iterative: up tomax_hopsrounds of "search again or answer" for questions that need several facts; passages accumulate (de-duplicated by id), and a repeated query ends the search.
An unusable routing reply falls back to single. Result {"text", "route", "hops", "sources", "queries"}.
Choosing¶
| Situation | Use |
|---|---|
| The index is good but sometimes misses, and you have a second source | CorrectiveRAG with a web_tool |
| Answers must be traceable to one passage and you want unsupported ones refused | SelfRAG |
| Questions vary from trivia to multi-hop | AdaptiveRAG |
| You just want the model to search as it sees fit | RAGAgent |
Grading and judging are model calls: they reduce, not remove, wrong answers. Use a separate grader_model if the answering model is the one you distrust.