Hello! Welcome back to the course.
In our last lesson, you learned how to control an LLM's output, forcing it to produce structured JSON that your applications can reliably parse. This was a massive step towards treating LLMs as predictable components in a software system.
However, a structurally valid response isn't necessarily a good response. It could be factually incorrect, miss the point of the user's query, or be incoherent. This brings us to a fundamental challenge in AI engineering: how do you test and measure the quality of an LLM's output?
Today's lesson will tackle this head-on. Our learning goal is to evaluate LLM outputs for quality, coherence, and factuality against defined criteria. Think of this as learning how to write the "test suite" for your LLM-powered features.
The Unique Challenges of Evaluating LLMs
As a software engineer, you're used to deterministic tests: given input X, function Y must return output Z. LLMs break this paradigm. They are non-deterministic, their failure modes can be subtle, and what constitutes a "good" answer is often subjective.
To get a solid grasp of why evaluation is so crucial and complex in the world of LLMs, let's start with a video that frames the problem perfectly.
How to Systematically Setup LLM Evals (Metrics, Unit Tests, LLM-as-a-Judge)
This video, 'How to Systematically Setup LLM Evals' by Dave Ebbelaar, introduces the core challenges we face, such as non-determinism and subjectivity, and explains why we need a systematic approach to evaluation.
Please watch the first section, from 01:55 to 09:22. Focus on understanding the key questions that evaluations help answer and the three core challenges of LLM development that he outlines.
As the video highlights, simply "eyeballing" a few examples isn't enough. We need a more rigorous process, especially when we want to know if changing a prompt or a model has actually made things better or worse.
Key Dimensions of LLM Evaluation
When we talk about a "good" response, we're usually assessing several qualities at once. For most applications, these can be boiled down to a few key dimensions.
LLM Evaluation Metrics: The Ultimate LLM Evaluation Guide
This guide from Confident AI provides an excellent breakdown of the most common and important metrics used in LLM evaluation. It gives us a vocabulary to talk about different aspects of output quality.
Please read the section 'What are LLM Evaluation Metrics?'. Pay close attention to the list of 8 common metrics. You don't need to memorize them, but understand how they map to broader concepts like factuality, relevance, and safety.
From that list, we can group the most critical metrics into categories that align with our learning goal:
- Factuality & Faithfulness: Is the output true? Does it contain made-up information (hallucinations)? Metrics like
CorrectnessandHallucinationaddress this. - Quality & Relevance: Is the output on-topic and helpful? Does it actually answer the user's question? Metrics like
Answer Relevancyare key here. - Coherence: Do the sentences and ideas in the output logically connect to each other? This is often part of a more subjective, task-specific evaluation.
- Safety & Responsibility: Does the output avoid harmful, biased, or toxic content? Metrics like
BiasandToxicityare crucial for user-facing applications.
A Three-Tiered Approach to Evaluation
So, how do we measure these things in practice? A robust evaluation strategy involves multiple layers, much like a testing strategy in software development (unit, integration, end-to-end).

The video you watched earlier introduces a fantastic three-level framework. Let's walk through it.
Level 1: Unit Tests
This should feel very familiar. These are fast, cheap, automated checks for basic, non-negotiable properties of the output.
- Format Compliance: In the last lesson, we used Pydantic models to enforce a schema. A simple unit test would be to ensure the LLM call doesn't raise a validation error.
- Simple Assertions: You can write
assertstatements to check for expected values in structured output. For example, if you're categorizing support tickets, you can assert that thecategoryfield is one of the valid options you defined.
# A simple unit test based on last lesson's Pydantic model
from typing import Literal
from pydantic import BaseModel
class ReviewAnalysis(BaseModel):
product_name: str
sentiment: Literal['positive', 'neutral', 'negative']
# Assume 'llm_output' is the Pydantic object from the LLM
# llm_output = ReviewAnalysis(product_name='X-Processor', sentiment='positive')
def test_sentiment_is_valid():
valid_sentiments = {'positive', 'neutral', 'negative'}
assert llm_output.sentiment in valid_sentiments
# This kind of test can be run in any standard testing framework like pytest.
Unit tests are great for catching regressions but don't tell you anything about the semantic quality of the output.
Level 2: Systematic Evaluation (Human & Model-Based)
This is the core of modern LLM evaluation. It involves running your system against a curated set of examples (an "evaluation set") and scoring the outputs.
First, you need data. The Databricks video "Evaluating LLM-based Applications" suggests an incremental approach to building your evaluation set:
- Start Small: Hand-craft 10-20 high-quality examples that cover common use cases and tricky edge cases.
- Generate More: Use a powerful LLM like GPT-4 to generate more variations of these examples.
- Add Real Data: As your application is used, log interesting or failed interactions and add them to your evaluation set.
Once you have your dataset, you need a "judge" to score the outputs. This leads to the most powerful technique in modern LLM evaluation: LLM-as-a-Judge.
Level 3: A/B Testing
This is the most advanced level, typically used for mature applications. You deploy two versions of your model or prompt (Variant A and Variant B) to different segments of real users and measure which one performs better on business-level KPIs, like user satisfaction, task completion rate, or engagement. We won't implement this now, but it's the ultimate test of real-world performance.
Deep Dive: The LLM-as-a-Judge Pattern
The idea is to use a powerful, state-of-the-art LLM (like GPT-4o) to act as an impartial judge, critiquing the output of your application's LLM based on a rubric you provide.
However, there's a critical first step: you must align the LLM judge with human judgment. You can't automate evaluation until you know what "good" looks like from a human perspective.
The following video segment explains this human-centric alignment process beautifully.
How to Systematically Setup LLM Evals (Metrics, Unit Tests, LLM-as-a-Judge)
Let's return to the Dave Ebbelaar video. This section is the most important part of our lesson. It demonstrates the practical, iterative process of creating an automated evaluator that 'thinks' like a human expert.
Please watch from 18:10 to 31:57. This is a dense but highly valuable section. Pay close attention to: Why you must start with human evaluation before automating. The step-by-step process of using a simple spreadsheet to collect model critiques, human critiques, and measure the alignment between them. The concept of using meta-prompting to refine the judge's prompt and improve the human-model agreement score.
This iterative cycle is the key takeaway:
- Collect Outputs: Run your LLM application on your evaluation dataset.
- Generate Model Critiques: Have your LLM judge score each output based on an initial prompt/rubric.
- Get Human Critiques: Have a human (ideally a domain expert, but initially, you) score the same outputs. This is your "ground truth."
- Compare & Iterate: Measure the agreement between the LLM judge and the human judge. If the agreement is low, analyze the discrepancies. Use the insights (and the human critiques) to refine the LLM judge's prompt. Repeat until the LLM judge reliably mimics human assessment.
Implementing LLM-as-a-Judge with G-Eval and DeepEval
Once you have a clear rubric, you can use a structured framework for your LLM judge. G-Eval is a popular technique for this.

