Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Evals and Testing

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.

Chaand Sheikh

·27 November 2026Evals and Testing

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"]}
RowAnswerWhat's wrong
E01Refund within 5 business days. [1]Nothing
E02Refund within 24 hours. [1] You also get a 10% voucher. [2]Invented: neither is in the passages
E03Only the carrier can change the address. [2]True, but cites the wrong passage
E04You 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))
  • passages turns contexts that start with [n] into a lookup: "1", "2" and so on.
  • citation_accuracy finds 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_include returns 1 when every required fact is in the answer.
  • must_not_include returns 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.

Which metric catches which answer faithfulnesscitationmust_includemust_not (RAGAS)(custom)(custom)(custom) E01E02E03E04 1.001.001.001.00 0.000.000.000.00 1.000.001.001.00 1.001.000.001.00 wrong cite missing fact
The gate's report as a grid. Faithfulness alone passes E03 and E04; the custom columns catch them.

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

CheckWhere it comes fromCatches here
FaithfulnessRAGAS, with a judge modelE02 (invented)
Citation accuracyCustom, wrapped as a RAGAS metricE02, E03 (wrong passage)
Must includeCustom, plain PythonE02, E04 (missing fact)
Must not includeCustom, plain PythonE02 ("24 hours")
Gate03_eval_gate.pyBLOCKED: 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 50 of 66

Previous
LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
Next post
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed

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.

On this page

  • The inspector and the house rules
  • Four Cartly answers
  • One place for the judge
  • What RAGAS asks the judge
  • First attempt: RAGAS alone
  • Checks RAGAS does not have
  • Our check as a RAGAS metric
  • One report, one gate
  • Fix one, watch the number move
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.