LESSON 71 Β· PRODUCTION GENAI

Evaluation

Learn how to measure whether a GenAI application is actually useful, correct, grounded, safe, fast, and cost-effective before and after it reaches production.

20 min readβ€’Intermediateβ€’Pythonβ€’Production

How GenAI Evaluation Works

Test SetQuestions + expected outcomes
AI ApplicationPrompt + RAG + tools
EvaluationRules + model judges
Quality SignalsCorrectness + groundedness
CompareBaseline + versions
ImproveFix + retest
iImportant: A model response can sound excellent and still be wrong. GenAI evaluation should measure the behavior that matters for the actual task, not just whether a request completed successfully.
1

What Is GenAI Evaluation?

Evaluation is the systematic process of measuring an AI application's behavior against defined expectations. It helps you decide whether a prompt, model, retriever, tool workflow, or full application is good enough for users.

Key idea:Evaluation turns β€œthis answer looks good” into measurable evidence that you can compare across versions.
2

Why Evaluation Matters

Production GenAI systems can change when you update a model, prompt, chunking strategy, retrieval configuration, tool, or safety policy.

  • Catch regressions: A new change may improve one task and break another.
  • Compare models: Measure quality before choosing a cheaper or faster model.
  • Improve RAG: Separate retrieval problems from generation problems.
  • Measure agents: Check whether the agent selected the right tools and completed the task.
  • Control risk: Test unsafe, incorrect, and sensitive scenarios before release.
  • Track production quality: Combine offline tests with real user feedback.
3

What Should You Evaluate?

Choose metrics based on the application. A customer-support assistant needs different tests from a document extraction system or research agent.

CorrectnessIs the answer factually and task-wise correct?
RelevanceDoes it directly answer the user's question?
GroundednessIs the answer supported by retrieved context?
CompletenessDoes it cover the important required information?
SafetyDoes it follow security and content policies?
Task successDid the application accomplish the user's goal?
4

Offline vs Online Evaluation

Offline evaluation

Run a fixed dataset before deployment. It is repeatable and useful for regression testing.

Online evaluation

Measure real production traffic using feedback, sampled traces, and automated quality checks.

Best practice

Use both. Offline tests protect releases; online evaluation shows what happens with real users.

5

Build a Golden Test Set

A golden dataset contains representative inputs and expected outcomes. Start small, then grow it from real failures and important business scenarios.

Happy paths

Common requests that the system should answer reliably.

Edge cases

Ambiguous, long, incomplete, or unusual inputs.

Failure cases

Known bugs, hallucinations, retrieval misses, and tool failures.

Safety cases

Prompt injection, data leakage, and disallowed actions.

6

Python: Represent an Evaluation Case

Keep test cases structured so the same dataset can be reused after every change.

</> Python
test_case = {
    "id": "billing-001",
    "question": "When is my invoice due?",
    "expected_facts": [
        "The invoice is due within 30 days."
    ],
    "must_be_grounded": True,
}

print(test_case["id"])

Store expected facts or acceptable answers instead of relying on one exact string match when multiple answers can be valid.

7

Exact Match and Rule-Based Checks

Deterministic checks are excellent when the expected output has a predictable structure.

Exact matchUseful for fixed labels, IDs, and simple classifications.
Schema checkVerify required fields, types, and valid JSON structure.
Business ruleCheck constraints such as totals, ranges, or required citations.
Use rules when possible:Deterministic checks are cheaper, repeatable, and easier to debug than asking another model to judge everything.
8

Semantic Evaluation

For open-ended responses, two correct answers may use different words. Semantic evaluation checks whether the meaning is sufficiently aligned with the expected outcome.

QuestionInput
AnswerGenerated
ReferenceExpected
JudgeCompare
Score0–1 or 1–5
9

LLM-as-a-Judge

An evaluator model can score qualities such as relevance, correctness, style, or groundedness. Give it explicit criteria and a structured output format.

Do not trust a single judge blindly:Judge models can have bias, inconsistent reasoning, and sensitivity to wording. Validate them against human-reviewed examples.
10

Python: Simple Rubric

A rubric makes evaluation criteria explicit and easier to compare.

</> Python
rubric = {
    "correctness": "0 = wrong, 1 = partly correct, 2 = correct",
    "relevance": "0 = off-topic, 1 = mostly relevant, 2 = direct",
    "groundedness": "0 = unsupported, 1 = partly supported, 2 = supported",
}

score = {
    "correctness": 2,
    "relevance": 2,
    "groundedness": 2,
}

print(sum(score.values()))
11

Evaluate RAG Retrieval Separately

Do not evaluate only the final answer. First check whether the retriever returned the information needed to answer the question.

QueryUser question
RetrieveCandidate chunks
CheckRelevant context?
GenerateFinal answer
EvaluateGrounded?

If the required document never appears in the retrieved context, generation quality alone cannot fix the retrieval failure.

12

Retrieval Metrics

For search and RAG systems, evaluate retrieval independently using a labeled set of relevant documents.

  • Recall@K: Did the relevant item appear in the top K results?
  • Precision@K: How many of the top K results were relevant?
  • MRR: How high was the first relevant result?
  • NDCG: How well were results ordered when relevance has multiple levels?
  • Empty retrieval rate: How often did search return nothing useful?
  • Source coverage: Did the retrieved context contain the needed evidence?
