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
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • 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
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release 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
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Evals and Testing

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.

Chaand Sheikh

·27 November 2026Evals and Testing

What you will learn

  • Explain precision and recall with one picture: the net and the lake
  • Carry precision and recall over to retrieval as precision@k and recall@k
  • See why exact match breaks on generated text and a key-fact check still works
  • Break a good answer into a rubric of yes-or-no checks with a pass rate

Before you start

  • Precision, Recall and F1 Score
  • Basic Python

What happens to precision and recall when you start building with LLMs? The short answer: they don't disappear. They move. The same ruler gets pointed at new things: first a spam label, then a list of retrieved documents, then a written answer.

We'll take those three in turn with three small scripts, then see the rubric that replaces a single label. No API key is needed.

A fishing net

Here's a lake. It has fish in it, and also a few old boots. You throw a net and pull it out. In the net there are three fish and one boot.

Precision asks about the net, recall asks about the lake lake net fishfishfish fishfishfishfishfish bootbootboot Precision: the net fish in the net / all in the net 3 of 4 Recall: the lake fish caught / all fish 3 of 8
Precision asks about the net: of everything in it, how much is fish? Recall asks about the lake: of all the fish, how many did we catch?
  • Precision asks about the net: of everything in the net, how much is fish? Three out of four.
  • Recall asks about the lake: of all the fish in the lake, how many did we catch? Only three of eight.

Keep this net in mind. It comes back twice.

The classic ruler: one label per row

Here's the classic version, with a spam filter and ten emails. truth says which emails are really spam; a person decided that, one label per email. flagged is what the filter said.

"""Precision and recall on a spam filter: 10 emails, labels by hand."""
from sklearn.metrics import precision_score, recall_score

truth = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]       # 1 = really spam
flagged = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0]     # 1 = filter said spam

# of the emails we flagged, how many were spam?
print("precision:", precision_score(truth, flagged))
# of the spam that exists, how much did we flag?
print("recall:   ", recall_score(truth, flagged))
precision: 0.75
recall:    0.75

The filter got three spam emails right, missed one and raised one false alarm. Of the four it flagged, three were spam: precision 0.75. Of the four spam emails that exist, it flagged three: recall 0.75. One label per row, two clear questions. (The four boxes behind these numbers, and F1, are in Precision, Recall and F1 Score.)

Retrieval is a net too

Now an LLM app. Before a model answers a help-desk question, a retriever looks up a few documents to hand it. The question is "I can't log in to my account". A person has marked which documents are really relevant: the password reset and the two-factor codes. The retriever picks its top three. That's the net.

"""Same ruler, new target: precision@k and recall@k for retrieval."""
import numpy as np
from sentence_transformers import SentenceTransformer

docs = [
    "Reset your password from Settings > Security.",       # 0
    "Refunds reach your card in 5 to 7 working days.",     # 1
    "Change the delivery address before the order ships.", # 2
    "Two-factor codes expire after 30 seconds.",           # 3
    "Cancelled orders are refunded to the original card.", # 4
    "Upload photos as JPG or PNG, up to 10 MB.",           # 5
]
tests = {  # question -> the docs a person marked as relevant
    "I can't log in to my account": {0, 3},
    "When do I get my money back?": {1, 4},
}
K = 3
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_vecs = model.encode(docs, normalize_embeddings=True)

for question, relevant in tests.items():
    q = model.encode(question, normalize_embeddings=True)
    top_k = set(np.argsort(-(doc_vecs @ q))[:K].tolist())
    hits = top_k & relevant
    print(question, "-> retrieved", sorted(top_k))
    print(f"  precision@{K}: {len(hits) / K:.2f}"
          f"   recall@{K}: {len(hits) / len(relevant):.2f}")
I can't log in to my account -> retrieved [0, 1, 3]
  precision@3: 0.67   recall@3: 1.00
When do I get my money back? -> retrieved [1, 3, 4]
  precision@3: 0.67   recall@3: 1.00

Here's where the labels moved. Instead of one label per email, each test question gets the set of documents a person marked as relevant. Each question is embedded with a small sentence model (all-MiniLM-L6-v2, about 90 MB, downloaded once), and the three documents with the highest similarity form the net. hits is what's in the net and also relevant.

precision@3 and recall@3 for the login question "I can't log in to my account" net: top 3 doc 0 Reset your password doc 1 Refunds reach your card doc 3 Two-factor codes expire doc 2 Change the delivery address doc 4, doc 5 refunds, photo upload relevant relevant precision@3 = 2 / 3 0.67 recall@3 = 2 / 2 1.00
The ruler didn't change. Only the thing inside the net did: three retrieved documents instead of flagged emails.

