RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
RAGAS faithfulness catches an invented promise (E02 scores 0.00) but gives a perfect 1.00 to an answer with the wrong citation and to one missing the key fact. Three plain-Python checks catch both, a CitationAccuracy class puts them in the same RAGAS report, and the gate prints BLOCKED: E02 E03 E04 with exit code 1.
What you will learn
- Run RAGAS faithfulness on a small RAG eval set with a swappable judge model
- See which wrong answers a framework metric lets through
- Write custom checks for citations, required facts and forbidden phrases in plain Python
- Wrap a custom check as a RAGAS metric and gate a release on one report
Before you start
- RAG Generation Metrics: Faithfulness, Groundedness and Relevance
- LLM-as-Judge
RAGAS is a popular framework for scoring RAG answers. It's fast to set up, and nobody on your team had to write its metrics. But it doesn't know your product's rules. In this article we run a RAGAS metric, see exactly what it misses, write the missing checks in plain Python, and gate a release on all of them together.
The project runs without a key: a stand-in judge answers the questions RAGAS asks with plain rules. Put your key in .env and the same code calls a real judge model.
The inspector and the house rules
A restaurant gets checked two ways. First, the health inspector, with a standard checklist that fits every kitchen: clean surfaces, safe temperatures. Second, the house rules that only this restaurant has: every dish carries its allergen label, and the soup is never sold after four. The inspector will never check those, because they don't know about them.
A framework like RAGAS is the inspector. Your product's own rules are custom evals. In practice you need both.
Four Cartly answers
Cartly is an online shop. Each row in data/eval_set.json has a question, the passages retrieval found, the bot's answer with citations, a reference answer, and two lists for our own checks:
{"id": "E03",
"user_input": "Can I change the delivery address after my order ships?",
"retrieved_contexts": ["[1] Once an order has shipped, the address can only be changed by the carrier.",
"[2] Before shipping, you can edit the address on the order page."],
"response": "Once an order has shipped, only the carrier can change the address. [2]",
"reference": "After shipping, only the carrier can change the address.",
"must_include": ["carrier"], "must_not_include": ["address has been updated"]}
| Row | Answer | What's wrong |
|---|---|---|
| E01 | Refund within 5 business days. [1] | Nothing |
| E02 | Refund within 24 hours. [1] You also get a 10% voucher. [2] | Invented: neither is in the passages |
| E03 | Only the carrier can change the address. [2] | True, but cites the wrong passage |
| E04 | You can combine one card with one gift card. [1] | True, but leaves out "split payments are not supported" |
Three wrong answers, wrong in three different ways.
One place for the judge
RAGAS needs a judge model, so judge.py is the one place that picks it. The versions are pinned together in requirements.txt, ragas 0.2.15 with the 0.3 line of LangChain, because those two have to match.
"""One place that picks the judge model RAGAS uses."""
import os
from ragas.llms import LangchainLLMWrapper
def get_judge():
if os.getenv("OPENAI_API_KEY"): # a real judge with your key
from langchain_openai import ChatOpenAI
return LangchainLLMWrapper(ChatOpenAI(model=os.getenv("JUDGE_MODEL", "gpt-4o-mini"), temperature=0))
from stand_in import StandInJudge # no key: the stand-in judge
return LangchainLLMWrapper(StandInJudge())
Either way, the judge is wrapped in LangchainLLMWrapper, so RAGAS sees exactly the same thing.
What RAGAS asks the judge
For faithfulness, RAGAS asks the judge two things. First, split the answer into separate statements (the stand-in also removes the citation numbers). Second, give a verdict for each statement: is it supported by the context? The stand-in says yes when 70% of the statement's words appear in the context. A real judge reads it properly, but the question is the same. It's a test model with the same prompts in and the same reply shape out, not a real judge.
First attempt: RAGAS alone
"""RAGAS faithfulness on the Cartly eval set."""
import json
from pathlib import Path
from ragas import EvaluationDataset, evaluate
from ragas.metrics import Faithfulness
from judge import get_judge
ROWS = json.loads(Path(__file__).with_name("data").joinpath("eval_set.json").read_text("utf-8"))
FIELDS = ("user_input", "retrieved_contexts", "response", "reference")
if __name__ == "__main__":
dataset = EvaluationDataset.from_list([{k: r[k] for k in FIELDS} for r in ROWS])
result = evaluate(dataset, metrics=[Faithfulness()], llm=get_judge(), show_progress=False)
scores = result.to_pandas()["faithfulness"]
print("id faithfulness")
for row, score in zip(ROWS, scores):
print(f"{row['id']:<6}{score:>12.2f}")
python 01_ragas_eval.py
id faithfulness
E01 1.00
E02 0.00
E03 1.00
E04 1.00
E02 scores 0.00, so the invented promise is caught. Good. But E03 and E04 both get a perfect 1.00. The wrong citation passes, and the missing fact passes. Faithfulness asks one question: is this statement in the context somewhere? It doesn't care which passage you cited, and it doesn't know what a good answer must contain. (The difference between "somewhere" and "where you said" is explained in RAG Generation Metrics.)
Checks RAGAS does not have
"""Checks RAGAS does not have: citations and the facts a Cartly answer must contain."""
import re
STOP = {"the", "a", "an", "and", "of", "to", "your", "you", "our",
"is", "are", "can", "be", "by", "with", "only", "once", "has"}
def words(text):
found = re.findall(r"[a-z0-9%]+", text.lower())
return {w.rstrip("s") for w in found if w not in STOP}
def passages(contexts):
"""{"1": "Refunds go back ...", ...} from contexts that start with [n]"""
return dict(re.match(r"\[(\d+)\]\s*(.*)", c).groups() for c in contexts)
def citation_accuracy(response, contexts, need=0.7):
"""share of claims whose CITED passage holds most of their words"""
claims = re.findall(r"(.+?)\[(\d+)\]", response)
by_id = passages(contexts)
ok = [len(words(c) & words(by_id.get(n, ""))) / len(words(c)) >= need
for c, n in claims]
return sum(ok) / len(ok) if ok else 0.0
def must_include(response, facts):
"""1.0 when every required fact is in the answer"""
return float(all(f.lower() in response.lower() for f in facts))
def must_not_include(response, phrases):
"""1.0 when no forbidden phrase is in the answer"""
return float(not any(p.lower() in response.lower() for p in phrases))
passagesturns contexts that start with[n]into a lookup:"1","2"and so on.citation_accuracyfinds every claim with the number it cites, looks up only that passage, and checks it holds at least 70% of the claim's words.must_includereturns 1 when every required fact is in the answer.must_not_includereturns 1 when none of the phrases we never want to see shows up.
python 02_custom_evals.py
id citations must_include must_not
E01 1.00 1.00 1.00
E02 0.00 0.00 0.00
E03 0.00 1.00 1.00
E04 1.00 0.00 1.00
E01 passes everything and E02 fails all three. E03's citations score is 0.00, because the claim lives in passage 1 but the answer cites passage 2. E04's must-include is 0.00, because "not supported" is missing. Both answers that slipped past RAGAS are caught now, and there's no judge model here, just Python, so it runs in a moment and costs nothing.
Our check as a RAGAS metric
It's nicer to see everything in one report, so ragas_custom.py wraps the citation check as a RAGAS metric:
"""Our citation check, wrapped as a RAGAS metric so it runs inside evaluate()."""
from dataclasses import dataclass, field
from ragas.metrics.base import MetricType, SingleTurnMetric
from custom_evals import citation_accuracy
@dataclass
class CitationAccuracy(SingleTurnMetric):
name: str = "citation_accuracy"
_required_columns: dict = field(default_factory=lambda: {
MetricType.SINGLE_TURN: {"response", "retrieved_contexts"}})
def init(self, run_config):
pass # no model, nothing to set up
async def _single_turn_ascore(self, sample, callbacks):
return citation_accuracy(sample.response, sample.retrieved_contexts)
It's a single-turn metric that tells RAGAS which columns it needs, the response and the retrieved contexts. init does nothing, because there's no model to set up, and the score is simply our own citation_accuracy. Nothing new to trust.
One report, one gate
"""RAGAS + our metrics in one report, then a ship / block gate."""
import json
import sys
from pathlib import Path
from ragas import EvaluationDataset, evaluate
from ragas.metrics import Faithfulness
from custom_evals import must_include, must_not_include
from judge import get_judge
from ragas_custom import CitationAccuracy
ROWS = json.loads(Path(__file__).with_name("data").joinpath("eval_set.json").read_text("utf-8"))
FIELDS = ("user_input", "retrieved_contexts", "response", "reference")
NEED = {"faithfulness": 1.0, "citation_accuracy": 1.0, "must_include": 1.0, "must_not": 1.0}
if __name__ == "__main__":
dataset = EvaluationDataset.from_list([{k: r[k] for k in FIELDS} for r in ROWS])
table = evaluate(dataset, metrics=[Faithfulness(), CitationAccuracy()],
llm=get_judge(), show_progress=False).to_pandas()
table["must_include"] = [must_include(r["response"], r["must_include"]) for r in ROWS]
table["must_not"] = [must_not_include(r["response"], r["must_not_include"]) for r in ROWS]
table.insert(0, "id", [r["id"] for r in ROWS])
print(table[["id", *NEED]].to_string(index=False, float_format="%.2f"))
failed = [r["id"] for _, r in table.iterrows() if any(r[m] < v for m, v in NEED.items())]
print("BLOCKED:" if failed else "SHIP", *failed)
sys.exit(1 if failed else 0)
NEED sets the thresholds: every metric has to reach 1.0. One evaluate call runs Faithfulness and our CitationAccuracy side by side, the two phrase checks are added as extra columns, and the script exits with code 1 when anything failed, so a CI pipeline stops right there.
python 03_eval_gate.py
id faithfulness citation_accuracy must_include must_not
E01 1.00 1.00 1.00 1.00
E02 0.00 0.00 0.00 0.00
E03 1.00 0.00 1.00 1.00
E04 1.00 1.00 0.00 1.00
BLOCKED: E02 E03 E04
Exit code 1. To wire this into a pipeline, see Regression Testing an LLM Bot in CI.
Fix one, watch the number move
Prove the check means something. In a copy of the eval set, E03 cites passage 1 instead of 2, and we run the gate again. Its citation accuracy goes to 1.00, and the last line now says BLOCKED: E02 E04. E03 is off the list.
You can also score a single answer with python demo.py ask. The same true sentence about the refund, citing [2], gets faithfulness 1.00 but citation accuracy 0.00. Cite [1], and both are 1.00. And python -m pytest -q prints 4 passed, so the checks themselves are tested too.
Common mistakes
- Treating a framework score as "the eval". RAGAS faithfulness gave 1.00 to two wrong answers here.
- Unpinned versions. RAGAS and LangChain move fast and must match; pin them together, as ragas 0.2.15 with LangChain 0.3.
- Two reports, two decisions. Put framework and custom metrics in one table, and let one gate say ship or blocked.
- A gate that only prints. Exit with code 1 on failure, or CI will happily continue.
- Untested checks. Your custom evals are code; give them tests, like the four here.
Quick recap
| Check | Where it comes from | Catches here |
|---|---|---|
| Faithfulness | RAGAS, with a judge model | E02 (invented) |
| Citation accuracy | Custom, wrapped as a RAGAS metric | E02, E03 (wrong passage) |
| Must include | Custom, plain Python | E02, E04 (missing fact) |
| Must not include | Custom, plain Python | E02 ("24 hours") |
| Gate | 03_eval_gate.py | BLOCKED: E02 E03 E04, exit code 1 |
Try it yourself
Run python demo.py all without a key. Then add an E05 with a promise you never make, and watch the gate. Finally, put your key in .env and run the same gate with a real judge.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
From ML Metrics to LLM Evals: Same Ruler, New Targets
Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.
Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.