Building a Self-Evaluating RAG System: Hybrid Search, Routing, and LLM-as-Judge
Most RAG systems are demos: they retrieve chunks and generate an answer immediately, with no check on whether the retrieved context is relevant, sufficient, or even correct. When retrieval misses, the model hallucinates. There is no recovery loop, no quality signal, and no way to tell which step produced a bad answer.
This post documents how to build a self-evaluating RAG system that routes queries, retrieves with hybrid search, and evaluates its own answers using LLM-as-judge. It is built in three cooperating parts:
- Hybrid search and retrieval — dense + BM25 vectors with int8 quantization in Qdrant, RRF fusion, payload filtering, and multi-year balanced fetch.
- Agent and MCP — a LangGraph ReAct loop with routing guardrails, wrapped in FastMCP and exposed through a Streamlit UI.
- Observability and evaluation — Arize Phoenix tracing plus LLM-as-judge scoring for hallucination, QA correctness, and context relevance.
The LLM provider layer is shared: Ollama (local llama3.2, nomic-embed-text) or Gemini API (gemini-2.5-flash-lite), switchable via environment variable with no code changes.
Three cooperating parts: hybrid retrieval, ReAct agent with MCP, and Phoenix observability with LLM-as-judge
Why demo RAG fails
A standard RAG pipeline looks like this:
user query
|
v
[ embed ] --> [ vector search ] --> [ generate answer ]
It works until it does not. The retriever returns irrelevant chunks, the generator has no way to know, and the user receives a fluent fabrication. There is no signal that the answer is wrong, and no loop to fix it.
A self-evaluating RAG system adds three things:
- Routing: the system decides where to look (vector store, web search, or direct answer) instead of always retrieving.
- Retrieval validation: the system grades retrieved context before generating, and rewrites the query if context is insufficient.
- Self-evaluation: every answer is scored for hallucination, QA correctness, and context relevance, and the scores are written back into the same traces they evaluate.
System architecture
data.csv Qdrant Arize Phoenix
------ ------- -------------
| | |
v v v
+--------+ +----------------+ +------------------+
| ingest |---> dense+| Qdrant: named |<----| query |<--| langgraph_flow |
| .py | BM25 int8| vectors, RRF |----> .py | .py |
+--------+ payload | payload idx | +--------+--------+
+-------+--------+ |
| v
| +----------------+
| | Phoenix traces|
| | + LLM-as-judge|
v +----------------+
+----------+
| agent.py|
| ReAct |
| loop |
+-----+----+
|
v
+----------+
| mcp_server.py |
| FastMCP |
+----------+
|
v
+----------+
| app.py |
| Streamlit|
+----------+
^
|
end user / MCP client
Part 1: Hybrid search and retrieval
The ingestion pipeline starts with data.csv as the source. ingest.py produces dense vectors (via nomic-embed-text or Gemini embeddings) and BM25 vectors, quantizes them to int8, and stores them in Qdrant with:
- Named vectors — separate vector fields for dense and sparse/BM25 representations
- RRF fusion — reciprocal rank fusion combines dense and keyword rankings without per-corpus alpha tuning
- Payload indexes — metadata fields for filtering (year, document type, source)
query.py handles runtime retrieval:
- Hybrid search (dense + BM25)
- Payload filtering (e.g., restrict to a specific year or document type)
- Multi-year balanced fetch — retrieve per year, then compare and summarize across years
langgraph_flow.py orchestrates the workflow: extract years from the query, fetch per-year context, compare, and summarize.
config.py is the single settings file and LLM provider abstraction.
Example ingest flow:
# ingest.py — simplified
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams, Distance, PointStruct
import uuid
client = QdrantClient("http://localhost:6333")
client.recreate_collection(
collection_name="documents",
vectors_config={
"dense": VectorParams(size=768, distance=Distance.COSINE),
"bm25": VectorParams(size=768, distance=Distance.COSINE),
},
quantization_config={
"scalar": {"type": "INT8", "quantile": 0.99, "always_ram": True},
},
)
for record in records:
point = PointStruct(
id=str(uuid.uuid4()),
vector={
"dense": dense_embedding(record["text"]),
"bm25": bm25_embedding(record["text"]),
},
payload={
"text": record["text"],
"year": record["year"],
"source": record["source"],
},
)
client.upsert(collection_name="documents", points=[point])
Runtime hybrid search with RRF:
# query.py — simplified
def hybrid_search(query, year=None, limit=10):
dense_vec = embed(query)
bm25_vec = bm25_embed(query)
prefetch = [
models.Prefetch(
query=dense_vec,
using="dense",
limit=limit,
),
models.Prefetch(
query=bm25_vec,
using="bm25",
limit=limit,
),
]
filter_condition = None
if year:
filter_condition = models.Filter(
must=[models.FieldCondition(key="year", match=models.MatchValue(value=year))]
)
results = client.query_points(
collection_name="documents",
prefetch=prefetch,
query=models.Fusion(fusion=models.Fusion.RRF),
query_filter=filter_condition,
limit=limit,
)
return results.points
Part 2: Agent and MCP
The retrieval layer feeds into a LangGraph ReAct agent (agent.py) that runs a think → act → synthesize loop with routing guardrails:
- Think: analyze the query, decide whether retrieval is needed, and where to route.
- Act: call retrieval, web search, or generate directly based on the routing decision.
- Synthesize: compose the final answer from validated context.
mcp_server.py wraps the agent in FastMCP and exposes three tools to any MCP client:
query_documents— hybrid search + generate over the local corpusweb_search— fallback for out-of-corpus queriesevaluate_answer— LLM-as-judge scoring on a generated answer
app.py is a Streamlit UI with five tabs:
- Data ingestion
- Agent chat
- Qdrant and Phoenix dashboards
- Datasets and experiments
- RAG evaluation
Start the MCP server:
# mcp_server.py — simplified
from fastmcp import FastMCP
mcp = FastMCP("rag-agent")
@mcp.tool()
def query_documents(question: str) -> str:
result = agent.run(question)
return result["answer"]
@mcp.tool()
def web_search(query: str) -> str:
return agent.web_search(query)
@mcp.tool()
def evaluate_answer(question: str, answer: str, context: str) -> dict:
return judge.score(question, answer, context)
if __name__ == "__main__":
mcp.run()
Part 3: Observability and evaluation
Every query produces a full span hierarchy in Arize Phoenix — latency, token counts, and a complete audit trail captured by Phoenix tracing.
phoenix_datasets.py manages versioned query sets and experiment runs, so you can compare how changes to chunking, top-k, or the judge model affect quality over time.
The LLM-as-judge layer runs three evaluators after each query:
| Evaluator | What it checks |
|---|---|
| Hallucination | Did the answer contradict or fabricate beyond the retrieved context? |
| QA correctness | Did the answer actually address the question? |
| Context relevance | Did the retrieved chunks contain what was needed to answer? |
The judge can be Ollama (local llama3.2) or Gemini API (gemini-2.5-flash-lite), selected through the same LLM_PROVIDER switch.
Scores are logged back as span annotations — visible inline with the Phoenix trace, alongside latency:
# phoenix_datasets.py — simplified
from phoenix.client import Client
from phoenix.trace import SpanAnnotationData
px = Client()
annotations = [
SpanAnnotationData(
name="hallucination",
span_id=str(span_id),
annotator_kind="LLM",
result={"label": hallucination_label, "score": 1.0 if hallucination_label == "not_hallucinated" else 0.0},
),
SpanAnnotationData(
name="qa_correctness",
span_id=str(span_id),
annotator_kind="LLM",
result={"label": correctness_label, "score": correctness_score},
),
SpanAnnotationData(
name="context_relevance",
span_id=str(span_id),
annotator_kind="LLM",
result={"label": relevance_label, "score": relevance_score},
),
]
px.annotate_spans(annotations=annotations)
LLM provider layer
All three parts share a single LLM provider abstraction in config.py:
# config.py — simplified
import os
LLM_PROVIDER = os.getenv("LLM_PROVIDER", "ollama") # ollama or gemini
if LLM_PROVIDER == "ollama":
EMBED_MODEL = "nomic-embed-text"
CHAT_MODEL = "llama3.2"
OLLAMA_BASE_URL = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
else:
EMBED_MODEL = "gemini-embedding-001"
CHAT_MODEL = "gemini-2.5-flash-lite"
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
Switching providers requires no code changes — only the LLM_PROVIDER environment variable, or a dropdown in the Streamlit UI.
Running the stack
Prerequisites
- Docker and Docker Compose
- Ollama installed locally (for the local provider option)
- Qdrant (vector database)
- Arize Phoenix (observability)
Docker Compose
# docker-compose.yml
services:
qdrant:
image: qdrant/qdrant:latest
ports:
- "6333:6333"
volumes:
- ./qdrant-data:/qdrant/storage
phoenix:
image: arizephoenix/phoenix:latest
ports:
- "6006:6006"
ollama:
image: ollama/ollama:latest
ports:
- "11434:11434"
volumes:
- ./ollama-data:/root/.ollama
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
rag-agent:
build: .
ports:
- "8501:8501"
environment:
- LLM_PROVIDER=ollama
- QDRANT_HOST=qdrant
- PHOENIX_HOST=phoenix
depends_on:
- qdrant
- phoenix
- ollama
Pull the local models:
docker exec ollama ollama pull llama3.2
docker exec ollama ollama pull nomic-embed-text
Initialize the vector store:
python ingest.py --source data.csv --collection documents
Start the Stack:
docker compose up -d
Open the Streamlit UI at http://localhost:8501.
Evaluation results
On the evaluation dataset, the self-evaluating RAG system produced:
| Metric | Result |
|---|---|
| Hallucination rate | 0% |
| QA correctness | 100% |
| Context relevance | 50% |
The 50% context relevance is expected: out-of-scope queries still retrieve something (the system does not refuse), but what is retrieved is not genuinely relevant. That is not a retrieval failure — it is correct behavior surfaced clearly by the evaluation. The value of closing the evaluation loop inside the observability platform is that you see not just that something went wrong, but which step produced the gap.
What to measure first
If you are building this from scratch, start with these signals:
- Context relevance — are the retrieved chunks actually useful? This is the leading indicator of answer quality.
- Hallucination — does the answer stay within the retrieved context?
- QA correctness — does the answer address the question asked?
- Latency per span — which part of the loop (retrieve, grade, generate) dominates?
- Token counts — input and output tokens per query, for cost tracking.
What we concluded
A self-evaluating RAG system is not much more complex than a demo RAG system, but it changes the operational model entirely:
- Routing prevents unnecessary retrieval for simple queries.
- Hybrid search (dense + BM25 with RRF) catches both semantic and keyword matches.
- Retrieval validation rewrites queries when context is insufficient, instead of generating from bad chunks.
- LLM-as-judge scores every answer for hallucination, correctness, and relevance, and writes the scores back into the traces.
- Shared LLM provider lets you switch between local Ollama and Gemini without code changes.
The result is a system that knows when it does not know, tells you which step failed, and improves observably over time through versioned experiment runs.
Have you run LLM-as-judge evaluation on your RAG system, and which evaluator caught the most issues — hallucination, correctness, or context relevance?