For the login question, documents 0, 1 and 3 came back. Two of the three are relevant: precision@3 is 0.67. Both relevant documents were caught: recall@3 is 1.00. The money question gets the same numbers.

Notice something: with only two relevant documents, three retrieved can never all be relevant, so precision@3 tops out at two thirds here. Choosing k is part of the ruler. For ranking-aware retrieval metrics like MRR and nDCG on a bigger test set, see Retrieval Evals: Recall@K, MRR and nDCG.

Many right answers

Now the generated answer itself, and this is where things really change. We have a reference answer and two answers written for this lesson. Answer A says the same thing in other words. Answer B is simply wrong.

"""Generation: many right answers. Exact match breaks, a check still works."""
reference = "Refunds reach your card in 5 to 7 working days."
answers = {  # two answers written for this lesson
    "A": "You will see the money on your card in 5-7 working days.",
    "B": "Refunds are instant and show up right away.",
}


def exact_match(answer):
    return answer == reference


def has_key_fact(answer):          # one rubric item, written as code
    return "5" in answer and "7" in answer


for name, text in answers.items():
    print(name, "exact match:", exact_match(text),
          "| key fact:", has_key_fact(text))
A exact match: False | key fact: True
B exact match: False | key fact: False

Exact match is the old one-label idea: is the answer identical to the reference? The key-fact check asks something smaller: does the answer contain the 5 and the 7?

Exact match fails both answers, the good one and the bad one. The check tells them apart. With text there are many right answers, so one label is no longer enough.

Same ruler, new things to measure

Classic MLRetrievalGeneration
What gets judgedone predictionthe top k documentsa whole written answer
What counts as rightone labela set of relevant documentsmany good answers
Who labelsa person, per rowa person, per questiona rubric, per answer
The rulerprecision, recallprecision@k, recall@kchecks plus a judge

The questions stay the same. What changes is what counts as right.

The label becomes a rubric

So what replaces the single label for generation? A rubric: "a good answer" broken into small yes-or-no checks.

A rubric of yes-or-no checks feeding a pass rate answer has the key fact?code only uses the given documents?judge model answers the question asked?judge model polite, right length?code or judge pass rate over many questions
Each check is a yes or no. Some are a few lines of code; the ones code can't judge go to a judge model.
  • Does it have the key fact? A few lines of code can check that, like has_key_fact above.
  • Does it only use the documents it was given? And does it answer the question that was asked? Those are hard for code, so a judge model reads the answer and decides. (Writing and validating that judge is covered in LLM-as-Judge.)
  • Is it polite and the right length? Code or a judge.

Every check is a yes or no, so you report a pass rate over many test questions. And because each check is a yes or no, precision and recall still apply: to the checks, and even to the judge model itself. How those checks, cases and a threshold fit together into a real eval is in Why You Cannot Ship an LLM Feature Without an Eval.

Common mistakes

  • Scoring generated text with exact match. It fails correct paraphrases, so it can't tell a good answer from a bad one.
  • Reading precision@k without looking at k. With two relevant documents and k = 3, the best possible precision@3 is 0.67.
  • Forgetting who labels. Retrieval metrics need a person to mark the relevant documents for every test question.
  • Trusting a judge model blindly. Its yes-or-no decisions need their own precision and recall.

Quick recap

TargetRulerResult here
A spam labelprecision_score, recall_score0.75 and 0.75
Retrieved documentsprecision@3, recall@30.67 and 1.00 for both questions
A written answerexact match vs key-fact checkA: False / True; B: False / False
Many answersa rubric of yes-or-no checksa pass rate

Try it yourself

  1. In the retrieval script, set K = 2 and compare precision and recall.
  2. Add a third test question and mark the documents you think are relevant.
  3. In the generation script, add an answer C with the numbers spelled out in words. What does the check say?

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 · 47 of 79

Previous
Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
Next post
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval

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

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.

Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions

A teammate changes one prompt line to make answers shorter, and four of ten golden questions lose their facts. A pytest eval on saved answers catches it: 12 passed for the old prompt, 2 failed gates and 4 xfailed cases for the new one, exit code 1, and the pull request check turns red.

On this page

  • A fishing net
  • The classic ruler: one label per row
  • Retrieval is a net too
  • Many right answers
  • Same ruler, new things to measure
  • The label becomes a rubric
  • 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.