feat: add local RAG evaluation harness (RAGAS vs DeepEval)

Add a self-contained eval harness under eval/ that runs the RAG pipeline
over a guideline-grounded eval set and scores the outputs with BOTH RAGAS
and DeepEval using a local judge model (no external API).

Includes eval_set.json, run_pipeline.py, score_ragas.py, score_deepeval.py,
compare.py, a README, and the 3-sample results (answer relevancy: RAGAS
0.969 vs DeepEval 0.889). Supports the #154 task of choosing a RAG eval
tool - both agree closely; DeepEval ran with far less setup friction on
the current stack.

Assisted-by: Claude Opus 4.8
Signed-off-by: gtfrans2re <francoisgonothitoure@gmail.com>
This commit is contained in:
Francois Gonothi Toure 2026-07-07 15:35:47 -04:00 • committed by Justin Wheeler
commit 07f5414890
10 changed files with 668 additions and 1 deletions

5
.gitignore vendored
View file

@ -57,4 +57,7 @@ collection/
# Benchmarking outputs
results/
*.json.bak
*.json.bak
# DeepEval cache/config
.deepeval/
.deepeval-cache/

86
eval/README.md Normal file
View file

@ -0,0 +1,86 @@
# RAG Evaluation Harness (RAGAS vs DeepEval)
This directory contains a small, self-contained harness to evaluate the editorial
assistant's RAG pipeline with **both RAGAS and DeepEval**, using a **local judge
model** (no external API).
The goal is to compare the two tools on the same pipeline outputs and inform
which one we adopt for the mini-project (follow-up to #154).
## Files
- `eval_set.json` - the evaluation set: questions with ground-truth reference answers derived from the Fedora writing guidelines.
- `run_pipeline.py` - runs the RAG pipeline over the eval set, producing `(question, answer, contexts, ground_truth)` in `pipeline_outputs.json`.
- `score_ragas.py` - scores those outputs with RAGAS.
- `score_deepeval.py` - scores those outputs with DeepEval.
- `compare.py` - prints a side-by-side of both tools' scores.
Running the pipeline once and scoring the same outputs with both tools keeps the
comparison fair (the slow, local RAG queries happen only once).
## Prerequisites
```bash
pip install ragas deepeval langchain-openai datasets
```
You also need a **local judge model** served over an OpenAI-compatible endpoint.
Any of these work:
- RamaLama: `ramalama serve <model>` (exposes an OpenAI-compatible API)
- Ollama: `ollama serve` then use the OpenAI-compatible `/v1` route
- llama.cpp server: `llama-server --port 8080 ...`
Point the scorers at it:
```bash
export OPENAI_API_BASE=http://localhost:8080/v1
export OPENAI_API_KEY=sk-local # any non-empty placeholder
```
## Steps
```bash
# 1. Generate pipeline outputs (query the RAG assistant over the eval set)
python eval/run_pipeline.py \
--image quay.io/fedora/editorial-guide-ramalama:commblog \
--model hf://bartowski/google_gemma-4-E4B-it-GGUF
# 2. Score with each tool (local judge)
python eval/score_ragas.py --judge-model <name-your-server-exposes>
python eval/score_deepeval.py --judge-model <name-your-server-exposes>
# 3. Compare
python eval/compare.py
```
## About retrieved contexts
Some metrics (faithfulness, context precision/recall) need the **retrieved
chunks** that the answer was grounded in, not just the final answer.
RamaLama's `run --rag` does not always print the retrieved chunks separately, so
by default `run_pipeline.py` records an empty `contexts` list and the scorers
fall back to reference-free metrics (answer relevancy).
To score the full metric set, capture the retrieved context in
`run_pipeline.py`'s `extract_contexts()` - for example by using a retrieval step
that returns the chunks (a direct Qdrant/doc2rag query), or a RamaLama option
that surfaces the context.
Until then, treat the answer-relevancy comparison as the primary signal and the
context metrics as a next step.
## Interpreting results
- Scores between the two tools are **not identical by construction** - they use
different prompts and judge logic. Read them as *directional*.
- The useful comparison is each tool **against itself** across pipeline changes
(did faithfulness go up after I changed chunk size?), plus a qualitative sense
of which tool's developer experience fits the project.
- Independent 2026 benchmarks caution that a RAG answer can score high on
faithfulness yet still be wrong if the retrieved context itself is stale or
incorrect - so these scores are a strong signal, not ground truth.
## Why this harness exists
This supports the #154 task of choosing a RAG evaluation tool. Rather than
deciding on paper, it lets us run both tools on the same local pipeline and see
their output and ergonomics first-hand before committing.

72
eval/compare.py Normal file
View file

@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""
compare.py
Reads eval/results_ragas.json and eval/results_deepeval.json and prints a
side-by-side comparison, mapping the two tools' metric names onto the shared
RAG concepts so they can be read together.
Usage (from repo root, after running both scorers):
python eval/compare.py
"""
import json
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
RAGAS_FILE = REPO_ROOT / "eval" / "results_ragas.json"
DEEPEVAL_FILE = REPO_ROOT / "eval" / "results_deepeval.json"
# Map both tools' metric names onto shared concepts
CONCEPTS = {
"Answer relevancy": {"ragas": "answer_relevancy", "deepeval": "AnswerRelevancyMetric"},
"Faithfulness": {"ragas": "faithfulness", "deepeval": "FaithfulnessMetric"},
"Context precision":{"ragas": "context_precision","deepeval": "ContextualPrecisionMetric"},
"Context recall": {"ragas": "context_recall", "deepeval": "ContextualRecallMetric"},
}
def load(path):
if not path.exists():
return None
with open(path, encoding="utf-8") as f:
return json.load(f)
def main():
ragas = load(RAGAS_FILE)
deepeval = load(DEEPEVAL_FILE)
if ragas is None and deepeval is None:
sys.exit("No results found. Run score_ragas.py and score_deepeval.py first.")
ragas_scores = ragas["scores"] if ragas else {}
deepeval_scores = deepeval["scores"] if deepeval else {}
print("\n" + "=" * 60)
print(" RAGAS vs DeepEval - side-by-side (local judge)")
print("=" * 60)
print(f"{'Concept':<20}{'RAGAS':>12}{'DeepEval':>14}")
print("-" * 60)
for concept, keys in CONCEPTS.items():
rv = ragas_scores.get(keys["ragas"])
dv = deepeval_scores.get(keys["deepeval"])
rs = f"{rv:.3f}" if isinstance(rv, (int, float)) else "-"
ds = f"{dv:.3f}" if isinstance(dv, (int, float)) else "-"
print(f"{concept:<20}{rs:>12}{ds:>14}")
print("-" * 60)
if ragas:
print(f"RAGAS judge: {ragas.get('judge_model')} ({ragas.get('num_samples')} samples)")
if deepeval:
print(f"DeepEval judge: {deepeval.get('judge_model')} ({deepeval.get('num_samples')} samples)")
print("=" * 60 + "\n")
print("Notes:")
print("- A '-' means that metric was not run (e.g. contexts not captured).")
print("- Scores are not perfectly 1:1 between tools; treat them as directional,")
print(" not identical. Compare each tool against itself across pipeline changes.")
if __name__ == "__main__":
main()

70
eval/eval_set.json Normal file
View file

@ -0,0 +1,70 @@
{
"description": "Evaluation set for the Fedora editorial-guide-ramalama RAG assistant. Each item has a question, a ground-truth reference answer derived from the Fedora Community Blog / Magazine writing guidelines, and the guideline area it tests. Used by both RAGAS and DeepEval to score the RAG pipeline.",
"source_guidelines": [
"https://communityblog.fedoraproject.org/writing-community-blog-article/",
"https://communityblog.fedoraproject.org/editor-guidelines/",
"https://docs.fedoraproject.org/en-US/fedora-magazine/writing-guidelines/"
],
"samples": [
{
"id": "featured_image",
"question": "Does a Fedora Community Blog article need a featured image, and what are the requirements?",
"ground_truth": "Yes. Every Community Blog article should have a featured image. The image must be uploaded to the site (not hotlinked from an external source), and it should be appropriately sized and relevant to the article content.",
"guideline_area": "Featured image"
},
{
"id": "read_more_tag",
"question": "Where should the Read More tag be placed in a Community Blog post?",
"ground_truth": "The Read More tag (the <!--more--> marker) should be placed after the first paragraph, so that only the introduction shows on listing pages and readers click through for the full article.",
"guideline_area": "Read More tag"
},
{
"id": "tone",
"question": "What tone should a Fedora Community Blog article use?",
"ground_truth": "The tone should be enthusiastic but not salesy, welcoming, and collaborative. Writers should avoid a condescending, dogmatic, or overly promotional tone, and write in a way that is accessible to the target audience.",
"guideline_area": "Tone"
},
{
"id": "headers",
"question": "When should headers be used in a Community Blog article?",
"ground_truth": "Headers should be used to break up articles longer than about 400 words, so the content is scannable and well organized. Shorter posts may not need them.",
"guideline_area": "Headers"
},
{
"id": "tags",
"question": "How many tags should a Community Blog article have?",
"ground_truth": "An article should suggest roughly 3 to 6 relevant tags. Tags should be appropriate to the content and help with discoverability without over-tagging.",
"guideline_area": "Tags"
},
{
"id": "category",
"question": "How many categories should be assigned to a Community Blog post?",
"ground_truth": "A single appropriate category should be selected for the post, chosen from the existing categories that best fits the article's topic.",
"guideline_area": "Category"
},
{
"id": "link_text",
"question": "What link text should be avoided in Fedora articles?",
"ground_truth": "Avoid using the word 'here' as link text. Link text should be descriptive of the destination so that the purpose of the link is clear out of context and for accessibility.",
"guideline_area": "Link text"
},
{
"id": "key_info_first",
"question": "Where should the main takeaway of a Community Blog article go?",
"ground_truth": "The most important information or main takeaway should appear in the first paragraph, so readers get the key point immediately, especially since only the intro shows before the Read More tag.",
"guideline_area": "Key info first"
},
{
"id": "hotlinking",
"question": "Is it acceptable to hotlink images in a Community Blog article?",
"ground_truth": "No. Images should be uploaded to the site rather than hotlinked from external sources, because hotlinked images can break and are outside the site's control.",
"guideline_area": "Images / hotlinking"
},
{
"id": "magazine_scope",
"question": "What kind of content is appropriate for Fedora Magazine?",
"ground_truth": "Fedora Magazine publishes articles of general interest to the Fedora user community, such as how-tos, tips, coverage of Fedora features, and free and open source software topics. Content should be relevant to Fedora users and follow the Magazine writing guidelines.",
"guideline_area": "Magazine scope"
}
]
}

View file

@ -0,0 +1,31 @@
{
"image": "quay.io/fedora/editorial-guide-ramalama:commblog",
"model": "hf://ibm-granite/granite-4.0-micro-GGUF",
"num_samples": 3,
"results": [
{
"id": "featured_image",
"question": "Does a Fedora Community Blog article need a featured image, and what are the requirements?",
"answer": "11a31cb9a004e7edad410cdb5e6bfbabb44a1c2a4d4d4cc3991ceb93f0f0cacf\n620e1b548e77b7e131eec8e7eef903782a9608924d4ecf504bc69bf201b1dcfb\n1b916f8c62d69b43af4c47dd539641a1da0815583d4c431633d808b050ae81b3\n\nYes, a Fedora Community Blog article should ideally have a featured image. The featured image, also known as a thumbnail, is an image that represents the topic or theme of your blog post. It is typically displayed on the front page of the blog, and in the feed of your article on other blogs or social media platforms.\n\nHere are some requirements for a featured image:\n\n1. Size: The recommended size for a featured image is 1200 x 628 pixels. This size is optimized for Twitter and Facebook sharing, ensuring that the image doesn't get cropped.\n\n2. Format: The image should be in a lossless format like JPEG or PNG. \n\n3. Content: The image should be relevant to the topic of the blog post. It could be an illustration, an image of the product, or a photo.\n\n4. Resolution: The image should be high quality and clear. A low resolution image may appear blurry when zoomed in.\n\n5. Alt Text: Always include alt text for the image to ensure that it's accessible to users who can't see the image.\n\n6. Description: Along with the image, provide a description or caption that gives context to the image.\n\nRemember to credit any images you use appropriately to respect copyright and intellectual property laws.",
"contexts": [],
"ground_truth": "Yes. Every Community Blog article should have a featured image. The image must be uploaded to the site (not hotlinked from an external source), and it should be appropriately sized and relevant to the article content.",
"guideline_area": "Featured image"
},
{
"id": "read_more_tag",
"question": "Where should the Read More tag be placed in a Community Blog post?",
"answer": "774f75376d65bad876d0a245b622d3c06d3afc2f5e48413b6afd98682b05b7f9\n1c3b6e651c2d8b83b02fc228c36b0211c1b00ea3b683d04eb319ce59ba3c267e\n703d97d4b564d93ab76e12d2300b8439e381058601115ae3cf5f378df393ac00\n\nThe \"Read More\" tag, also known as a \"read more\" link or \"continue reading\" link, should ideally be placed at the end of a Community Blog post, typically at the end of the last sentence or after the last piece of content. This is to ensure the post remains readable and the call to action is clear without disrupting the flow of the content. It's also important to note that this tag is used to differentiate between content that was truncated due to size limitations and the full article. \n\nHowever, it's also important to note that the use of this tag is becoming less common in modern web development. Many modern blogging platforms and content management systems have moved away from the \"Read More\" tag and instead use other methods to manage content display, such as AJAX loading or lazy loading.",
"contexts": [],
"ground_truth": "The Read More tag (the <!--more--> marker) should be placed after the first paragraph, so that only the introduction shows on listing pages and readers click through for the full article.",
"guideline_area": "Read More tag"
},
{
"id": "tone",
"question": "What tone should a Fedora Community Blog article use?",
"answer": "d17b342af142a1ebabecc79dde5f4500560e1439f3e9dfcdbdbe2a7f18c3484f\ndf0456a030f9dbe4b0c4bc5d6a6096b235132a4ea463ac708adb9c2f3c53a03a\n4bf7b3c161fea1fcb1af07f0aab5676eea1ed85685efbec26254dbcd924b4bc7\n\nA Fedora Community Blog article should use a professional, informative, and engaging tone. It should be friendly and welcoming to both new and experienced users of Fedora. The article should be clear, concise, and easy to understand, while also providing in-depth information and insights into the various features and functionalities of Fedora. It should encourage user interaction and feedback, promoting a sense of community and collaboration among its readers.",
"contexts": [],
"ground_truth": "The tone should be enthusiastic but not salesy, welcoming, and collaborative. Writers should avoid a condescending, dogmatic, or overly promotional tone, and write in a way that is accessible to the target audience.",
"guideline_area": "Tone"
}
]
}

View file

@ -0,0 +1,8 @@
{
"tool": "deepeval",
"judge_model": "ibm-granite/granite-4.0-micro-GGUF",
"num_samples": 3,
"scores": {
"AnswerRelevancyMetric": 0.8888888888888888
}
}

8
eval/results_ragas.json Normal file
View file

@ -0,0 +1,8 @@
{
"tool": "ragas",
"judge_model": "ibm-granite/granite-4.0-micro-GGUF",
"num_samples": 3,
"scores": {
"answer_relevancy": 0.96856693486059
}
}

125
eval/run_pipeline.py Normal file
View file

@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""
run_pipeline.py
Runs the RAG editorial assistant over the evaluation set (eval/eval_set.json)
and records, for each question:
- question
- answer (what the RAG pipeline generated)
- contexts (the retrieved chunks the answer was grounded in)
- ground_truth (the reference answer from the guidelines)
The result is written to eval/pipeline_outputs.json, which both the RAGAS and
DeepEval scorers consume. Keeping this step separate means we query the (slow,
local) RAG pipeline only once, then score those same outputs with both tools for
a fair comparison.
Usage (from repo root):
python eval/run_pipeline.py \
--image quay.io/fedora/editorial-guide-ramalama:commblog \
--model hf://bartowski/google_gemma-4-E4B-it-GGUF
Prerequisites:
- ramalama installed and the model pulled
- the RAG image available locally or pullable from Quay
"""
import argparse
import json
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
EVAL_SET = REPO_ROOT / "eval" / "eval_set.json"
OUT_FILE = REPO_ROOT / "eval" / "pipeline_outputs.json"
def run_rag_query(image: str, model: str, question: str) -> str:
"""
Send a single question to the RAG pipeline via `ramalama run --rag`.
The prompt is passed on stdin. Returns the generated answer text.
"""
cmd = ["ramalama", "run", "--rag", image, model]
try:
proc = subprocess.run(
cmd,
input=question,
capture_output=True,
text=True,
timeout=300,
)
except FileNotFoundError:
sys.exit("ERROR: 'ramalama' not found. Install it and try again.")
except subprocess.TimeoutExpired:
return "[ERROR: query timed out]"
if proc.returncode != 0:
return f"[ERROR: ramalama exited {proc.returncode}: {proc.stderr.strip()[:200]}]"
return proc.stdout.strip()
def extract_contexts(answer_blob: str) -> list:
"""
Best-effort extraction of retrieved context.
RamaLama's RAG output does not always expose the retrieved chunks
separately on stdout. If your pipeline is configured to print retrieved
context (e.g. a --show-context flag or a separate retrieval call), wire it
in here. As a safe default we return an empty list, which the scorers
handle by falling back to reference-free metrics where possible.
NOTE: For metrics that require contexts (context precision/recall,
faithfulness), populate this list with the actual retrieved chunks. See
eval/README.md for how to enable context capture in your setup.
"""
return []
def main():
parser = argparse.ArgumentParser(description="Run RAG pipeline over the eval set.")
parser.add_argument("--image", required=True, help="RAG OCI image (e.g. quay.io/fedora/editorial-guide-ramalama:commblog)")
parser.add_argument("--model", required=True, help="RamaLama model string (hf://...)")
parser.add_argument("--limit", type=int, default=0, help="Only run the first N samples (0 = all)")
args = parser.parse_args()
with open(EVAL_SET, encoding="utf-8") as f:
eval_data = json.load(f)
samples = eval_data["samples"]
if args.limit > 0:
samples = samples[: args.limit]
results = []
total = len(samples)
for i, sample in enumerate(samples, 1):
q = sample["question"]
print(f"[{i}/{total}] Querying: {q[:70]}...", flush=True)
answer = run_rag_query(args.image, args.model, q)
results.append(
{
"id": sample["id"],
"question": q,
"answer": answer,
"contexts": extract_contexts(answer),
"ground_truth": sample["ground_truth"],
"guideline_area": sample["guideline_area"],
}
)
payload = {
"image": args.image,
"model": args.model,
"num_samples": len(results),
"results": results,
}
with open(OUT_FILE, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2, ensure_ascii=False)
print(f"\nWrote {len(results)} pipeline outputs to {OUT_FILE}")
print("Next: score with `python eval/score_ragas.py` and `python eval/score_deepeval.py`")
if __name__ == "__main__":
main()

123
eval/score_deepeval.py Normal file
View file

@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""
score_deepeval.py
Scores the RAG pipeline outputs (eval/pipeline_outputs.json) with DeepEval, using
a LOCAL judge model served over an OpenAI-compatible endpoint. No external API.
Metrics (RAG-focused, to mirror the RAGAS run for a fair comparison):
- AnswerRelevancyMetric
- FaithfulnessMetric [needs retrieval_context]
- ContextualPrecisionMetric [needs retrieval_context + expected_output]
- ContextualRecallMetric [needs retrieval_context + expected_output]
If contexts are empty in pipeline_outputs.json, only AnswerRelevancy is run and a
note is printed (mirrors score_ragas.py behavior).
Usage (from repo root), with a local judge model already served:
export OPENAI_API_BASE=http://localhost:8080/v1
export OPENAI_API_KEY=sk-local
python eval/score_deepeval.py --judge-model local-model
Install:
pip install deepeval
"""
import argparse
import json
import os
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
IN_FILE = REPO_ROOT / "eval" / "pipeline_outputs.json"
OUT_FILE = REPO_ROOT / "eval" / "results_deepeval.json"
def main():
parser = argparse.ArgumentParser(description="Score pipeline outputs with DeepEval (local judge).")
parser.add_argument("--judge-model", default="local-model",
help="Model name your local OpenAI-compatible server exposes")
parser.add_argument("--base-url", default=os.environ.get("OPENAI_API_BASE", "http://localhost:8080/v1"))
args = parser.parse_args()
if not IN_FILE.exists():
sys.exit(f"ERROR: {IN_FILE} not found. Run eval/run_pipeline.py first.")
try:
from deepeval import evaluate
from deepeval.test_case import LLMTestCase
from deepeval.metrics import (
AnswerRelevancyMetric,
FaithfulnessMetric,
ContextualPrecisionMetric,
ContextualRecallMetric,
)
from deepeval.models import GPTModel
except ImportError as e:
sys.exit(f"ERROR: missing dependency ({e}). Run: pip install deepeval")
with open(IN_FILE, encoding="utf-8") as f:
payload = json.load(f)
rows = payload["results"]
has_contexts = any(r.get("contexts") for r in rows)
# Point DeepEval's judge at the LOCAL OpenAI-compatible endpoint.
os.environ.setdefault("OPENAI_API_KEY", "sk-local")
os.environ["OPENAI_API_BASE"] = args.base_url
os.environ["OPENAI_BASE_URL"] = args.base_url
judge = GPTModel(model=args.judge_model, base_url=args.base_url)
# Build test cases
test_cases = []
for r in rows:
test_cases.append(
LLMTestCase(
input=r["question"],
actual_output=r["answer"],
expected_output=r["ground_truth"],
retrieval_context=(r.get("contexts") or None),
)
)
if has_contexts:
metrics = [
AnswerRelevancyMetric(model=judge),
FaithfulnessMetric(model=judge),
ContextualPrecisionMetric(model=judge),
ContextualRecallMetric(model=judge),
]
else:
metrics = [AnswerRelevancyMetric(model=judge)]
print("NOTE: no retrieved contexts found in pipeline_outputs.json.")
print(" Only 'AnswerRelevancy' is scored. Enable context capture to")
print(" score Faithfulness / ContextualPrecision / ContextualRecall.\n")
print(f"Scoring {len(rows)} samples with DeepEval using local judge '{args.judge_model}'...")
# Score each metric across all test cases and average
aggregate = {}
for metric in metrics:
name = metric.__class__.__name__
vals = []
for tc in test_cases:
try:
metric.measure(tc)
vals.append(metric.score)
except Exception as e:
print(f" [warn] {name} failed on one case: {str(e)[:120]}")
if vals:
aggregate[name] = sum(vals) / len(vals)
out = {"tool": "deepeval", "judge_model": args.judge_model, "num_samples": len(rows), "scores": aggregate}
with open(OUT_FILE, "w", encoding="utf-8") as f:
json.dump(out, f, indent=2)
print("\nDeepEval scores (averaged across samples):")
for k, v in aggregate.items():
print(f" {k:26s}: {v:.3f}")
print(f"\nWrote {OUT_FILE}")
if __name__ == "__main__":
main()

141
eval/score_ragas.py Normal file
View file

@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""
score_ragas.py
Scores the RAG pipeline outputs (eval/pipeline_outputs.json) with RAGAS, using a
LOCAL judge model served over an OpenAI-compatible endpoint (e.g. RamaLama,
Ollama, or llama.cpp server). No external API is used.
Metrics:
- faithfulness (is the answer grounded in the retrieved context?)
- answer_relevancy (does the answer address the question?)
- context_precision (are the retrieved chunks relevant?) [needs contexts]
- context_recall (was the needed info retrieved?) [needs contexts + ground_truth]
Reference-free metrics (faithfulness, answer_relevancy) still work when contexts
are empty is NOT guaranteed - faithfulness needs contexts. If contexts are empty
in pipeline_outputs.json, only answer_relevancy is reported, and a note is
printed. See eval/README.md for enabling context capture.
Usage (from repo root), with a local judge model already served:
export OPENAI_API_BASE=http://localhost:8080/v1
export OPENAI_API_KEY=sk-local # any non-empty string
python eval/score_ragas.py --judge-model gemma
Install:
pip install ragas langchain-openai datasets
"""
import argparse
import json
import os
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
IN_FILE = REPO_ROOT / "eval" / "pipeline_outputs.json"
OUT_FILE = REPO_ROOT / "eval" / "results_ragas.json"
def main():
parser = argparse.ArgumentParser(description="Score pipeline outputs with RAGAS (local judge).")
parser.add_argument("--judge-model", default="local-model",
help="Model name your local OpenAI-compatible server exposes")
parser.add_argument("--base-url", default=os.environ.get("OPENAI_API_BASE", "http://localhost:8080/v1"),
help="OpenAI-compatible base URL of the local judge server")
parser.add_argument("--embed-model", default="sentence-transformers/all-MiniLM-L6-v2",
help="Local sentence-transformers model for embeddings (runs in-process)")
args = parser.parse_args()
if not IN_FILE.exists():
sys.exit(f"ERROR: {IN_FILE} not found. Run eval/run_pipeline.py first.")
try:
from datasets import Dataset
from ragas import evaluate
from ragas.metrics import faithfulness, answer_relevancy, context_precision, context_recall
from langchain_openai import ChatOpenAI
except ImportError as e:
sys.exit(f"ERROR: missing dependency ({e}). Run: pip install ragas langchain-openai datasets")
with open(IN_FILE, encoding="utf-8") as f:
payload = json.load(f)
rows = payload["results"]
has_contexts = any(r.get("contexts") for r in rows)
# Build the dataset in the schema RAGAS expects
data = {
"question": [r["question"] for r in rows],
"answer": [r["answer"] for r in rows],
"contexts": [r.get("contexts") or [""] for r in rows],
"ground_truth": [r["ground_truth"] for r in rows],
}
dataset = Dataset.from_dict(data)
# Point RAGAS's JUDGE LLM at the local OpenAI-compatible endpoint (Granite).
os.environ.setdefault("OPENAI_API_KEY", "sk-local")
judge_llm = ChatOpenAI(model=args.judge_model, base_url=args.base_url, temperature=0)
# Embeddings: the local chat server (ramalama serve) does NOT provide an
# embeddings endpoint, so reusing it returns HTTP 501. Instead, run a small
# embedding model locally in-process via sentence-transformers. This keeps
# everything offline and avoids needing a second server.
try:
from langchain_huggingface import HuggingFaceEmbeddings
except ImportError:
try:
from langchain_community.embeddings import HuggingFaceEmbeddings
except ImportError:
sys.exit("ERROR: need local embeddings. Run: pip install langchain-huggingface sentence-transformers")
judge_emb = HuggingFaceEmbeddings(model_name=args.embed_model)
# Choose metrics based on whether we captured retrieved contexts
if has_contexts:
metrics = [faithfulness, answer_relevancy, context_precision, context_recall]
else:
metrics = [answer_relevancy]
print("NOTE: no retrieved contexts found in pipeline_outputs.json.")
print(" Only 'answer_relevancy' is scored. Enable context capture to")
print(" score faithfulness / context_precision / context_recall.\n")
print(f"Scoring {len(rows)} samples with RAGAS using local judge '{args.judge_model}'...")
result = evaluate(dataset, metrics=metrics, llm=judge_llm, embeddings=judge_emb)
# Extract scores robustly across RAGAS versions. The most reliable path is
# to_pandas(): one row per sample, one column per metric. We average each
# metric column (ignoring NaN failures) to get an aggregate score.
scores = {}
try:
df = result.to_pandas()
metric_names = [m.name if hasattr(m, "name") else str(m) for m in metrics]
for col in df.columns:
if col in metric_names or col in ("answer_relevancy", "faithfulness",
"context_precision", "context_recall"):
series = df[col].dropna()
if len(series):
scores[col] = float(series.mean())
except Exception as e:
# Fallback: try dict-style access
try:
scores = {k: float(v) for k, v in dict(result).items()}
except Exception:
print(f"WARNING: could not parse RAGAS result ({e}).")
if not scores:
print("\nWARNING: RAGAS produced no numeric scores (all samples may have")
print("failed judging). Nothing written. Check the judge server and retry.")
sys.exit(1)
out = {"tool": "ragas", "judge_model": args.judge_model, "num_samples": len(rows), "scores": scores}
with open(OUT_FILE, "w", encoding="utf-8") as f:
json.dump(out, f, indent=2)
print("\nRAGAS scores:")
for k, v in scores.items():
print(f" {k:20s}: {v:.3f}")
print(f"\nWrote {OUT_FILE}")
if __name__ == "__main__":
main()