Search Tutorials
--Ads--Project 6: RAG Evaluation Dashboard
Compare RAG configurations side by side on a golden test set.
The final project builds the tool that ties everything together: an evaluation runner that tests several RAG configurations on your golden test set, and a dashboard to compare them. With it, every technique in this tutorial (chunk sizes, hybrid search, reranking, prompts, effort levels) becomes a measurable experiment instead of a guess.
What you will build
- eval_runner.py: runs each configuration over the golden set and records per-question results: retrieval hit and reciprocal rank, LLM-judged correctness, latency and token usage.
- dashboard.py: a Streamlit app showing a summary table, metric charts, per-category breakdowns and a side-by-side view of answers that differ between two configurations.
pip install anthropic sentence-transformers rank-bm25 numpy pandas streamlit
The evaluation runner
It reuses components from earlier lessons: the dense and hybrid retrievers, the cross-encoder reranker and the correctness judge. The golden set is the JSONL file from Building a Golden Test Set.
"""Run RAG configurations over a golden set. python eval_runner.py"""
import json
import time
from dataclasses import dataclass
from pathlib import Path
import anthropic
from sentence_transformers import CrossEncoder
from hybrid import HybridRetriever # hybrid search lesson
from judge import grade # LLM-as-judge lesson
from retriever import DenseRetriever # top-k search lesson
client = anthropic.Anthropic()
records = json.loads(Path("index/chunks.json").read_text(encoding="utf-8"))
texts = [r["text"] for r in records]
golden = [json.loads(line) for line in open("golden_set.jsonl", encoding="utf-8")]
dense = DenseRetriever(records)
hybrid = HybridRetriever(texts)
reranker = CrossEncoder("BAAI/bge-reranker-base")
@dataclass
class Config:
name: str
retrieval: str # "dense" | "hybrid" | "hybrid+rerank"
k: int = 4
effort: str = "low"
CONFIGS = [
Config("dense-k4", "dense"),
Config("hybrid-k4", "hybrid"),
Config("hybrid-rerank-k4", "hybrid+rerank"),
Config("hybrid-rerank-k4-medium", "hybrid+rerank", effort="medium"),
]
def retrieve(cfg: Config, question: str) -> list[str]:
if cfg.retrieval == "dense":
return [h.text for h in dense.search(question, k=cfg.k)]
candidates = [t for t, _ in hybrid.search(question, k=30 if "rerank" in cfg.retrieval else cfg.k)]
if "rerank" in cfg.retrieval:
scores = reranker.predict([(question, c) for c in candidates])
candidates = [c for c, _ in sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)]
return candidates[:cfg.k]
def generate(cfg: Config, question: str, chunks: list[str]):
sources = "\n\n".join(f'<source id="{i}">\n{c}\n</source>' for i, c in enumerate(chunks, start=1))
return client.messages.create(
model="claude-opus-5-5", max_tokens=1500, output_config={"effort": cfg.effort},
system="Answer using only the sources, citing ids like [1]. If they do not contain the "
"answer, say the documents do not contain this information.",
messages=[{"role": "user", "content": f"<sources>\n{sources}\n</sources>\n\n{question}"}])
def run(cfg: Config) -> None:
out = Path("eval_results") / f"{cfg.name}.jsonl"
out.parent.mkdir(exist_ok=True)
with out.open("w", encoding="utf-8") as f:
for case in golden:
t0 = time.perf_counter()
chunks = retrieve(cfg, case["question"])
t1 = time.perf_counter()
msg = generate(cfg, case["question"], chunks)
t2 = time.perf_counter()
answer = "".join(b.text for b in msg.content if b.type == "text")
evidence = [e.lower() for e in case.get("evidence", [])]
rank = next((r for r, c in enumerate(chunks, start=1) if any(e in c.lower() for e in evidence)), None)
verdict = grade(case["question"], answer, case["reference_answer"]).verdict
f.write(json.dumps({
"config": cfg.name, "id": case["id"], "question": case["question"],
"category": case.get("category", "general"), "type": case.get("type", ""),
"answer": answer, "verdict": verdict,
"correct": verdict in ("correct", "correctly_declined"),
"hit": rank is not None, "rr": 1 / rank if rank else 0.0,
"retrieval_ms": round((t1 - t0) * 1000), "generation_ms": round((t2 - t1) * 1000),
"input_tokens": msg.usage.input_tokens, "output_tokens": msg.usage.output_tokens,
}) + "\n")
print(f"finished {cfg.name}")
if __name__ == "__main__":
for cfg in CONFIGS:
run(cfg)
For unanswerable cases (no evidence), hit is always false; the dashboard reports retrieval metrics on answerable cases only and abstention separately.
The dashboard
"""RAG evaluation dashboard. streamlit run dashboard.py"""
import json
from pathlib import Path
import pandas as pd
import streamlit as st
st.set_page_config(page_title="RAG Evaluation Dashboard", layout="wide")
st.title("RAG Evaluation Dashboard")
rows = [json.loads(line) for p in Path("eval_results").glob("*.jsonl") for line in p.open(encoding="utf-8")]
if not rows:
st.warning("No results yet. Run eval_runner.py first.")
st.stop()
df = pd.DataFrame(rows)
df["answerable"] = df["type"] != "unanswerable"
PRICE_IN, PRICE_OUT = 4.00, 20.00 # USD per million tokens; keep in sync with current pricing
df["cost_usd"] = (df["input_tokens"] * PRICE_IN + df["output_tokens"] * PRICE_OUT) / 1e6
df["total_ms"] = df["retrieval_ms"] + df["generation_ms"]
# ---- Summary ----
ans = df[df["answerable"]]
summary = pd.DataFrame({
"correct %": df.groupby("config")["correct"].mean() * 100,
"hit rate %": ans.groupby("config")["hit"].mean() * 100,
"MRR": ans.groupby("config")["rr"].mean(),
"declines OK %": df[~df["answerable"]].groupby("config")["correct"].mean() * 100,
"p95 latency ms": df.groupby("config")["total_ms"].quantile(0.95),
"cost / 1k questions $": df.groupby("config")["cost_usd"].mean() * 1000,
}).round(2)
st.subheader("Summary")
st.dataframe(summary, use_container_width=True)
col1, col2 = st.columns(2)
col1.subheader("Correctness by configuration")
col1.bar_chart(summary["correct %"])
col2.subheader("Correctness by category")
col2.dataframe((df.pivot_table(index="category", columns="config", values="correct", aggfunc="mean") * 100).round(1))
# ---- Compare two configurations question by question ----
st.subheader("Compare two configurations")
configs = sorted(df["config"].unique())
a = st.selectbox("Baseline", configs, index=0)
b = st.selectbox("Candidate", configs, index=len(configs) - 1)
wide = df.pivot_table(index=["id", "question"], columns="config", values="correct", aggfunc="first").reset_index()
changed = wide[wide[a] != wide[b]]
st.write(f"{(changed[b] > changed[a]).sum()} improved, {(changed[b] < changed[a]).sum()} regressed")
for _, row in changed.iterrows():
label = "improved" if row[b] > row[a] else "REGRESSED"
with st.expander(f"{label}: {row['question']}"):
left, right = st.columns(2)
for column, cfg in ((left, a), (right, b)):
r = df[(df["id"] == row["id"]) & (df["config"] == cfg)].iloc[0]
column.markdown(f"**{cfg}** ({r['verdict']})")
column.write(r["answer"])
Run it
python eval_runner.py
streamlit run dashboard.py
The summary table answers the practical questions at a glance: does reranking improve correctness enough to justify its latency? Does medium effort help, and what does it cost? The comparison view shows exactly which questions changed, which is where the real insight is.
Making it trustworthy
- Validate the judge against human labels before trusting the correctness column (LLM-as-Judge).
- Check significance with the paired bootstrap from A/B and Regression Testing before declaring a winner.
- Record versions: store the git commit, prompt version and index version with each run, so results remain interpretable months later.
- Cost control: evaluation runs make many LLM calls. Cache judge results by (question, answer) and consider the Batch API for large runs.
Where to go from here
You now have every piece of a production RAG practice: ingestion, chunking, embeddings, vector search, hybrid retrieval, reranking, query transformation, grounded generation, advanced architectures, security, and an evaluation loop to improve all of it with evidence. The Decision Cheat Sheet summarises which technique to reach for when.
Key takeaways
- An evaluation runner turns each RAG configuration into a measurable experiment on the golden set.
- Record retrieval, correctness, abstention, latency and cost per question, not just averages.
- A dashboard with per-question comparisons shows what improved and what regressed.
- Validate judges, test significance and record versions so results can be trusted.