This process, while powerful, can be complex to implement from scratch. Fortunately, open-source libraries like deepeval make it incredibly straightforward. They provide pre-built metrics that use the LLM-as-a-judge pattern under the hood.
Let's see it in action. First, install the library:
pip install deepeval
# You'll also need to have your OPENAI_API_KEY set as an environment variable
Now, let's write a simple evaluation test case. We'll use the AnswerRelevancyMetric to check if the model's output is relevant to the input query.
from deepeval import evaluate
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.test_case import LLMTestCase
# 1. Define the metric you want to use
# The threshold sets the minimum acceptable score (0.0 to 1.0)
metric = AnswerRelevancyMetric(threshold=0.7)
# 2. Create a test case
# This represents one entry in your evaluation set
test_case = LLMTestCase(
input="What is the capital of France?",
actual_output="Paris is the capital of France, known for its art, fashion, and culture."
)
# 3. Run the evaluation
# The 'evaluate' function runs the metric against the test case
# In the background, it makes an LLM call to a powerful model like GPT-4
# to judge if the 'actual_output' is relevant to the 'input'.
evaluate([test_case], [metric])
# When you run this, deepeval will print a report:
# ✅ Test Passed
# -- Metric Score --
# Answer Relevancy: 1.0
# -- Reason --
# The output directly and correctly answers the input question about the capital of France.
Test your understanding!
What do you think would happen if you changed the actual_output in the code above to "The Eiffel Tower is a famous landmark in Paris."? Would the AnswerRelevancyMetric pass or fail? Why?
Show answer
The metric would likely fail (or score very low). The output, while related to the topic of Paris, does not directly answer the question "What is the capital of France?". The LLM judge, following its rubric for "answer relevancy," would identify that the core question was not addressed, even though the statement is factually correct. This demonstrates the difference between correctness and relevancy.
deepeval and similar frameworks (Ragas, uptrain) are powerful tools that encapsulate the best practices of LLM-as-a-judge into easy-to-use Python objects. You can integrate these into a CI/CD pipeline to automatically test your prompts and models, just as you would with traditional software.
Conclusion
You now have a solid framework for thinking about and implementing LLM evaluation. This is a critical skill that separates hobbyists from professional AI engineers. Building a good LLM application isn't just about clever prompting; it's about having a rigorous process to validate that your system is effective, reliable, and safe.
Key Takeaways:
- Evaluation is Essential: You cannot reliably improve LLM applications without a systematic way to measure their quality.
- Start with Humans: Automated evaluation must be grounded in and aligned with human judgment. The goal is to build an AI judge that replicates the decisions of a human expert.
- Use a Multi-Layered Approach: Combine fast "unit tests" for format and structure with more in-depth "systematic evaluation" for semantic quality using an evaluation set.
- LLM-as-a-Judge is the Standard: Using a powerful model to critique your application's output is the most effective and scalable evaluation method today. Frameworks like G-Eval, implemented in libraries like
deepeval, make this practical. - Define Your Criteria: Be explicit about what you're measuring. Choose specific metrics like
AnswerRelevancy,Faithfulness, orCorrectnessthat align with your application's goals.
Next Up:
With a solid understanding of LLM fundamentals—prompting, structured outputs, and now evaluation—we are ready to move on to building more advanced systems. In the next module, we will dive into one of the most popular and powerful patterns in the LLM space: Retrieval-Augmented Generation (RAG). You'll learn how to connect an LLM to your own private data, and we'll see how the evaluation principles you learned today are used to assess both the retrieval and generation components of a RAG pipeline.