13

Evaluate Agents

Agents need trajectory-level evaluation. A final answer can be correct even when the agent took an inefficient path, and an apparently reasonable path can still fail the task.

Tool selectionDid the agent choose the correct tool?
ArgumentsWere tool inputs valid and appropriate?
SequenceWere actions taken in a sensible order?
TerminationDid the agent stop instead of looping?
Task successWas the user's goal actually completed?
EfficiencyHow many model calls and tool calls were required?
14

Evaluate Safety and Guardrails

Include adversarial cases in the evaluation set. Test whether the application blocks or safely handles unsafe inputs, prompt injection, sensitive-data requests, and unauthorized actions.

Input safety

Does the system detect risky or malicious requests?

Data protection

Does it avoid exposing secrets or unrelated private data?

Tool safety

Does it prevent unauthorized or dangerous actions?

Output safety

Does the final response follow the required policy?

15

Human Evaluation

Human review remains valuable for ambiguous or high-impact tasks. Use a clear rubric so reviewers evaluate the same criteria.

Sample

Review a representative subset rather than every request.

Blind comparison

Hide which model or prompt produced each answer when comparing versions.

Agreement

Measure reviewer agreement and refine the rubric when judgments differ frequently.

16

Evaluation Thresholds

Turn scores into release decisions. Define minimum acceptable quality before the application reaches users.

MetricQuality
BaselineCurrent
TargetRequired
RegressionAllowed?
ReleasePass/Fail

For example, you might require retrieval Recall@10 to stay above a target while keeping cost and p95 latency below their budgets.

17

Regression Testing

Run the same golden dataset whenever you change prompts, models, embeddings, chunking, reranking, tools, or guardrails.

Think like software testing:Every production bug that reaches users can become a permanent regression test so the same failure is less likely to return.
18

Compare Model Versions

Evaluate quality, latency, and cost together. A model with a slightly lower quality score may still be the better production choice for a low-risk task if it is dramatically faster and cheaper.

Quality

Correctness, relevance, groundedness, and task success.

Performance

TTFT, total latency, throughput, and failure rate.

Economics

Tokens and cost per successful task.

Risk

Safety, policy adherence, and failure severity.

19

Production Evaluation

Offline evaluation does not represent every real-world request. Sample production traffic and evaluate it using privacy-safe telemetry, user feedback, automated checks, and periodic human review.

  • Sample real requests by feature or tenant.
  • Redact or minimize sensitive information.
  • Track thumbs-up/down and task completion.
  • Investigate low-score traces.
  • Add important failures to the golden dataset.
  • Watch quality trends after model or prompt changes.
20

Evaluation Pipeline

DatasetCases
RunApplication
ScoreMetrics
CompareBaseline
GateRelease

Keep evaluation automated enough to run in development and CI, while reserving human review for cases where automated scoring is not trustworthy.

21

Common Evaluation Mistakes

  • Using only one test question.
  • Measuring only model output and ignoring retrieval.
  • Using exact string matching for open-ended answers.
  • Trusting an LLM judge without validation.
  • Ignoring safety and adversarial cases.
  • Optimizing average quality while missing tail failures.
  • Changing the test set until a model looks better.
  • Collecting production data without privacy controls.
22

Mini Project: Build a RAG Evaluation Harness

Create a small Python evaluation harness for a support RAG application.

Step 1

Create 20 representative questions with expected facts.

Step 2

Run each question through your RAG pipeline.

Step 3

Measure retrieval Recall@K and whether the answer contains the expected facts.

Step 4

Record latency, token usage, and cost alongside quality.

Step 5

Compare two prompts or models against the same dataset.

Step 6

Fail the release if a critical quality or safety threshold is missed.

23

Evaluation Checklist

Dataset

Representative, versioned, and protected.

Metrics

Task-specific quality and operational metrics.

Baselines

Previous model/prompt results are stored.

Regression

Every important failure becomes a test.

Safety

Adversarial and policy cases are included.

Release gate

Minimum thresholds are enforced.

30-Second Recap

01Evaluation measures whether the AI system actually works for its intended task.
02Use golden datasets, deterministic checks, semantic metrics, and human review.
03Evaluate RAG retrieval and agent trajectories separately from final answers.
04Run regression tests whenever models, prompts, retrieval, tools, or guardrails change.
05Combine quality with latency, cost, reliability, and safety.
06Use production feedback to continuously improve the evaluation set.

Key Takeaways

  • There is no single GenAI metric that works for every application.
  • Evaluate the complete system, not just the model.
  • Keep a versioned golden dataset and run regression tests.
  • Separate retrieval quality, generation quality, tool behavior, and safety.
  • Use deterministic checks where possible and validate LLM judges.
  • Make evaluation part of the production improvement loop.

Quick Quiz

1. Why is a golden dataset useful?

It provides repeatable test cases for comparing versions and catching regressions.

2. When should you use exact-match evaluation?

When the expected output is deterministic, such as a fixed label or ID.

3. Why evaluate RAG retrieval separately?

A missing relevant chunk is a retrieval failure that generation cannot reliably repair.

4. What is LLM-as-a-judge?

An evaluator model scores another model's output against explicit criteria.