Standard RAG retrieves blindly and trusts the LLM to stay grounded — Self-RAG teaches your agent to decide when retrieval is even needed, score retrieved passages for relevance, verify its own outputs against source documents, and iterate until quality thresholds are met. This lesson walks through building a complete, production-hardened Self-RAG pipeline with async execution, cost controls, and full observability.

Picture a junior analyst who retrieves every document in the filing cabinet before answering any question, even one as simple as "What year was the company founded?" Now picture one who freezes after writing their first draft, convinced it's wrong but unable to say why. Standard RAG systems often behave like the first analyst — retrieving reflexively, regardless of whether retrieval actually helps. Standard LLM pipelines without any self-evaluation behave like the second — generating confidently, with no mechanism to catch errors before they reach the user.
Self-RAG (Self-Reflective Retrieval-Augmented Generation) is a framework that teaches an LLM agent to reason about its own knowledge gaps, decide dynamically whether to retrieve at all, evaluate the relevance and quality of what it retrieves, and then grade its own generated output before returning it to the user. The original paper by Asai et al. (2023) demonstrated that models trained with Self-RAG outperform standard RAG on knowledge-intensive tasks while generating fewer hallucinations — without necessarily needing more retrievals. The insight is that when and how you retrieve matters as much as what you retrieve.
In this lesson, you'll implement a production-grade Self-RAG pipeline from scratch. We won't just translate the academic paper into Python; we'll build a system that handles the messy realities of production: cost constraints, latency budgets, error handling, and observability. By the end, you'll have an agent that decides when to retrieve, scores the retrieved documents, critiques its own answers, and iterates until it meets a quality threshold — or gracefully degrades.
What you'll learn:
You should be comfortable with the core RAG pattern before tackling Self-RAG. If you need a refresher, start with Retrieval-Augmented Generation Explained: How RAG Works and When to Use It and Building a Production Document Q&A System with Vector Embeddings.
You'll also want familiarity with structured output from LLMs — we'll rely on it heavily for the critique steps. The Structured Output: Getting JSON, Tables, and Code from LLMs article covers the patterns we'll use. Working knowledge of async Python and basic familiarity with a vector store (Chroma, Pinecone, or Weaviate) is assumed.
Before writing any code, you need to understand the conceptual architecture. Self-RAG introduces four types of reflection tokens — think of them as internal monologue checkpoints the system makes at specific moments:
Retrieve? — Before generating, should we even look anything up? This is a yes/no gate based on whether the query requires factual grounding beyond what the model already knows.
IsREL (Is Relevant?) — For each retrieved passage, is this passage actually relevant to the query? A retrieval step might return documents that are topically adjacent but not useful.
IsSUP (Is Supported?) — Does the generated response actually use and accurately reflect the retrieved passages? This catches hallucinations that contradict retrieved facts.
IsUSE (Is Useful?) — Is the overall response useful to the user? This is the final quality gate before returning.
In the original paper, these tokens were baked into a specially fine-tuned model. In practice, most production teams implement Self-RAG as a pipeline where each reflection is a separate LLM call with a structured prompt. That's the approach we'll take — it works with any foundation model and gives you full observability into every decision.
Key insight
Self-RAG is not about retrieving more. It's about retrieving smarter and verifying everything. A well-implemented Self-RAG system will often retrieve less than naive RAG while producing better-grounded answers, because it skips retrieval when the model's parametric knowledge is sufficient.
Here's the execution flow we're building:
Query → [Retrieve? Gate] → Branch A (No Retrieval): Generate → [IsUSE?] → Return or Retry
↘ Branch B (Retrieve): Fetch Docs → [IsREL? Filter] → Generate → [IsSUP?] → [IsUSE?] → Return or Retry
Each critique decision can trigger a retry, a retrieval with a different query, or a graceful degradation. We'll implement this as a state machine with an explicit loop budget to prevent runaway API calls.
Let's start with the core data structures:
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
import time
class RetrieveDecision(Enum):
YES = "yes"
NO = "no"
class RelevanceScore(Enum):
RELEVANT = "relevant"
PARTIALLY_RELEVANT = "partially_relevant"
IRRELEVANT = "irrelevant"
class SupportScore(Enum):
FULLY_SUPPORTED = "fully_supported"
PARTIALLY_SUPPORTED = "partially_supported"
NOT_SUPPORTED = "not_supported"
class UtilityScore(Enum):
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
@dataclass
class RetrievedPassage:
content: str
source: str
relevance_score: Optional[RelevanceScore] = None
metadata: dict = field(default_factory=dict)
@dataclass
class SelfRAGState:
query: str
iteration: int = 0
max_iterations: int = 3
retrieve_decision: Optional[RetrieveDecision] = None
retrieved_passages: list[RetrievedPassage] = field(default_factory=list)
filtered_passages: list[RetrievedPassage] = field(default_factory=list)
draft_response: Optional[str] = None
support_score: Optional[SupportScore] = None
utility_score: Optional[UtilityScore] = None
final_response: Optional[str] = None
critique_log: list[dict] = field(default_factory=list)
start_time: float = field(default_factory=time.time)
def log_critique(self, step: str, decision: str, reasoning: str):
self.critique_log.append({
"step": step,
"decision": decision,
"reasoning": reasoning,
"iteration": self.iteration,
"elapsed_ms": int((time.time() - self.start_time) * 1000)
})
The SelfRAGState object is your paper trail. Every critique decision, every iteration, every elapsed millisecond goes in here. When something goes wrong in production — and it will — this log is what you'll debug against. We'll talk more about observability in the instrumentation section.
The first critique is the most impactful: should we retrieve at all? For a question like "What is the capital of France?", retrieval adds latency and cost with zero benefit. For a question like "What were Q3 2024 earnings for ACME Corp?", retrieval is essential.
The gate works by asking the LLM to classify the query based on whether it requires current, specific, or domain-restricted facts.
import openai
import json
from typing import Optional
client = openai.OpenAI()
RETRIEVAL_GATE_PROMPT = """You are a knowledge assessment system. Your job is to determine whether answering a query requires retrieving external documents.
Retrieve when the query requires:
- Specific facts about recent events (after your training cutoff)
- Precise numerical data (financial figures, statistics, measurements)
- Domain-specific details from a particular organization's documents
- Exact quotes, policies, or procedural steps from specific sources
Do NOT retrieve when:
- The answer is general world knowledge any educated person would know
- The query is about concepts, definitions, or reasoning tasks
- The query is conversational or opinion-based
Respond with valid JSON only. No explanation outside the JSON structure.
Query: {query}
Response format:
{{
"decision": "yes" or "no",
"reasoning": "one sentence explaining why"
}}"""
def should_retrieve(query: str, state: SelfRAGState) -> RetrieveDecision:
response = client.chat.completions.create(
model="gpt-4o-mini", # Use a cheap model for the gate — it's a binary classification
messages=[
{
"role": "user",
"content": RETRIEVAL_GATE_PROMPT.format(query=query)
}
],
temperature=0,
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
decision = RetrieveDecision(result["decision"])
state.log_critique(
step="retrieve_gate",
decision=result["decision"],
reasoning=result["reasoning"]
)
return decision
Notice we're using gpt-4o-mini for the gate — this is a deliberate cost optimization. The retrieval gate is a binary classification task. You don't need GPT-4o's reasoning capability for it; you need speed and low cost. We'll use the more capable model for generation and the nuanced critique steps.
Tip
If you're building for a specialized domain, add 2-3 few-shot examples to the gate prompt using queries typical of your users. A financial analyst system will have very different "retrieve vs. don't retrieve" patterns than a general-purpose assistant. See Prompt Engineering Fundamentals for how to structure those examples effectively.
Once we retrieve, we don't just hand everything to the generator. We filter. Each retrieved passage gets an IsREL score, and passages scoring "irrelevant" are dropped before generation. "Partially relevant" passages are included but flagged.
RELEVANCE_PROMPT = """You are evaluating whether a retrieved passage is relevant to answering a query.
Query: {query}
Retrieved Passage:
---
{passage}
---
Assess relevance:
- "relevant": The passage directly addresses the query or contains key facts needed to answer it
- "partially_relevant": The passage contains some useful context but isn't directly about the query
- "irrelevant": The passage doesn't help answer the query at all
Respond with valid JSON only.
{{
"relevance": "relevant" | "partially_relevant" | "irrelevant",
"reasoning": "one sentence explaining the relevance assessment"
}}"""
def score_passage_relevance(
query: str,
passage: RetrievedPassage,
state: SelfRAGState
) -> RetrievedPassage:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": RELEVANCE_PROMPT.format(
query=query,
passage=passage.content
)
}
],
temperature=0,
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
passage.relevance_score = RelevanceScore(result["relevance"])
state.log_critique(
step="relevance_scoring",
decision=result["relevance"],
reasoning=f"Source: {passage.source} | {result['reasoning']}"
)
return passage
def filter_passages(
query: str,
passages: list[RetrievedPassage],
state: SelfRAGState,
min_relevance: RelevanceScore = RelevanceScore.PARTIALLY_RELEVANT
) -> list[RetrievedPassage]:
scored = [score_passage_relevance(query, p, state) for p in passages]
relevance_rank = {
RelevanceScore.RELEVANT: 0,
RelevanceScore.PARTIALLY_RELEVANT: 1,
RelevanceScore.IRRELEVANT: 2
}
min_rank = relevance_rank[min_relevance]
filtered = [
p for p in scored
if relevance_rank[p.relevance_score] <= min_rank
]
# Sort: relevant passages first
filtered.sort(key=lambda p: relevance_rank[p.relevance_score])
return filtered
This parallel scoring step has a meaningful latency implication: if you retrieved 5 passages, you now have 5 sequential relevance calls. In practice, you should run these concurrently. We'll address async execution in the hands-on exercise. For now, the sequential version is easier to reason about while learning the structure.
Warning
Don't be tempted to score relevance entirely with heuristics or embedding similarity. Embedding similarity measures topical overlap, not answering utility. A passage that's topically similar to your query might not contain the specific fact you need. The LLM critique is slower and costs tokens, but it catches these cases. Use embedding-based pre-filtering to get from 1000 candidates to 10, then use LLM-based scoring to get from 10 to 3.
With filtered passages in hand, we generate a response. Then immediately — before returning anything — we apply the IsSUP critique to check whether the response is actually grounded in the retrieved evidence.
GENERATION_PROMPT = """You are a knowledgeable assistant. Answer the query using the provided passages as your primary source of truth.
If the passages don't fully address the query, say so explicitly rather than speculating.
Cite passages when you use specific facts from them.
Query: {query}
Retrieved Passages:
{passages}
Provide a clear, accurate answer."""
SUPPORT_CRITIQUE_PROMPT = """You are a fact-checking system. Evaluate whether a generated response is properly supported by the provided source passages.
Query: {query}
Source Passages:
{passages}
Generated Response:
{response}
Determine support level:
- "fully_supported": Every factual claim in the response can be verified in the passages
- "partially_supported": Most claims are supported, but some facts are added beyond what the passages state
- "not_supported": The response contradicts the passages or makes significant claims not in the passages
Respond with valid JSON only.
{{
"support": "fully_supported" | "partially_supported" | "not_supported",
"unsupported_claims": ["list any specific claims not found in passages, or empty list"],
"reasoning": "brief explanation"
}}"""
def generate_with_context(
query: str,
passages: list[RetrievedPassage],
state: SelfRAGState
) -> str:
passages_text = "\n\n".join([
f"[Source: {p.source}]\n{p.content}"
for p in passages
])
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": GENERATION_PROMPT.format(
query=query,
passages=passages_text
)
}
],
temperature=0.2
)
return response.choices[0].message.content
def score_support(
query: str,
passages: list[RetrievedPassage],
response: str,
state: SelfRAGState
) -> SupportScore:
passages_text = "\n\n".join([
f"[Source: {p.source}]\n{p.content}"
for p in passages
])
result_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": SUPPORT_CRITIQUE_PROMPT.format(
query=query,
passages=passages_text,
response=response
)
}
],
temperature=0,
response_format={"type": "json_object"}
)
result = json.loads(result_response.choices[0].message.content)
support = SupportScore(result["support"])
state.log_critique(
step="support_scoring",
decision=result["support"],
reasoning=f"Unsupported claims: {result['unsupported_claims']} | {result['reasoning']}"
)
return support
The IsSUP critique is where Self-RAG earns its keep. Standard RAG gives the LLM retrieved context and trusts it to stay grounded. That trust is frequently misplaced — LLMs will interpolate from their parametric memory, contradict source documents with confident-sounding confabulations, or simply blend facts from unrelated passages. The support critique catches exactly this.
The final gate is IsUSE: is the response actually useful to the user? This is subtly different from support. A response can be fully grounded in the evidence and still be a useless non-answer — imagine a legal document Q&A where the response is "The document discusses this topic in section 7" rather than actually summarizing what section 7 says.
UTILITY_PROMPT = """You are evaluating the quality and usefulness of a response to a user query.
Query: {query}
Response: {response}
Rate utility:
- "high": The response directly and completely answers the query
- "medium": The response partially answers the query or is accurate but incomplete
- "low": The response fails to answer the query, is too vague, or tells the user to look elsewhere without providing the answer
Respond with valid JSON only.
{{
"utility": "high" | "medium" | "low",
"issues": ["list specific issues with the response, or empty list"],
"improvement_hint": "one sentence on how to improve, or null if utility is high"
}}"""
def score_utility(
query: str,
response: str,
state: SelfRAGState
) -> tuple[UtilityScore, Optional[str]]:
result_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": UTILITY_PROMPT.format(
query=query,
response=response
)
}
],
temperature=0,
response_format={"type": "json_object"}
)
result = json.loads(result_response.choices[0].message.content)
utility = UtilityScore(result["utility"])
improvement_hint = result.get("improvement_hint")
state.log_critique(
step="utility_scoring",
decision=result["utility"],
reasoning=f"Issues: {result['issues']} | Hint: {improvement_hint}"
)
return utility, improvement_hint
Now we assemble the full loop. This is the orchestration layer that ties every component together and enforces the iteration budget:
from typing import Callable
def self_rag_pipeline(
query: str,
retriever: Callable[[str], list[RetrievedPassage]],
max_iterations: int = 3,
min_utility: UtilityScore = UtilityScore.MEDIUM,
require_full_support: bool = False
) -> SelfRAGState:
state = SelfRAGState(
query=query,
max_iterations=max_iterations
)
while state.iteration < state.max_iterations:
state.iteration += 1
# Step 1: Retrieve gate (only on first iteration, or if support failed)
if state.iteration == 1:
state.retrieve_decision = should_retrieve(query, state)
# Step 2: Retrieve and filter if needed
if state.retrieve_decision == RetrieveDecision.YES:
# On retry iterations, modify the query to find better passages
retrieval_query = query
if state.iteration > 1 and state.draft_response:
retrieval_query = f"{query} [Previous attempt was {state.support_score.value if state.support_score else 'low quality'}]"
raw_passages = retriever(retrieval_query)
state.retrieved_passages.extend(raw_passages)
state.filtered_passages = filter_passages(
query,
raw_passages,
state,
min_relevance=RelevanceScore.PARTIALLY_RELEVANT
)
if not state.filtered_passages:
state.log_critique(
step="filter_result",
decision="no_relevant_passages",
reasoning="All retrieved passages were irrelevant. Falling back to parametric knowledge."
)
state.retrieve_decision = RetrieveDecision.NO
# Step 3: Generate
if state.retrieve_decision == RetrieveDecision.YES and state.filtered_passages:
state.draft_response = generate_with_context(
query,
state.filtered_passages,
state
)
else:
# Parametric generation (no retrieval)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": query}],
temperature=0.2
)
state.draft_response = response.choices[0].message.content
# Step 4: Score support (only if we retrieved)
if state.retrieve_decision == RetrieveDecision.YES and state.filtered_passages:
state.support_score = score_support(
query,
state.filtered_passages,
state.draft_response,
state
)
if state.support_score == SupportScore.NOT_SUPPORTED and state.iteration < state.max_iterations:
state.log_critique(
step="loop_control",
decision="retry",
reasoning="Response not supported by passages. Retrying retrieval."
)
continue
if require_full_support and state.support_score == SupportScore.PARTIALLY_SUPPORTED:
if state.iteration < state.max_iterations:
continue
# Step 5: Score utility
utility, improvement_hint = score_utility(query, state.draft_response, state)
state.utility_score = utility
utility_rank = {UtilityScore.HIGH: 0, UtilityScore.MEDIUM: 1, UtilityScore.LOW: 2}
min_rank = utility_rank[min_utility]
if utility_rank[utility] <= min_rank or state.iteration >= state.max_iterations:
state.final_response = state.draft_response
state.log_critique(
step="loop_control",
decision="accept" if utility_rank[utility] <= min_rank else "max_iterations_reached",
reasoning=f"Utility: {utility.value}. Iterations used: {state.iteration}"
)
break
# If utility is too low and we have iterations left, loop
state.log_critique(
step="loop_control",
decision="retry",
reasoning=f"Utility {utility.value} below threshold. Hint: {improvement_hint}"
)
if not state.final_response:
state.final_response = state.draft_response # Graceful degradation
return state
Note
The retrieval_query modification on retry iterations is a simplified example. In production, you'd want a dedicated query rewriting step that takes the critique feedback (specifically the improvement_hint from the utility score and the unsupported_claims from the support score) and reformulates a targeted retrieval query. This is significantly more effective than appending status text to the original query.
The pipeline above expects a retriever callable. Here's how to wire that to a Chroma vector store, following patterns from Building a Production Document Q&A System with Vector Embeddings:
import chromadb
from chromadb.utils import embedding_functions
def build_retriever(
collection_name: str,
n_results: int = 5
) -> Callable[[str], list[RetrievedPassage]]:
"""
Returns a retriever function that queries a Chroma collection.
"""
chroma_client = chromadb.PersistentClient(path="./chroma_db")
ef = embedding_functions.OpenAIEmbeddingFunction(
model_name="text-embedding-3-small"
)
collection = chroma_client.get_collection(
name=collection_name,
embedding_function=ef
)
def retrieve(query: str) -> list[RetrievedPassage]:
results = collection.query(
query_texts=[query],
n_results=n_results,
include=["documents", "metadatas", "distances"]
)
passages = []
for doc, meta, distance in zip(
results["documents"][0],
results["metadatas"][0],
results["distances"][0]
):
# Pre-filter by embedding distance before expensive LLM relevance scoring
# Distance threshold is collection-specific; tune empirically
if distance < 1.2:
passages.append(RetrievedPassage(
content=doc,
source=meta.get("source", "unknown"),
metadata=meta
))
return passages
return retrieve
For production systems, you'll want to layer hybrid search on top of this — combining dense embedding retrieval with BM25 sparse retrieval significantly improves recall for precise queries. The article on Implementing Hybrid Search for RAG: Combining Dense and Sparse Retrieval covers this in depth.
The synchronous pipeline above will work in development but will fall apart in production. Let's address the three critical hardening concerns.
Scoring 5 passages sequentially adds 5 sequential LLM calls before generation even starts. With async execution, those run concurrently:
import asyncio
from openai import AsyncOpenAI
async_client = AsyncOpenAI()
async def score_passage_relevance_async(
query: str,
passage: RetrievedPassage,
state: SelfRAGState
) -> RetrievedPassage:
response = await async_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": RELEVANCE_PROMPT.format(
query=query,
passage=passage.content
)
}
],
temperature=0,
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
passage.relevance_score = RelevanceScore(result["relevance"])
state.log_critique(
step="relevance_scoring",
decision=result["relevance"],
reasoning=f"Source: {passage.source} | {result['reasoning']}"
)
return passage
async def filter_passages_async(
query: str,
passages: list[RetrievedPassage],
state: SelfRAGState,
min_relevance: RelevanceScore = RelevanceScore.PARTIALLY_RELEVANT
) -> list[RetrievedPassage]:
# Score all passages concurrently
tasks = [
score_passage_relevance_async(query, p, state)
for p in passages
]
scored = await asyncio.gather(*tasks)
relevance_rank = {
RelevanceScore.RELEVANT: 0,
RelevanceScore.PARTIALLY_RELEVANT: 1,
RelevanceScore.IRRELEVANT: 2
}
min_rank = relevance_rank[min_relevance]
filtered = [
p for p in scored
if relevance_rank[p.relevance_score] <= min_rank
]
filtered.sort(key=lambda p: relevance_rank[p.relevance_score])
return filtered
For patterns on managing concurrency and rate limits across many parallel LLM calls, the Orchestrating Parallel LLM Calls article is essential reading.
The critique_log in SelfRAGState gives you the data; you need to ship it somewhere useful. Here's a minimal structured logging setup:
import logging
import json
from datetime import datetime
logger = logging.getLogger("self_rag")
def emit_pipeline_trace(state: SelfRAGState):
"""Emit structured trace data for observability tooling."""
trace = {
"timestamp": datetime.utcnow().isoformat(),
"query": state.query,
"total_iterations": state.iteration,
"retrieve_decision": state.retrieve_decision.value if state.retrieve_decision else None,
"passages_retrieved": len(state.retrieved_passages),
"passages_after_filter": len(state.filtered_passages),
"final_support_score": state.support_score.value if state.support_score else None,
"final_utility_score": state.utility_score.value if state.utility_score else None,
"total_elapsed_ms": int((time.time() - state.start_time) * 1000),
"critique_log": state.critique_log
}
logger.info("self_rag_trace", extra={"trace": json.dumps(trace)})
return trace
For a production observability stack, plug this into your existing tracing infrastructure. The article on Implementing LLM Observability: Tracing, Logging, and Monitoring Requests in Production covers how to structure spans and attributes for tools like LangSmith, Weights & Biases, or OpenTelemetry.
A Self-RAG pipeline with 3 iterations and 5 passages can generate 20+ LLM calls per query. That adds up fast. Here's a cost estimation helper:
# Approximate token costs (update with current pricing)
MODEL_COSTS_PER_1K = {
"gpt-4o": {"input": 0.0025, "output": 0.010},
"gpt-4o-mini": {"input": 0.000150, "output": 0.000600}
}
def estimate_pipeline_cost(state: SelfRAGState) -> dict:
"""
Rough cost estimation based on critique log step counts.
In production, capture actual token counts from API responses.
"""
# Count critique calls by model
gate_calls = sum(1 for c in state.critique_log if c["step"] == "retrieve_gate")
relevance_calls = sum(1 for c in state.critique_log if c["step"] == "relevance_scoring")
support_calls = sum(1 for c in state.critique_log if c["step"] == "support_scoring")
utility_calls = sum(1 for c in state.critique_log if c["step"] == "utility_scoring")
# Mini model calls: gate + relevance + support + utility
mini_calls = gate_calls + relevance_calls + support_calls + utility_calls
# Full model calls: generation (one per iteration)
full_calls = state.iteration
# Rough token estimates per call type
mini_cost = mini_calls * (500 * MODEL_COSTS_PER_1K["gpt-4o-mini"]["input"] / 1000 +
100 * MODEL_COSTS_PER_1K["gpt-4o-mini"]["output"] / 1000)
full_cost = full_calls * (2000 * MODEL_COSTS_PER_1K["gpt-4o"]["input"] / 1000 +
500 * MODEL_COSTS_PER_1K["gpt-4o"]["output"] / 1000)
return {
"estimated_total_usd": round(mini_cost + full_cost, 5),
"mini_model_calls": mini_calls,
"full_model_calls": full_calls,
"total_llm_calls": mini_calls + full_calls
}
Warning
Self-RAG's cost model is fundamentally different from naive RAG. You're trading retrieval + one generation for retrieval + N generation + M critique calls. For high-traffic production systems, you need to set hard limits on max_iterations and consider whether the quality improvement justifies the cost per query. For most Q&A use cases, max_iterations=2 with the min_utility=MEDIUM threshold hits a good cost/quality balance. Detailed token-level cost optimization strategies are covered in Cost Optimization: Token Counting, Caching, and Model Selection for LLMs.
Let's wire everything together with a realistic scenario: a financial analyst Q&A system where users ask questions about earnings reports.
# Assuming you've already built and populated a Chroma collection
# with chunked earnings documents
def run_analyst_qa(query: str) -> dict:
retriever = build_retriever(
collection_name="earnings_reports",
n_results=6
)
state = self_rag_pipeline(
query=query,
retriever=retriever,
max_iterations=2, # Keep costs predictable
min_utility=UtilityScore.MEDIUM,
require_full_support=True # Financial data must be grounded
)
cost = estimate_pipeline_cost(state)
trace = emit_pipeline_trace(state)
return {
"answer": state.final_response,
"confidence": {
"support": state.support_score.value if state.support_score else "not_applicable",
"utility": state.utility_score.value if state.utility_score else "unknown"
},
"sources": [p.source for p in state.filtered_passages],
"retrieved": state.retrieve_decision == RetrieveDecision.YES,
"iterations_used": state.iteration,
"estimated_cost_usd": cost["estimated_total_usd"],
"critique_log": state.critique_log
}
# Example queries demonstrating the gate in action
queries = [
"What is revenue recognition under ASC 606?", # Should NOT retrieve (general knowledge)
"What was ACME Corp's gross margin in Q3 2024?", # SHOULD retrieve (specific fact)
"Explain the difference between GAAP and non-GAAP earnings" # Should NOT retrieve
]
for q in queries:
result = run_analyst_qa(q)
print(f"\nQuery: {q}")
print(f"Retrieved: {result['retrieved']}")
print(f"Iterations: {result['iterations_used']}")
print(f"Support: {result['confidence']['support']}")
print(f"Utility: {result['confidence']['utility']}")
print(f"Cost: ${result['estimated_cost_usd']}")
print(f"Answer preview: {result['answer'][:200]}...")
This output tells you everything you need to monitor the system in production. If the retrieval gate starts triggering for general knowledge questions (expensive and unnecessary), you know to adjust your gate prompt. If support scores are consistently "partially_supported," you have a retrieval quality problem or a chunking problem.
Build a Self-RAG system for a customer support use case. Use the following specification:
Scenario: A SaaS company's customer support bot. The knowledge base contains product documentation, FAQs, and release notes. Users ask a mix of product-specific questions and general software/tech questions.
Your tasks:
Customize the retrieval gate for a customer support context. Add 3 few-shot examples that reflect the boundary between "general tech knowledge" and "product-specific knowledge" for a SaaS product.
Implement async passage scoring using asyncio.gather() as shown in the async section. Measure the latency difference between sequential and concurrent scoring on 5 passages.
Add a query rewriting step that runs when the support score is NOT_SUPPORTED. The rewriter should take the original query and the list of unsupported_claims from the support critique and generate 2-3 alternative search queries that might surface better supporting evidence.
Implement a cache layer in front of the retrieval gate: if the same query (or a semantically similar one) has been seen before with the same retrieve decision, return the cached decision rather than making an LLM call. Use embedding similarity with a threshold of 0.95 for semantic deduplication. This pattern is detailed in Implementing LLM Response Caching with Redis.
Build a simple evaluation harness using 20 test queries with known answers. Measure: percentage of questions where retrieval was (correctly) triggered, average iterations per query, and percentage of responses scoring "fully_supported". Compare against a baseline naive RAG implementation. Refer to Testing and Evaluating LLM Applications for evaluation design patterns.
Symptom: retrieve_decision is consistently YES even for clearly general knowledge questions.
Cause: Your gate prompt doesn't include examples of the domain-specific boundary. A general "is this world knowledge?" prompt will decide conservatively and retrieve often.
Fix: Add 3-5 few-shot examples specific to your domain showing clear YES/NO cases. Tune the gate on a held-out sample of queries before deploying.
Symptom: The pipeline always uses all max_iterations on certain query types.
Cause: Your knowledge base doesn't contain documents that can answer the question. Every retrieval returns irrelevant passages, the support score stays low, the loop retries — but the underlying problem (missing documents) never resolves.
Fix: Distinguish between "the LLM didn't use the passages" (a generation problem) and "no relevant passages exist" (a knowledge base gap). Log the case where filtered_passages is empty after multiple retrieval attempts, and route to a "knowledge gap" response rather than continuing to loop.
# Add to loop control logic
if len(state.filtered_passages) == 0 and state.iteration >= 2:
state.final_response = (
"I don't have specific documentation to answer this question accurately. "
"Please contact support directly."
)
state.log_critique(
step="loop_control",
decision="knowledge_gap",
reasoning="No relevant passages found after multiple retrieval attempts."
)
break
Symptom: Responses that are factually correct get marked NOT_SUPPORTED because they include commonsense context not in the retrieved passages.
Cause: The IsSUP prompt is evaluating completeness against passages rather than contradiction with passages. If you retrieved "ACME Corp revenue was $4.2B" and the response says "ACME Corp had a strong Q3, with revenue reaching $4.2B, beating analyst estimates by 3%," the analyst estimate detail will trigger a not-supported score even if it's accurate.
Fix: Revise the support critique to focus on contradictions rather than additive information:
The key question is: does the response contradict the passages, or does it accurately
represent what the passages say? Additional context drawn from general knowledge is
acceptable as long as it doesn't contradict the passages.
Symptom: End-to-end latency exceeds your SLA (typically 3-5s for a user-facing application).
Cause: With synchronous execution, a single-iteration path through Self-RAG might be: gate call (1s) + 5 relevance calls (5s) + generation (3s) + support call (1s) + utility call (1s) = 11s. That's 3-4x worse than naive RAG.
Fix: Profile your bottlenecks and apply several strategies together:
Symptom: The quality of critique decisions degrades gradually over weeks without any code changes.
Cause: Prompt performance can drift as the underlying model is updated by the provider, as your document corpus changes, or as the query distribution shifts.
Fix: Version your critique prompts and run weekly regression tests against a fixed evaluation set. Track the percentage of queries where the critique decisions agree with human labels. The Prompt Versioning and Management article covers the infrastructure for this.
Key insight
The Self-RAG critique calls are only as good as their prompts. Unlike your generation prompt, the critique prompts are definitionally about evaluation — they need to be more precise, more structured, and more rigorously tested than the prompts you use to generate answers. Invest in few-shot examples and regression tests for every critique prompt you write.
When you're handling hundreds of requests per minute, the synchronous state machine described above needs architectural upgrades.
Separate the critique workers. In a high-volume system, you don't want critique calls and generation calls competing for the same thread pool. Separate them into distinct worker pools with separate rate limit budgets. The gate and relevance scoring (mini model, fast) can run in a high-concurrency pool; generation (full model, slow) runs in a smaller pool.
Consider asynchronous, non-blocking pipelines. For non-real-time use cases (batch report generation, overnight processing), implement the Self-RAG loop as a task queue. Submit the query, get a job ID, poll for completion. This lets you process hundreds of queries concurrently without worrying about per-request latency.
Cache aggressively at every layer. The retrieval gate result for "What year was ACME Corp founded?" is deterministic — cache it for 24 hours. Retrieved passage relevance scores for a given (query, passage) pair are deterministic — cache them. Each cached decision saves a mini model call.
Monitor your critique quality, not just your response quality. A standard RAG system is easy to evaluate: did the response match the expected answer? A Self-RAG system has intermediate outputs that also need monitoring. Add dashboards tracking: retrieval gate trigger rate, average relevance score distribution, support score distribution, average iterations per query. Anomalies in these metrics are early warning signs of system degradation.
Self-RAG transforms a retrieval pipeline from a passive lookup mechanism into an active reasoning system. By teaching your agent to decide when to retrieve, evaluate what it retrieves, verify that its output is grounded, and judge whether that output is actually useful — you close the feedback loop that standard RAG leaves open.
The key architectural decisions you've learned to make:
critique_log is your primary debugging tool.From here, there are several natural directions to deepen this system:
Query rewriting for failed retrievals: When support scoring fails, don't just retry with the same query — have a dedicated query rewriter analyze the unsupported claims and generate targeted alternative queries. This is closely related to multi-hop reasoning patterns covered in Building a Knowledge Graph-Augmented RAG System.
Active learning from critique data: Every critique decision is labeled training data. Collect the cases where the critique disagreed with human judgment and use them to improve your critique prompts. The Building a Feedback Collection and Human Preference Dataset Pipeline article covers how to operationalize this.
Self-improving retrieval: Use the support and utility scores as a feedback signal to improve the retrieval layer itself — downranking passages that consistently score "irrelevant" and upranking those that consistently score "relevant." This is the core idea behind Building a Self-Improving RAG Pipeline.
Agentic escalation: When Self-RAG exhausts its iteration budget without reaching a satisfactory answer, that's not a failure — it's a signal that human escalation is appropriate. Connect your loop control's "max_iterations_reached" exit to a human-in-the-loop workflow, as described in Agentic Loop Design.
The analytical instinct you need to build great Self-RAG systems is the same one that makes a good editor: not just asking "is this answer correct?" but "how do I know it's correct, and what would I need to see to believe it?" Build that instinct into your pipeline, and you'll ship systems that are genuinely trustworthy — not just confident.