LLM Evaluation: RAGAS, DeepEval and Custom Metrics
Language model applications fail in ways ordinary tests do not catch. The JSON still parses, the endpoint still returns two hundred, and the answer is subtly wrong, uncited, or phrased so confidently that nobody questions it. Evaluation is the practice of turning those judgments into numbers you can track â a dataset of real cases, metrics that mean something for your task, and a gate that refuses changes which make things worse. Frameworks such as RAGAS and DeepEval supply metric implementations and harnesses, but the hard parts are yours: deciding what correct means, assembling representative cases, and calibrating any automatic judge against humans before trusting it.
The Evaluation Stack
Four layers are involved, and confusing them is the usual source of pointless dashboards. Datasets hold cases with expectations. Metrics turn a run into scores. Harnesses execute the suite across versions. Governance decides what happens when scores move â who is notified, what blocks a release, and which numbers go in a report.
| Layer | Examples | Owned by | Failure mode |
|---|---|---|---|
| Dataset | Labeled Q and A, adversarial cases, production samples | Domain experts plus engineers | Stale, unrepresentative, leaking answers |
| Metric | Exact match, faithfulness, answer relevance, latency | Engineers | Optimized proxies that drift from the task |
| Harness | RAGAS, DeepEval, pytest plugins, custom runners | Engineers | Runs but nobody reads the output |
| Governance | Release gates, dashboards, regression policy | Team lead or owner | Gates too weak to stop a bad release |
Start from governance and work down. If you cannot name the decision a score will change, do not build the metric; you are generating numbers, not evidence.
Datasets Are the Product
A useful dataset is small, layered and alive. Thirty to fifty carefully chosen cases outperform a scraped benchmark of ten thousand mismatched questions, because every case is one you inspected. Layer it: core cases that must always pass, edge cases covering known failure modes, adversarial cases with ambiguity or missing context, and a rotating sample of production traffic with outcomes attached.
import json
import random
from dataclasses import dataclass, field
@dataclass
class EvalCase:
case_id: str
question: str
context: list = field(default_factory=list)
expected: str = ""
must_cite: list = field(default_factory=list)
forbidden: list = field(default_factory=list)
layer: str = "core"
def validate(self) -> list[str]:
problems = []
if not self.question.strip():
problems.append("empty question")
if self.layer == "core" and not self.expected:
problems.append("core case without expected answer")
if self.must_cite and not self.context:
problems.append("citation expectation without context")
return problems
def sample_rotation(production: list[dict], n: int = 15, seed: int = 7) -> list[EvalCase]:
random.seed(seed)
picked = random.sample(production, min(n, len(production)))
return [
EvalCase(
case_id=f"prod-{row['id']}",
question=row["question"],
context=row.get("passages", []),
expected=row.get("approved_answer", ""),
layer="production",
)
for row in picked
]
def load_suite(path: str) -> list[EvalCase]:
with open(path, encoding="utf-8") as fh:
raw = json.load(fh)
cases = [EvalCase(**row) for row in raw]
broken = [(c.case_id, p) for c in cases for p in c.validate()]
if broken:
raise ValueError(f"invalid cases: {broken}")
return cases
suite = load_suite("evals/support.json")
print(len(suite), "cases,", sum(1 for c in suite if c.layer == "core"), "core")
Validate cases on load. Datasets rot quietly â an expected answer that no longer matches policy will fail a correct change and train everyone to ignore the suite. Assign each case an owner and a review date the way you would for any other test fixture, and delete cases that no longer describe a question users ask. A shrinking, well-curated suite stays credible; a growing pile of legacy expectations becomes noise that everyone learns to skip past on the way to the metrics they actually trust.
Reference, Reference-Free and RAG Metrics
Reference metrics compare against a known answer and are the most trustworthy when you have one: exact match for short factual replies, token-level overlap for summaries, schema validation for structured output. They are brittle for open-ended text, where many phrasings are equally correct.
Reference-free metrics fill that gap. Answer relevance asks whether the response addresses the question; faithfulness or groundedness asks whether each claim is supported by the retrieved context; context precision and recall score whether retrieval supplied the right material at the right rank. RAGAS popularized this decomposition, and it is genuinely useful because it localizes failure: a faithful answer built on bad retrieval is a retrieval bug, while a well-retrieved context with an unfaithful answer is a generation bug.
Human scoring remains the anchor. Have two people score the same sample and measure their agreement; if humans cannot agree, no automated metric will be more consistent than the ground truth it imitates. Agreement also calibrates your judge thresholds rather than leaving them at a library default.
Making a Judge You Can Trust
LLM-as-judge is cheap, scalable and biased in predictable directions: it favors longer answers, prefers responses it generated itself, mirrors the wording of the prompt it was given, and grades generously when asked for a single holistic number. Each of those is manageable when you build calibration into the process rather than hoping the model is impartial.
Give the judge a rubric with anchored examples per score level, ask it to quote evidence from the candidate before scoring, and force a structured verdict. Then measure agreement against a human-scored sample and keep only the dimensions where agreement clears your bar â often correctness and instruction-following pass while style and nuance do not.
import json
import openai
client = openai.OpenAI()
RUBRIC = """Score the answer on two dimensions, each 1-5.
1 correctness: is every claim supported by the context or the reference?
2 completeness: does it cover the required points in the reference?
Quote evidence for each score. If the quote is not present in the inputs,
score 1 and set low_confidence true."""
def judge(question: str, context: str, answer: str, reference: str = "") -> dict:
r = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": RUBRIC},
{"role": "user", "content": json.dumps({
"question": question, "context": context,
"answer": answer, "reference": reference,
})},
],
)
return json.loads(r.choices[0].message.content)
def agreement(judged: list[dict], human: list[dict], key: str) -> float:
pairs = [(j.get(key), h.get(key)) for j, h in zip(judged, human) if j.get(key) and h.get(key)]
if not pairs:
return 0.0
within_one = sum(1 for a, b in pairs if abs(a - b) <= 1)
exact = sum(1 for a, b in pairs if a == b)
return {"exact": exact / len(pairs), "within_one": within_one / len(pairs)}
scores = [judge(c["question"], c["context"], c["answer"], c["reference"]) for c in sample]
print(agreement(scores, human_labels, "correctness"))
Rotate judge prompts and models periodically, because judges drift when their underlying model updates â the same problem you manage everywhere else, arriving on a different schedule. Where stakes are high, use the judge to triage: automatic acceptance for the clear cases, human review for the borderline ones, which captures most of the cost saving without pretending the judge is final.
Evaluation in CI and in Production
Continuous evaluation has two loops. The pre-merge loop runs the core suite on every prompt or code change and fails the build on regression beyond a tolerance; keep it fast and deterministic by freezing retrieval results or using recorded fixtures, so a corpus change never masks a prompt regression. The production loop samples real traffic, scores it with the cheap automatic metrics, and feeds outliers back into the dataset.
import sys
GATES = {
"faithfulness": 0.85,
"answer_relevance": 0.80,
"schema_valid": 1.00,
"latency_p95_ms": 4000,
}
def evaluate_run(report: dict, gates: dict = GATES) -> int:
breaches = []
for metric, floor in gates.items():
value = report.get(metric)
if value is None:
breaches.append(f"{metric}: missing")
elif metric.startswith("latency"):
if value > floor:
breaches.append(f"{metric}: {value} > {floor}")
elif value < floor:
breaches.append(f"{metric}: {value} < {floor}")
for breach in breaches:
print("GATE FAIL", breach)
return 1 if breaches else 0
status = evaluate_run(previous_report)
sys.exit(status)
Two rules keep the loops honest. Failures must be triaged, not just emailed â a gate that everyone overrides within a week is a gate that no longer exists. And the dataset grows whenever production reveals a case the suite lacked, which is the mechanism that prevents evaluation from calcifying around the shapes you already understood.
Reading Scores Without Fooling Yourself
Single numbers hide more than they reveal, so report distributions and slices. Averages move less than individual cases: an unchanged average with two new catastrophic failures is a regression, and a modest average gain driven by easy cases is not a win. Slice by question type, document source and difficulty tier, and watch each separately.
Comparisons need the same care. Different judge versions produce different absolute scores, so compare only within a judge version and re-baseline when it changes. Sample sizes matter: with forty cases, differences of a few points are noise, which is why effect sizes and confidence from repeated runs beat one decimal place of precision. And beware of overfitting your suite â a prompt tuned against the same fifty cases will eventually ace them while getting no better in the wild. Hold out a shadow set that is never used for tuning, and check it monthly.
Common Mistakes
Optimizing a proxy metric nobody ties to user outcomes
Fix: Name the decision each score changes before building it
Trusting a judge without measuring human agreement
Fix: Calibrate on a double-scored sample and drop dimensions that do not agree
Freezing the dataset after the first release
Fix: Add production outliers on a cadence so the suite tracks reality
Comparing scores across judge model versions
Fix: Re-baseline whenever the judge changes and compare only within a version
Tuning prompts against the evaluation set directly
Fix: Keep a shadow set reserved for periodic untouched checks
Key Takeaways
- Evaluation is datasets, metrics, harness and governance â not just a metric library
- Small curated layers beat large mismatched benchmarks for product decisions
- Faithfulness versus relevance separates retrieval bugs from generation bugs
- LLM judges need anchored rubrics, quoted evidence and measured human agreement
- Gates must be enforced and datasets must grow, or evaluation quietly stops meaning anything