10B.2 DeepEval Fundamentals: Test Cases, Metrics and the Test Runner
DeepEval is the open-source Python evaluation library from Confident AI, and its pitch is one line: unit testing for LLM apps. You record what your app did as a test case, you pick metric objects that score it against a threshold, and you run them either from Python with evaluate() or from pytest with assert_test() and the deepeval test run command, which fails your CI job when a metric fails. This lesson teaches that core properly, the way an engineer who has to defend the numbers needs to know it: what installing and importing the package does to your machine and your environment, every field of the test-case classes and which metrics read which field, the contract every metric object follows, evaluate() and its four configuration objects, the result objects, the pytest runner with its flags and exit codes, the cache, local result files and the SQLite store, the command line, and the traps that bite in the first week. Every runnable sample in the lesson ran on a laptop with no API key, using DeepEval's deterministic metrics, two small custom metrics and a scripted fake judge (FakeJudge), and every output shown is what those runs printed. Several of those runs found behaviour the documentation does not describe, and the lesson shows each one.
What you'll learn
- What DeepEval is (a library, a pytest runner, a command line, and an optional paid platform called Confident AI), who maintains it, its licence, its release pace, and how to upgrade it safely
- What
uv add deepevalinstalls (about 80 packages, including pytest and four pytest plugins, the OpenAI SDK, OpenTelemetry and a telemetry client) and what it leaves out - What
import deepevaldoes before your code runs: loading.envfiles in a fixed order, and how to switch that off - What DeepEval sends as telemetry, how to opt out, and what it writes to disk (
.deepeval/,.env.local, results files) LLMTestCasefield by field, the table of which metric needs which field,contextversusretrieval_context,ToolCalland its equality rule,ConversationalTestCaseandTurn,MLLMImage, andArenaTestCase- The metric object contract:
threshold,score,reason,success, the>=pass rule,threshold=None,strict_mode,flaky,include_reason,async_mode, and why LLM metrics fail at construction without a key - DeepEval's deterministic metrics and their exact rules, and how to write your own metric in twenty lines
measure(),a_measure(),evaluate()withAsyncConfig,DisplayConfig,CacheConfigandErrorConfig, and theEvaluationResult→TestResult→MetricDataobjects you read afterwards- The rule
evaluate()andassert_test()use, in their default async mode, to rebuild your metric for each test case, and the silent bug it causes when a custom metric stores an argument under a different name assert_test(),deepeval test run, every flag, extra pytest arguments, exit codes,log_hyperparametersandon_test_run_end- The cache (what its key contains, when it is read, and how it serves stale scores), saving runs as JSON, the SQLite store, and reading a saved run back
- The command line (
diagnose,settings,set-*, and the commands that upload data), and the environment variables worth knowing - The complete
evalkit↔ DeepEval mapping, how to run anevalkitgrader inside DeepEval, and what DeepEval does not do for you - Methodology from the first run: naming the number, oracle and null controls, reading reasons, intervals on small suites, and recording what produced a number
What you don't need
- An API key. LLM metrics in this lesson run against
FakeJudge, a scripted judge that never calls a model; the only illustrative samples are the ones that name a real provider, and they are labelled. - A Confident AI account. DeepEval works fully offline for everything in this lesson; the platform is surveyed in 10B.7.
- Depth on the judges and metrics. How DeepEval picks and wraps a judge model, G-Eval, DAG and custom LLM metrics are 10B.3; every built-in metric's prompts and formulas are 10B.4; tracing and agent metrics are 10B.5; datasets, goldens and synthetic data are 10B.6; CI pipelines, red teaming and the platform are 10B.7. This lesson uses a G-Eval metric as a black box in a few runs and points to those lessons for what is inside.
- The eval concepts themselves. Test cases, deterministic graders, judges, CI gates and statistics were taught framework-free in 10A.1 to 10A.8; here they are mapped onto DeepEval, not re-taught. 10B.1 explains why you would adopt a framework at all and sets up the project the track uses.
Setup
You need Python 3.10 or newer (DeepEval's floor; the course uses 3.13) and uv. If you have not set up a uv project before, 01B.1 and 03.1, Part 4 walk through it; 10B.1 sets up one project for the whole track, and this lesson works in it or in a fresh one.
uv init deepeval-lab --bare --python 3.13 && cd deepeval-lab # first time only
uv add deepeval
# or: pip install deepevalThen create a .env file in the project folder with one line, so that no run in this lesson sends usage telemetry (Part 1.5 explains what that is):
# .env (commit a copy without secrets as .env.example)
DEEPEVAL_TELEMETRY_OPT_OUT=1That is everything the runnable samples need. Save each sample under the file name its first comment gives, all in one folder, and run Python files with uv run python file.py and the command line with uv run deepeval ... from that folder. Several samples import two small helper files you write early on (fake_judge.py in 3.5 and support_metrics.py in 3.7) and a third (support_cases.py, in 4.2), so keep them in the same folder. The illustrative real-provider snippets would also need the provider's SDK and a key; nothing else in the lesson needs either.
Versions (current at time of writing, read from PyPI on 24 November 2026): deepeval 4.3.5 (released 24 November 2026, Apache-2.0, Python ≥ 3.10). DeepEval ships a release every few days, and releases have changed scores and names (the 4.2.0 release flipped the direction of four metrics), so treat the version as a snapshot and read 1.2 on upgrading. Every sample marked as run was executed on 24 November 2026 with Python 3.13.14, deepeval 4.3.5 and pytest 9.2.0 in a uv virtual environment, with DEEPEVAL_TELEMETRY_OPT_OUT=1 and no provider key set; the output blocks are what those runs printed, trimmed only where marked. The package source was read the same day to confirm behaviour the documentation leaves out.
What you must be able to do after this lesson#
- Build an LLMTestCase and tell context from retrieval_context
- Create a metric and explain its threshold rule (a score equal to the threshold passes)
- Score a suite in code with evaluate() and read results from the returned object, not from m.score
- Write a pytest test with assert_test() and run it with deepeval test run
- Explain what the DeepEval cache key contains and one change it does not notice
- Choose between the two ErrorConfig policies for a failing case
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "DeepEval is just pytest for LLMs." | 1.1 and Part 5 |
"Why did uv add deepeval pull in pytest and OpenTelemetry?" |
1.3 |
"CI is using the wrong model: it picked up someone's .env.local." |
1.6 |
| "Does DeepEval phone home?" | 1.5 |
"Which fields does Faithfulness need? It says retrieval_context cannot be None." |
2.3 |
"Should the retrieved chunks go in context or retrieval_context?" |
2.4 |
| "It crashed before it scored anything: 'OpenAI API key is not configured'." | 3.4 |
| "Is a score of exactly 0.7 with threshold 0.7 a pass?" | 3.2 |
| "Write a quick custom metric for that." | 3.7 |
| "Run the suite and send me the pass rate." | Part 4 and Part 10.1 |
| "My custom metric ignores the limit I passed in." | 4.5 |
| "One test case is missing a field and the whole run died." | 4.9 |
| "Wire it into CI so the build fails when quality drops." | Part 5 |
| "Turn on the cache so reruns are free." | Part 6 |
| "Where are the results? I need last week's run." | 6.4 and 6.5 |
| "How does this map to evalkit?" | Part 8 |
| "The suite passed 2 of 3, so we're at 67%." | Part 10 |
Part 1: What DeepEval is, and what installing it changes#
1.1 A library, a test runner, a command line and an optional platform#
"DeepEval" names four things that ship in, or connect to, one package:
| Piece | What it is | What you do with it |
|---|---|---|
The Python library (deepeval) |
Test-case classes (LLMTestCase, ConversationalTestCase, ...), more than 50 metric classes, the evaluate() and assert_test() runners, judge-model wrappers, datasets, a synthesizer, a conversation simulator, tracing |
Write test cases and metrics in ordinary Python; score them with evaluate() or inside pytest |
| The pytest runner | A pytest plugin plus the deepeval test run command, which runs pytest with that plugin, prints a results table and exits with pytest's code |
Gate CI on metric thresholds |
The command line (deepeval) |
Configuration (set-*, settings, diagnose), the runner (test run), a trace viewer (inspect), and platform commands (login, view, gate) |
Configure the default judge, inspect your configuration, run tests |
| Confident AI (optional, commercial) | Confident AI's hosted platform: stores runs, datasets and traces, compares runs, runs evals on production traffic | Nothing in this lesson. Several commands upload to it, so 7.5 lists the ones to avoid when you want everything local |
The design idea that runs through the whole library is the one in its tagline: an evaluation is a unit test. A test case holds one interaction, a metric is an assertion with a threshold, and the result is pass or fail per test case, with a score and a written reason per metric. That shape is excellent for regression gates on product behaviour and is the main reason teams pick DeepEval. It is weaker for research-style evals with many models, long agent transcripts and statistics, which is the ground Inspect covers; 10B.17 compares the two on every axis.
The second idea is that most metrics are LLM-as-a-judge. Of DeepEval's 50-plus metrics, only a handful are plain code (Part 3.6). The rest send prompts to a judge model (by default an OpenAI model, chosen as 10B.3 explains) and turn the answers into a score with a fixed formula. Everything 10A.4 and 10A.5 said about judges applies to those metrics: they are instruments with error, and DeepEval gives you no tools to measure that error (8.4).
1.2 Who builds it, the licence and the release cadence#
These facts are volatile; each is dated and each has a place to check it again.
| Fact (as of 24 November 2026) | Value | Where to check |
|---|---|---|
| Maintainer | Confident AI (the package's author field names Jeffrey Ip of Confident AI) | PyPI, GitHub |
| Licence | Apache-2.0 | the LICENSE.md file on GitHub |
| Package and command | deepeval on PyPI; import name deepeval; command deepeval |
uv run deepeval --version |
| Current version | 4.3.5, uploaded 24 November 2026 | PyPI |
| Python | 3.10 or newer (classifiers list 3.10 to 3.14) | PyPI |
| Repository | confident-ai/deepeval, created August 2023, about 19.6k stars |
GitHub |
| Cadence | Very fast: roughly 30 releases between 4.0.8 (10 July 2026) and 4.3.5 (24 November 2026), about one every five days | the PyPI release history |
| Release notes | The GitHub releases page stops at python-v4.2.4 (22 September 2026); later versions appear only on PyPI |
GitHub releases |
| Other SDKs | A TypeScript SDK (deepeval on npm) shares the metric prompts; the docs pages have Python and TypeScript tabs. This track covers Python only |
the docs |
The releases that matter most for code you will read online (dates are PyPI upload dates; a GitHub release can be dated a few days earlier):
| Version (date) | What changed |
|---|---|
| 2.2.7 (January 2025) | The DAG metric ("deterministic LLM-judge metrics"), 10B.3 |
| 2.5.9 (March 2025) | Custom prompts for metrics (evaluation_template) |
| 3.0 (May 2025) | Component-level evals and tracing, 10B.5 |
| 4.0.2 (May 2026) | "Eval harness for coding agents", one-line integrations, a terminal trace viewer |
| 4.1.7 (August 2026) | Flaky test cases and flaky metrics (3.3) |
| 4.2.0 (24 August 2026) | Every metric now scores 0 to 1 with higher meaning better. Bias, Toxicity, Hallucination and Misuse used to score the proportion of violations, with the threshold as a maximum; they flipped. A tutorial written before August 2026 with ToxicityMetric(threshold=0.2) meant "at most 20% toxic"; in 4.3.5 the same line means "at least 0.2 clean", a much weaker gate (10B.4 covers those metrics) |
| 4.2.4 (September 2026) | Classifiers and "eval modes" with an external decision model, surveyed in 10B.3 |
| 4.3.x (October to November 2026) | The current line: Expectations, the SQLite local store, the deepeval setup wizard |
Three habits follow. Pin the version you validated. In a uv project the lock file (uv.lock) pins it; commit it. The course writes install commands without version pins, so pinning is the lock file's job. Upgrade on purpose: read what changed, then re-run a known suite on the old and new version and compare scores case by case before you trust a trend line that crosses the upgrade (10A.8, 8.4 is the playbook). Record the version with every result: a DeepEval score is only comparable with scores from the same version, because prompts and formulas change between releases (Part 10.5 shows where to record it).
1.3 What uv add deepeval installs, and what it does not#
The install is broad. In a fresh virtual environment, deepeval 4.3.5 brought in 80 packages and about 140 MB of site-packages (the deepeval package itself is about 12 MB). Among them, run on 24 November 2026:
confident-trace 0.1.14
deepeval 4.3.5
grpcio 1.85.4
openai 3.58.0
opentelemetry-api 1.45.2
opentelemetry-sdk 1.45.2
... (ten more opentelemetry-* packages)
posthog 7.91.4
pydantic 2.14.4
pytest 9.2.0
pytest-asyncio 1.5.0
pytest-repeat 0.9.4
pytest-rerunfailures 16.7
pytest-xdist 3.8.0
rich 14.3.4
typer 0.29.2What that means in practice:
| Installed | Why | Consequence for you |
|---|---|---|
pytest and four plugins (pytest-asyncio, pytest-repeat, pytest-rerunfailures, pytest-xdist) |
The test runner is part of the product | DeepEval decides your pytest version unless your lock file does; the plugins load in every pytest session in that environment (5.6) |
The openai SDK |
The default judge is an OpenAI model | An OpenAI client is present even if you never use OpenAI |
OpenTelemetry and gRPC exporters, confident-trace |
Tracing (10B.5) | Heavier images; import deepeval sets GRPC_VERBOSITY=ERROR to quiet gRPC |
posthog |
The telemetry client (1.5) | Switch it off |
pydantic, rich, typer, tenacity, python-dotenv, jinja2 and more |
Test cases are Pydantic models, the console is Rich, the CLI is Typer, retries are Tenacity, .env loading is python-dotenv, metric prompts are Jinja templates |
Version conflicts with your app are possible; keep evals in their own dependency group or project if they appear |
What it does not install:
| Not included | Why it matters | What to add |
|---|---|---|
| Provider SDKs other than OpenAI | Each judge wrapper imports its SDK when you create it and raises an error with an install hint if it is missing (for example OllamaModel requires the 'ollama' package) |
anthropic for AnthropicModel; google-genai and google-auth for GeminiModel; litellm for LiteLLMModel and provider-prefixed model strings; see 10B.3 |
| The trace viewer's terminal UI | deepeval inspect exits with "pip install 'deepeval[inspect]'" without it |
uv add "deepeval[inspect]" (the only optional extra; it adds textual and pyperclip) |
ragas and its dependencies |
Only the RAGAS wrapper metrics need them | 10B.4 |
1.4 Importing DeepEval has side effects#
import deepeval runs code before your first line does. Reading deepeval/__init__.py in 4.3.5, in order:
- It loads
.envfiles from the current working directory intoos.environ(the next two sections). This happens before anything else, which is why aDEEPEVAL_TELEMETRY_OPT_OUT=1line in.envis honoured. - It sets
GRPC_VERBOSITY=ERRORif you have not set it (unlessDEEPEVAL_GRPC_LOGGINGis set). - It checks PyPI for a newer version only if you opt in with
DEEPEVAL_UPDATE_WARNING_OPT_IN=1. - It exposes a small top-level API:
evaluate,assert_test,compare,log_hyperparameters,on_test_run_end,login,instrument,flush_traces,a_flush_traces.
One import quirk saves a confusing error: deepeval.evaluate is a function after import, and the configuration classes are re-attached to it for compatibility. Import them as from deepeval.evaluate import AsyncConfig, DisplayConfig, CacheConfig, ErrorConfig, which is the form every sample here uses.
1.5 Telemetry, and how to switch it off#
By default DeepEval sends anonymous usage events to PostHog, a product-analytics service. In 4.3.5 the telemetry client is the only module that imports posthog. The docs' data-privacy page says what is collected: event names (an evaluation ran, a synthesizer ran, a CLI command ran, and so on, with the entry point such as evaluate or pytest), metric names, whether you are in a notebook, which local store you use, an anonymous machine id, and your public IP address (for coarse region). Your test cases and outputs are not on that list, the page says DeepEval "does not report crashes or exceptions anywhere", and the 4.3.5 source contains no crash reporter (only the PostHog client).
| Control | Effect |
|---|---|
DEEPEVAL_TELEMETRY_OPT_OUT=1 |
Turns telemetry off. Put it in .env (loaded at import) and in your CI environment |
DEEPEVAL_HOME |
Where the anonymous id file lives (default ~/.deepeval/.deepeval_telemetry.txt) |
DEEPEVAL_TELEMETRY_ENABLED |
An older, inverted variable; still read, but use the opt-out |
Observed in this lesson's runs: with the opt-out set, the DEEPEVAL_HOME directory was never created. Telemetry is not the same as uploading results: nothing in this lesson sends test cases anywhere, but two commands and one evaluate() argument do (7.5).
1.6 Configuration sources and the .env load order#
DeepEval's settings (the judge model, keys, local store, timeouts and dozens more) are read from environment variables, which can come from five places. Because import deepeval loads .env files itself, you need to know the order. This run creates three files and a script in an empty folder:
# .env
GREETING=from .env
APP_ENV=staging
# .env.staging
GREETING=from .env.staging
REGION=from .env.staging
# .env.local
GREETING=from .env.local# env_order.py: which .env file wins when DeepEval loads them? (lesson 10B.2)
import os
print("before import:", os.environ.get("GREETING"), "|", os.environ.get("REGION"))
import deepeval # noqa: E402 (the import itself loads the .env files)
print("after import: ", os.environ.get("GREETING"), "|", os.environ.get("REGION"))
print("APP_ENV =", os.environ.get("APP_ENV"))$ python env_order.py
before import: None | None
after import: from .env.local | from .env.staging
APP_ENV = staging
$ GREETING="from the shell" python env_order.py
before import: from the shell | None
after import: from the shell | from .env.staging
APP_ENV = staging
$ DEEPEVAL_DISABLE_DOTENV=1 python env_order.py
before import: None | None
after import: None | None
APP_ENV = NoneRead it as a precedence list, highest first:
flowchart TD
q["A setting DeepEval needs<br/>(for example OPENAI_MODEL_NAME)"] --> p{"Set in the process<br/>environment?"}
p -->|yes| use1["Use it"]
p -->|no| l{"In .env.local?"}
l -->|yes| use2["Use it"]
l -->|no| e{"In .env.APP_ENV<br/>(only if APP_ENV is set)?"}
e -->|yes| use3["Use it"]
e -->|no| d{"In .env?"}
d -->|yes| use4["Use it"]
d -->|no| k{"In .deepeval/.deepeval<br/>(legacy keystore, no secrets)?"}
k -->|yes| use5["Use it"]
k -->|no| def["Built-in default"]- The process environment always wins. DeepEval only writes keys that are not already set, so a variable exported in your shell or CI job beats every file.
.env.localbeats.env.{APP_ENV}beats.env. The middle file is read only whenAPP_ENVis set: DeepEval looks forAPP_ENVin the process environment, then in.env.local, then in.env(in the run above it came from.env). With noAPP_ENVanywhere, no middle file is read, so a lone.env.devis silently ignored. (The settings object reportsAPP_ENVasdevafterwards, but that default is applied after the files are loaded; checked in the 4.3.5 source,_resolve_app_env()indeepeval/config/settings.py.)DEEPEVAL_DISABLE_DOTENV=1turns the whole mechanism off, andENV_DIR_PATHchanges the folder it looks in (default: the current working directory).- The files are read from the current working directory, not from the script's folder. Run the same script from another folder and different settings apply.
1.7 What DeepEval writes to disk#
Everything goes under .deepeval/ in the current working directory unless you say otherwise. After the first evaluate() run in 4.2, in an empty folder:
$ find .deepeval -type f
.deepeval/.deepeval-cache.json
.deepeval/.latest_run_full.json
.deepeval/.latest_test_run.json| File | Written when | What it holds |
|---|---|---|
.deepeval/.latest_run_full.json |
after every evaluate() or deepeval test run |
the latest run in full (overwritten each time); what deepeval inspect opens |
.deepeval/.latest_test_run.json |
same | the latest run's data and, if logged in, its platform link |
.deepeval/.deepeval-cache.json |
when cache writing is on (the default in evaluate() and test run) |
metric results keyed by test case and metric configuration (Part 6) |
<results_folder>/test_run_YYYYMMDD_HHMMSS.json |
only when you set a results folder (6.4) | one file per run: the durable record |
deepeval.db |
when the SQLite store is on (6.5) | every run, in tables |
.deepeval/.deepeval |
set-* commands run without --save |
the legacy settings keystore (never secrets) |
.env.local |
set-* and login with --save=dotenv |
settings, including API keys in plain text |
A standalone metric.measure(test_case) writes nothing at all (checked: an empty folder stayed empty). Two variables change the defaults: DEEPEVAL_CACHE_FOLDER moves .deepeval/, and DEEPEVAL_FILE_SYSTEM=READ_ONLY stops DeepEval writing files, which is what you want in a read-only container.
Add these to your .gitignore on day one:
.deepeval/
.env.local
deepeval.db
results/1.8 The mental model: test cases, metrics, a runner, results#
Four pieces, and one fact that ties them together: DeepEval scores what your app already produced.
flowchart LR
app["Your app<br/>(already ran)"] --> tc["Test cases<br/>LLMTestCase / ConversationalTestCase"]
tc --> m["Metrics<br/>objects with a threshold"]
judge["Judge model<br/>(LLM metrics only)"] -.-> m
m --> runner{"Runner"}
runner -->|"measure()"| one["One score on the metric object"]
runner -->|"evaluate()"| res["EvaluationResult<br/>+ console report"]
runner -->|"assert_test() + deepeval test run"| ci["pytest pass/fail<br/>+ exit code"]
res --> files[".deepeval/ cache and latest run<br/>results folder JSON or SQLite"]
ci --> files- Test cases record one interaction: the input, what your app answered, and whatever else a metric needs (a reference answer, the retrieved chunks, the tools called). Part 2.
- Metrics are objects with a threshold that score one test case each time they run, either with code or with a judge model. Part 3.
- A runner applies metrics to test cases:
measure()for one metric on one case,evaluate()for a suite in code,assert_test()underdeepeval test runfor CI. Parts 3.8, 4 and 5. - Results come back as objects, a console report, cache entries and files. Part 4 and Part 6.
What this means for you as an engineer: the part of 10A.1's harness that DeepEval does not own is the part that runs your system. Generating the outputs (with retries, concurrency, caching of your app's calls, and a record of which prompt and model produced them) stays your code, or moves to DeepEval's tracing in 10B.5. DeepEval's cache stores metric results, not your app's outputs.
Part 2: Test cases: recording what your app did#
2.1 A test case is a finished record, not a call#
An LLMTestCase is a Pydantic model that records one interaction after it happened. evaluate() and assert_test() never call your application; they read the fields you filled in. That has three consequences that shape everything else:
- You own generation. Running the app on each input, with whatever concurrency, retries and caching your app's calls need, is your code (2.10 shows the shape). The 10A.1 harness did this inside
run_eval(); in DeepEval you do it before you build the test cases. - A test case is only as honest as its fields. If you put the ideal retrieved chunks into
retrieval_contextinstead of what your retriever really returned, every RAG metric scores a system that does not exist. Fill fields from real runs. - Test cases are cheap and serializable. They are plain data, so you can build them in one job, save them, and score them in another. Datasets of reusable inputs (goldens) that become test cases at run time are 10B.6's subject.
2.2 LLMTestCase, field by field#
The single-turn test case, as defined in 4.3.5 (Pydantic, unknown fields ignored):
| Field | Type and default | What it is for |
|---|---|---|
input |
str, required |
What the user sent. Must be a string: anything else raises TypeError |
actual_output |
str, default None |
What your app answered. Optional in the class; required by almost every metric |
expected_output |
str, default None |
A reference answer, for metrics that compare against one |
context |
list[str], default None |
Ground-truth context: the facts the answer should rest on, written by you. Read by HallucinationMetric |
retrieval_context |
list[str | RetrievedContextData], default None |
What your retriever actually returned, in rank order. Read by the RAG metrics |
tools_called |
list[ToolCall], default None |
The tool calls your agent made |
expected_tools |
list[ToolCall], default None |
The tool calls it should have made |
name |
str, default None |
A stable id. Without one, results show test_case_0, test_case_1, ... by position |
metadata |
dict, default None |
Anything you want carried into results: slice labels, prompt version, model. Returned on every TestResult |
tags |
list[str], default None |
Labels for filtering on Confident AI, and readable by G-Eval. Not returned on TestResult, so use metadata for slicing locally |
comments |
str, default None |
Free text for humans |
token_cost, input_token_count, output_token_count, completion_time |
numbers, default None |
Your app's cost, tokens and latency (seconds). Recorded only; no built-in metric reads them |
flaky |
bool, default False |
A failing flaky case warns instead of failing assert_test() (5.1) |
multimodal |
bool, default False |
Set automatically when an image placeholder appears in a text field (2.7) |
expectations |
Expectations, default None |
Must and must-not conditions checked by a judge (2.9) |
expected_labels |
dict, default None |
Expected labels for classifiers (2.9) |
mcp_servers, mcp_tools_called, mcp_resources_called, mcp_prompts_called |
MCP types | For MCP metrics (10B.5) |
custom_column_key_values |
dict[str, str] |
Extra columns on Confident AI |
The run below exercises the test-case classes, including what they refuse. Each numbered block is discussed in the section after it.
# test_cases.py: what DeepEval's test-case classes accept, and what they refuse (lesson 10B.2)
from pydantic import ValidationError
from deepeval.test_case import (
ArenaTestCase, Contestant, ConversationalTestCase, LLMTestCase,
MLLMImage, RetrievedContextData, ToolCall, Turn,
)
# 1. A single-turn case: only `input` is required.
tc = LLMTestCase(input="How long do I have to return shoes?")
print("1. minimal case:", tc.actual_output, tc.expected_output, tc.name, tc.flaky, tc.multimodal)
# 2. `input` must be a string; a dict (say, your app's request object) is refused.
try:
LLMTestCase(input={"question": "refund window?"})
except (TypeError, ValidationError) as e:
print("2. non-string input:", type(e).__name__, "-", str(e).splitlines()[0][:90])
# 3. A RAG case: retrieval_context is the ranked list your retriever returned.
rag = LLMTestCase(
input="Can I return worn shoes?",
actual_output="Yes, within 30 days if they are unworn.",
retrieval_context=[
RetrievedContextData(context="Unworn shoes can be returned within 30 days.",
source="returns-policy.md#shoes"),
"Gift cards are non-refundable.",
],
)
print("3. retrieval_context when serialized:", rag.model_dump()["retrieval_context"])
# 4. ToolCall equality ignores description, reasoning and type.
a = ToolCall(name="lookup_order", input_parameters={"order_id": "A-1042"},
reasoning="user gave an order id")
b = ToolCall(name="lookup_order", input_parameters={"order_id": "A-1042"},
description="Look up an order by id")
c = ToolCall(name="lookup_order", input_parameters={"order_id": "a-1042"})
print("4. same name+params, different reasoning:", a == b, "| different param case:", a == c)
# 5. Conversations: roles are only "user" and "assistant", and turns must not be empty.
try:
Turn(role="system", content="You are a shoe-store assistant.")
except ValidationError as e:
print("5a. system turn:", e.errors()[0]["msg"])
try:
ConversationalTestCase(turns=[])
except TypeError as e:
print("5b. empty turns:", e)
convo = ConversationalTestCase(
chatbot_role="A polite shoe-store assistant",
turns=[{"role": "user", "content": "These shoes don't fit."},
{"role": "assistant", "content": "Sorry! You can return them within 30 days."}],
)
print("5c. dict turns become:", type(convo.turns[0]).__name__, "| count:", len(convo.turns))
# 6. Images ride inside strings as placeholders; the case flips to multimodal.
img = MLLMImage(url="https://example.com/receipts/A-1042.png")
mm = LLMTestCase(input=f"What is the total on this receipt? {img}", actual_output="$84.00")
print("6. placeholder:", str(img)[:24] + "...", "| multimodal:", mm.multimodal)
try:
MLLMImage(url="receipt.png-does-not-exist")
except Exception as e:
print("6b. bad image:", type(e).__name__, "-", str(e)[:95])
# 7. Arena cases: every contestant must share the same input (and expected_output).
q = "Summarize our refund policy in one sentence."
ok = ArenaTestCase(contestants=[
Contestant(name="prompt-v1", test_case=LLMTestCase(input=q, actual_output="30-day refunds.")),
Contestant(name="prompt-v2", test_case=LLMTestCase(input=q, actual_output="Unworn items: 30 days.")),
])
print("7. arena ok with", len(ok.contestants), "contestants")
try:
ArenaTestCase(contestants=[
Contestant(name="prompt-v1", test_case=LLMTestCase(input=q, actual_output="x")),
Contestant(name="prompt-v2", test_case=LLMTestCase(input=q + " ", actual_output="y")),
])
except ValueError as e:
print("7b. arena mismatch:", e)1. minimal case: None None None False False
2. non-string input: TypeError - 'input' must be a string
3. retrieval_context when serialized: ['returns-policy.md#shoes: Unworn shoes can be returned within 30 days.', 'Gift cards are non-refundable.']
4. same name+params, different reasoning: True | different param case: False
5a. system turn: Input should be 'user' or 'assistant'
5b. empty turns: 'turns' must not be empty
5c. dict turns become: Turn | count: 2
6. placeholder: [DEEPEVAL:IMAGE:f5cf8ae2... | multimodal: True
6b. bad image: ValueError - Invalid remote URL format: receipt.png-does-not-exist. URL must start with http:// or https://
7. arena ok with 2 contestants
7b. arena mismatch: All contestants must have the same 'input'.Lines 1 and 2 are the two rules of the class itself: only input is required, and it must be a string. If your app takes structured requests, put the user-visible text in input and the rest in metadata, or serialize the request to JSON yourself and accept that judges will read JSON.
2.3 Which metrics need which fields#
Every built-in metric declares the fields it reads (a class attribute named _required_params). Reading it for the common metrics in 4.3.5:
# required_fields.py: which LLMTestCase fields each built-in metric reads (lesson 10B.2)
import deepeval.metrics as M
NAMES = [
"ExactMatchMetric", "PatternMatchMetric", "JsonCorrectnessMetric",
"AnswerRelevancyMetric", "FaithfulnessMetric", "ContextualPrecisionMetric",
"ContextualRecallMetric", "ContextualRelevancyMetric", "HallucinationMetric",
"SummarizationMetric", "BiasMetric", "ToxicityMetric", "PIILeakageMetric",
"PromptAlignmentMetric", "ToolCorrectnessMetric", "ArgumentCorrectnessMetric",
"TaskCompletionMetric",
]
for name in NAMES:
params = getattr(getattr(M, name), "_required_params", None)
fields = ", ".join(p.value for p in params) if params else "(set per instance)"
print(f"{name:28} {fields}")ExactMatchMetric input, actual_output, expected_output
PatternMatchMetric input, actual_output
JsonCorrectnessMetric input, actual_output
AnswerRelevancyMetric input, actual_output
FaithfulnessMetric input, actual_output, retrieval_context
ContextualPrecisionMetric input, retrieval_context, expected_output
ContextualRecallMetric input, retrieval_context, expected_output
ContextualRelevancyMetric input, retrieval_context
HallucinationMetric input, actual_output, context
SummarizationMetric input, actual_output
BiasMetric input, actual_output
ToxicityMetric input, actual_output
PIILeakageMetric input, actual_output
PromptAlignmentMetric input, actual_output
ToolCorrectnessMetric input, tools_called, expected_tools
ArgumentCorrectnessMetric input, tools_called
TaskCompletionMetric input, actual_outputThree things to notice. Contextual Precision and Contextual Recall do not read actual_output at all: they judge the retriever against the reference answer, so they are retrieval metrics, not answer metrics (exactly the split 10A.6 teaches). Summarization reads input as the source document and actual_output as the summary. And G-Eval and the DAG metric read whatever you list in their evaluation_params (10B.3), so a G-Eval that compares against a reference needs expected_output only because you said so. You can run the same loop for any metric name in deepeval.metrics.__all__; 10B.4 has the full catalogue.
When a field is missing, the metric raises MissingTestCaseParamsError with a readable message, for example 'retrieval_context' cannot be None for the 'Faithfulness' metric (reproduced in 4.9, together with the two ways to tolerate it).
2.4 context versus retrieval_context#
The two names look interchangeable and are not:
context |
retrieval_context |
|
|---|---|---|
| Who writes it | You, when you build the dataset | Your retriever, at run time |
| What it means | The facts the answer should be based on (ground truth) | The chunks the app actually used, in rank order |
| Changes between runs? | No | Yes, every time retrieval changes |
| Read by | HallucinationMetric |
Faithfulness and the three Contextual metrics |
evalkit analogue (10A.6) |
the gold passages in a RagCase |
the retrieved list in a StageRun |
Putting retrieved chunks into context makes Hallucination measure agreement with whatever was retrieved; putting gold passages into retrieval_context makes Faithfulness and Contextual Precision score a perfect retriever you do not have. Both mistakes produce plausible numbers, which is what makes them expensive.
retrieval_context items can be plain strings or RetrievedContextData(context=..., source=...). The second form keeps the document id; when serialized (line 3 of the output above) it becomes "source: context", which is also how it is shown to judges, and Contextual Precision groups chunks that share a source. Keep the list in the retriever's rank order: Contextual Precision is a ranking metric (10B.4), and a sorted or shuffled list changes its score.
2.5 ToolCall: recording agent actions#
ToolCall(name, input_parameters=None, output=None, description=None, reasoning=None, type=ToolCallType.FUNCTION) records one tool invocation; type is FUNCTION or MCP. Line 4 of the output shows the rule that matters for scoring: two tool calls are equal when their name, input_parameters and output are equal. description, reasoning and type are ignored, and parameter values are compared exactly ("A-1042" is not "a-1042"). The deterministic ToolCorrectnessMetric builds on that equality, with options that decide whether arguments and order count (3.6). Trajectory metrics, traces and the agent-level picture are 10B.5's; the method is 10A.7's.
2.6 Conversations: ConversationalTestCase and Turn#
Multi-turn interactions use a different class. A Turn has a role that is only "user" or "assistant" (line 5a: a system turn is refused; put the system prompt's intent in chatbot_role instead), a content string, and optional per-turn retrieval_context, tools_called, MCP call lists, metadata, user_id and voice fields (audio, latency_ms, interrupted, provider_transcript).
A ConversationalTestCase has:
| Field | Notes |
|---|---|
turns |
list[Turn], required and must not be empty (line 5b). Plain dicts are converted to Turn (line 5c) and turns are deep-copied |
chatbot_role |
The assistant's intended role; required by RoleAdherenceMetric |
scenario, expected_outcome, user_description |
The situation, the outcome a good conversation reaches, and who the user is; used by conversation metrics and by the simulator (10B.6) |
context |
Ground-truth context for the whole conversation |
name, metadata, comments, tags, flaky, expectations, expected_labels, mcp_servers |
As for LLMTestCase |
multimodal, voice, call_recording_path |
Set automatically from images or audio in turns |
Two rules from evaluate() follow: you cannot mix single-turn and conversational test cases in one call, and single-turn metrics cannot score conversations (and vice versa); 4.10 reproduces both errors and runs a keyless multi-turn metric. The built-in conversation metrics (Knowledge Retention, Role Adherence, Conversation Completeness, Turn Relevancy and the turn-level RAG metrics) are 10B.4's; evaluating memory and multi-agent conversations is 10A.11 and 10A.12.
2.7 Images and other media: MLLMImage#
There is no separate multimodal test-case class any more: multimodal is a flag on LLMTestCase and ConversationalTestCase. You create an MLLMImage from a URL (url="https://..."), a local path (read and base64-encoded at construction, FileNotFoundError if it is missing), or dataBase64 plus mimeType. Its string form is a placeholder such as [DEEPEVAL:IMAGE:<uuid>] registered globally, so you embed images in ordinary f-strings (line 6), and the test case's multimodal flag turns on by itself. A string that is neither an existing path nor an http(s) URL is refused at once (line 6b). Remote URLs are not fetched at construction.
Image metrics need a judge that accepts images, and some judges do not; the multimodal metric catalogue is in 10B.4, and the methodology for judging images is 10A.7, Part 9.
2.8 Pairwise comparisons: ArenaTestCase and Contestant#
For "which of these two answers is better" questions, an ArenaTestCase holds a list of Contestant(name, test_case, hyperparameters=None) entries. It validates on construction that names are unique and that every contestant has the same input and the same expected_output (line 7b: one trailing space in the input is enough to be refused, which is right, because a pairwise judgement is only meaningful on the same question). Arena cases are scored by ArenaGEval and run with deepeval.compare(), which returns win counts per contestant; both are 10B.3's, and pairwise methodology (position bias, swaps, Bradley-Terry) is 10A.4, 2.2.
2.9 Expectations and expected labels (a preview)#
Two newer fields let a test case carry its own pass conditions instead of relying only on metrics:
expectations=Expectations(must=[...], must_not=[...])(4.3.x) lists plain-language conditions such as "Ask the user to confirm the cancellation" and "Claim the subscription has already been cancelled" as a must-not. A judge checks each condition and the case passes only if all pass.evaluate()accepts a list of test cases with no metrics at all as long as the cases carry expectations (DeepEval checks that at least one does; give every case its own). It is DeepEval's closest analogue to a rubric checklist; 10B.3 covers how it is judged.expected_labels={"RefusalClassifier": "refused"}gives classifiers (categorical judges added in 4.2.4) something to pass or fail against; a classifier with no expected label only reports a label. Also 10B.3.
2.10 Building test cases from your app: the adapter pattern#
Because DeepEval scores finished records, every real project has a small adapter that runs the app and fills a test case. Keep it in one function so every field is filled the same way in every suite. This one wraps a stand-in for 07's docs_qa pipeline, so it runs without a key:
# adapter.py: turn one run of your app into a DeepEval test case (lesson 10B.2)
import time
from dataclasses import dataclass, field
from deepeval.test_case import LLMTestCase, RetrievedContextData, ToolCall
@dataclass
class Chunk: # what your retriever returns (06/07 style)
text: str
source: str
@dataclass
class AppResult: # what your app returns for one request
answer: str
chunks: list[Chunk] = field(default_factory=list)
tool_calls: list[dict] = field(default_factory=list)
cost_usd: float | None = None
model: str = "unknown"
prompt_version: str = "unknown"
def fake_docs_qa(question: str) -> AppResult:
"""Stand-in for 07's docs_qa pipeline, so this file runs without a key."""
return AppResult(
answer="Unworn shoes can be returned within 30 days; refunds go to the original card.",
chunks=[Chunk("Unworn shoes can be returned within 30 days of delivery.", "returns.md#shoes"),
Chunk("Refunds are issued to the original payment method.", "refunds.md#method")],
tool_calls=[{"name": "search_docs", "args": {"query": question}}],
cost_usd=0.0004, model="gpt-6-luna", prompt_version="docs-qa-v7",
)
def to_test_case(case_id: str, question: str, expected: str | None, run) -> LLMTestCase:
start = time.perf_counter()
result = run(question) # your app, called by YOUR code
elapsed = time.perf_counter() - start
return LLMTestCase(
name=case_id,
input=question,
actual_output=result.answer,
expected_output=expected,
retrieval_context=[RetrievedContextData(context=c.text, source=c.source)
for c in result.chunks], # keep the retriever's rank order
tools_called=[ToolCall(name=t["name"], input_parameters=t["args"])
for t in result.tool_calls],
completion_time=elapsed,
token_cost=result.cost_usd,
metadata={"model": result.model, "prompt_version": result.prompt_version},
)
tc = to_test_case("returns-001", "Can I return worn shoes?",
"Only unworn shoes can be returned, within 30 days.", fake_docs_qa)
print(tc.name, "|", tc.actual_output)
print("retrieval_context:", tc.model_dump()["retrieval_context"])
print("tools_called:", [(t.name, t.input_parameters) for t in tc.tools_called])
print("metadata:", tc.metadata, "| token_cost:", tc.token_cost,
"| completion_time set:", tc.completion_time is not None)returns-001 | Unworn shoes can be returned within 30 days; refunds go to the original card.
retrieval_context: ['returns.md#shoes: Unworn shoes can be returned within 30 days of delivery.', 'refunds.md#method: Refunds are issued to the original payment method.']
tools_called: [('search_docs', {'query': 'Can I return worn shoes?'})]
metadata: {'model': 'gpt-6-luna', 'prompt_version': 'docs-qa-v7'} | token_cost: 0.0004 | completion_time set: TrueThe design choices are the point, not the code: a stable name per case (so results line up across runs; without it, names are positional), real retrieval in rank order, the model and prompt version in metadata (so a saved result says what produced it), and your app's cost and latency in the fields made for them. For a real pipeline, replace fake_docs_qa with the function from 07 and wrap the loop with the concurrency and retry tools of 03.9 and 03.8. In production code, also catch your app's own exceptions here and record them (for example as a test case whose actual_output is an error marker, with the exception in metadata) rather than silently dropping the case: a dropped case is a case that can never fail.
Part 3: The metric object contract#
3.1 A metric is a stateful object#
Every DeepEval metric is an instance of a class that subclasses BaseMetric (single-turn), BaseConversationalMetric (multi-turn) or BaseArenaMetric (pairwise). You configure it in the constructor, run it on a test case, and read the result from the object:
| Attribute | Meaning |
|---|---|
threshold |
The minimum passing score. Default 0.5 for nearly every metric; 1.0 for ExactMatchMetric, PatternMatchMetric and JsonCorrectnessMetric |
score |
The latest score, 0 to 1 for built-in metrics (None before the first run) |
reason |
The latest written explanation (None if not produced) |
success |
The latest pass or fail (None when the metric has no threshold) |
score_breakdown |
Sub-scores for metrics that combine several (for example Summarization's alignment and coverage) |
error |
The error message if the latest run failed under ignore_errors (4.9) |
verbose_logs |
The intermediate steps (extracted statements, verdicts, steps), filled when verbose_mode=True and recorded in results |
evaluation_model |
The judge's name, for LLM metrics |
evaluation_cost, input_tokens, output_tokens |
Judge cost and tokens, for priced built-in judges only (3.4) |
strict_mode, async_mode, include_reason, verbose_mode, flaky |
The switches in 3.3 |
The word that matters is latest. A metric object holds one result at a time, so running it on a second test case overwrites the first. This run shows the life of an ExactMatchMetric, together with three other rules this part explains:
# metric_contract.py: the life of a DeepEval metric object (lesson 10B.2)
from deepeval.metrics import AnswerRelevancyMetric, BaseMetric, ExactMatchMetric
from deepeval.test_case import LLMTestCase
from fake_judge import FakeJudge
# 1. LLM metrics build their judge in __init__: no model and no key fails at once.
try:
AnswerRelevancyMetric()
except Exception as e:
print("1. construction:", type(e).__name__, "-", e)
# 2. A metric is a stateful object: results live on it after measure().
exact = ExactMatchMetric()
print("2. before:", exact.score, exact.success, exact.reason, "| threshold:", exact.threshold)
exact.measure(LLMTestCase(input="Refund window?", actual_output="30 days.",
expected_output="30 days."))
print(" after case A:", exact.score, exact.success, exact.reason)
exact.measure(LLMTestCase(input="Refund window?", actual_output="Thirty days.",
expected_output="30 days."))
print(" after case B:", exact.score, exact.success, "(case A's result is gone)")
# 3. Pass means score >= threshold, so a score equal to the threshold passes.
class Fixed(BaseMetric):
"""Returns a fixed score; enough to probe the pass rule."""
def __init__(self, value: float, threshold: float | None = 0.5):
self.value, self.threshold = value, threshold
def measure(self, test_case, *args, **kwargs) -> float:
self.score = self.value
self.success = self.is_successful() # the base class's rule
return self.score
async def a_measure(self, test_case, *args, **kwargs) -> float:
return self.measure(test_case)
@property
def __name__(self):
return "Fixed"
tc = LLMTestCase(input="q", actual_output="a")
for value, threshold in [(0.5, 0.5), (0.49, 0.5), (0.9, None)]:
m = Fixed(value, threshold)
m.measure(tc)
print(f"3. score {value} threshold {threshold}: success = {m.success}")
# 4. strict_mode forces threshold 1 and clamps any lower QAG score to 0.
script = {
"Statements": [{"statements": ["Unworn shoes: 30 days.", "Refunds go to the card.",
"Gift cards are final.", "We sell socks too."]}] * 2,
"Verdicts": [{"verdicts": [{"verdict": "yes"}, {"verdict": "yes"},
{"verdict": "yes"}, {"verdict": "no", "reason": "socks are off-topic"}]}] * 2,
"AnswerRelevancyScoreReason": [{"reason": "One statement is off-topic."}] * 2,
}
case = LLMTestCase(input="What is your refund policy for shoes?",
actual_output="Unworn shoes: 30 days. Refunds go to the card. "
"Gift cards are final. We sell socks too.")
for strict in (False, True):
judge = FakeJudge({k: list(v) for k, v in script.items()})
m = AnswerRelevancyMetric(model=judge, strict_mode=strict, async_mode=False)
m.measure(case)
print(f"4. strict_mode={strict}: threshold {m.threshold}, score {m.score}, "
f"success {m.success}, judge calls {len(judge.calls)}")1. construction: DeepEvalError - OpenAI API key is not configured. Set OPENAI_API_KEY in your environment or pass `api_key` to OpenAIModel(...).
2. before: None None None | threshold: 1
after case A: 1.0 True The actual and expected outputs are exact matches.
after case B: 0.0 False (case A's result is gone)
3. score 0.5 threshold 0.5: success = True
3. score 0.49 threshold 0.5: success = False
3. score 0.9 threshold None: success = None
4. strict_mode=False: threshold 0.5, score 0.75, success True, judge calls 3
4. strict_mode=True: threshold 1, score 0, success False, judge calls 3Block 2 is the reason you never read results from a metric object you passed to evaluate(): depending on the mode, that object either was not used at all or holds only the last case's result (4.5). Read EvaluationResult instead. And if you run metrics yourself on many cases, use one metric object per case (3.8).
3.2 Scores, thresholds and the pass rule#
Since 4.2.0, every built-in metric scores from 0 to 1 and higher is better. The pass rule lives in BaseMetric.is_successful() and reads, in 4.3.5:
if threshold is None: success = None (score-only, informational)
elif error is not None: success = False
else: success = score >= threshold (a TypeError, e.g. score None, means False)Block 3 of the output confirms the edges: a score equal to the threshold passes (0.5 against 0.5), 0.49 fails, and a metric with threshold=None reports a score but neither passes nor fails. Three consequences:
- The threshold is a minimum, for every metric. That is new since August 2026 for Bias, Toxicity, Hallucination and Misuse (1.2). Those four now print a
DeprecationWarningonce per process to remind you, and the message says it directly: a threshold of 0.2 that meant "at most 20% violations" should now be 0.8. threshold=Nonemakes a tracking metric. Use it for numbers you want to watch without gating on them (a style score, a length).evaluate()andassert_test()refuse to run unless at least one non-flaky metric has a threshold (4.4), because otherwise nothing could ever fail.- Built-in scores are not always clamped. DeepEval trusts the numbers a judge returns for some metrics: a judge that answers 8 to a field described as 0 to 1 produces a score of 8.0 (observed in the research for
TaskCompletionMetric). Real judges rarely do this, but a broken custom judge can, and any score above 1 is a bug to investigate, not a great result.
What this means for you as an engineer: write thresholds as "pass if at least", check every threshold you copied from a tutorial dated before August 2026, and choose thresholds on evidence. A threshold is a decision about acceptable risk on a measured instrument, which is 10A.8, 1.3's subject; DeepEval's default of 0.5 is a placeholder, not a recommendation.
3.3 The switches every metric shares#
Most built-in metrics accept the same keyword arguments:
| Argument | Default | Effect |
|---|---|---|
threshold |
0.5 (1.0 for the exact-match family) | Minimum passing score; None makes the metric informational |
model |
None (the default judge) |
The judge for LLM metrics: a string, a built-in wrapper, or your own DeepEvalBaseLLM (10B.3) |
include_reason |
True |
QAG metrics write the reason with a separate judge call after scoring; False saves that call (G-Eval has no such switch: it returns score and reason together) |
strict_mode |
False |
Sets threshold to 1 in the constructor and, for verdict-counting (QAG) metrics, turns any score below 1 into 0. Block 4: three of four statements relevant scores 0.75 normally and 0 in strict mode. G-Eval switches to a 0-or-1 prompt instead (10B.3) |
async_mode |
True |
Inside one measure() call, run the metric's independent judge calls concurrently (Faithfulness, for example, extracts truths and claims at the same time). measure() still blocks your code until it finishes |
verbose_mode |
False |
Record (and print) the intermediate steps in verbose_logs |
flaky |
False |
The metric is computed and reported, but its failure never fails the test case (4.4) |
evaluation_template |
the metric's template class | Override the metric's prompts (10B.3) |
Two of these deserve a word on judgement. strict_mode turns a graded score into a hard gate: use it for properties where any violation is a failure (every statement must be supported), and expect it to flake more with an imperfect judge, since one wrong verdict among twenty flips the result. flaky exists because LLM metrics are noisy; it lets a metric you are still calibrating sit in the suite without blocking merges. It is a holding pen, not a fix: a metric that stays flaky for months is a metric nobody trusts, and 10A.8, 2.5 has the real fixes (repeats, paired comparisons, better instruments).
3.4 LLM metrics build their judge at construction#
Block 1 is the error everyone meets first. An LLM metric creates its judge in __init__, so AnswerRelevancyMetric() with no model= argument and no OpenAI key fails on the line that creates it, before any test case exists:
DeepEvalError: OpenAI API key is not configured. Set OPENAI_API_KEY in your environment or pass `api_key` to OpenAIModel(...).Without a model= argument, DeepEval picks a default judge from your configuration (the set-* commands, DEEPEVAL_LLM, or OpenAI with the model DeepEval ships as its default, gpt-5.4 in 4.3.5); 10B.3 explains the full order of that choice. For this lesson, three practical rules:
- Every keyless sample passes
model=withFakeJudge(3.5). - Some deterministic metrics also build a judge.
ToolCorrectnessMetric()andJsonCorrectnessMetric(...)score with plain code, but both create a judge in__init__(Tool Correctness for an optional tool-selection check, JSON Correctness to write the reason when the JSON is invalid). Without a key, both fail at construction exactly like block 1, so they needmodel=too (3.6). - Cost is reported only for built-in judges.
evaluation_costis summed in US dollars for DeepEval's own provider wrappers when the model's price is known or configured; for your own judge class it isNone, and the run summary printstoken cost: None(as in every run in this lesson).
A real judge, for reference. This is illustrative: it needs OPENAI_API_KEY in .env, makes real calls, and was not run.
# real_judge.py: the same metric with a real judge model (illustrative; needs a key)
from deepeval.metrics import AnswerRelevancyMetric
from deepeval.models import OpenAIModel
from deepeval.test_case import LLMTestCase
judge = OpenAIModel(model="gpt-6-luna") # reads OPENAI_API_KEY from the environment
metric = AnswerRelevancyMetric(threshold=0.7, model=judge)
metric.measure(LLMTestCase(input="What is your refund policy for shoes?",
actual_output="Unworn shoes can be returned within 30 days."))
print(metric.score, metric.success, metric.reason, metric.evaluation_cost)1.0 True The score is 1.00 because the answer addresses the refund policy for shoes directly. 0.000413.5 A keyless judge for this lesson#
DeepEval accepts any subclass of DeepEvalBaseLLM as a judge. An LLM metric asks its judge for structured answers: it calls generate(prompt, schema=SomeSchema), where the schema is a Pydantic class such as ReasonScore (G-Eval) or Statements, Verdicts and AnswerRelevancyScoreReason (Answer Relevancy). FakeJudge is a stand-in that returns scripted answers for those schemas and records every prompt it was sent, so the LLM metrics in this lesson run without a model and give the same result every time. It is the one fake judge for the whole DeepEval track: 10B.3 and 10B.4 use this same file, so write it once and keep it with your test helpers.
# fake_judge.py: a keyless, scripted DeepEval judge that records every prompt (lesson 10B.2)
# It never calls a model. When a metric asks for a structured answer (a Pydantic
# schema such as ReasonScore), the judge answers with a dict you scripted for that
# schema's class name. 10B.3 and 10B.4 reuse this file unchanged.
from __future__ import annotations
import json
from typing import Any
from pydantic import BaseModel
from deepeval.models import DeepEvalBaseLLM
Answer = dict[str, Any]
class FakeJudge(DeepEvalBaseLLM):
"""Scripted stand-in for an LLM judge.
script: {schema name: [answer, answer, ...]}, popped in call order.
routes: {schema name: [(needle, answer), ...]}; checked first, the first needle
found in the prompt wins (and can answer any number of times).
as_json: return JSON text instead of a schema object, to exercise DeepEval's
string-parsing path (what most real custom judges return).
name: the model name DeepEval prints and records in results.
calls: every (schema name, prompt) pair DeepEval sent, in order.
"""
def __init__(self, script: dict[str, list[Answer]] | None = None, *,
routes: dict[str, list[tuple[str, Answer]]] | None = None,
as_json: bool = False, name: str = "fake-judge"):
# Copy the lists so one script dict can seed several judges.
self.script = {k: list(v) for k, v in (script or {}).items()}
self.routes = {k: list(v) for k, v in (routes or {}).items()}
self.as_json = as_json
self.calls: list[tuple[str | None, str]] = []
self._name = name
super().__init__(model=name) # calls load_model()
def load_model(self):
return self # nothing to load: no client, no key
def _answer(self, prompt: str, schema: type[BaseModel] | None):
name = schema.__name__ if schema else None
self.calls.append((name, prompt))
data = next((answer for needle, answer in self.routes.get(name or "", [])
if needle in prompt), None)
if data is None:
queue = self.script.get(name or "")
if not queue: # fail loudly: an unscripted call is a bug
raise RuntimeError(f"FakeJudge has no scripted answer for schema {name!r}")
data = queue.pop(0)
if self.as_json or schema is None:
return json.dumps(data)
return schema.model_validate(data)
def generate(self, prompt: str, schema: type[BaseModel] | None = None):
return self._answer(prompt, schema)
async def a_generate(self, prompt: str, schema: type[BaseModel] | None = None):
return self._answer(prompt, schema)
def get_model_name(self) -> str:
return self._name
# Helpers for reading what DeepEval asked.
def schemas(self) -> list[str | None]:
return [name for name, _ in self.calls]
def prompt(self, i: int) -> str:
return self.calls[i][1]Its interface, which the rest of the track relies on:
| Part | What it does | Used in this lesson by |
|---|---|---|
FakeJudge(script=None, *, routes=None, as_json=False, name="fake-judge") |
Builds the judge; everything after script is keyword-only |
every LLM-metric sample |
script={"Schema": [answer, ...]} |
Answers for a schema class name, popped in call order; the lists are copied, so one dictionary can seed several judges | metric_contract.py, configs_and_errors.py, skip_only.py (one case at a time, so order is safe) |
routes={"Schema": [(needle, answer), ...]} |
Checked before script: the first needle found in the prompt answers, as many times as it matches. Answers depend on content, not order, which is what concurrent evaluate() and deepeval test run need |
support_cases.py, test_support.py |
| No answer for a call | Raises RuntimeError("FakeJudge has no scripted answer for schema 'X'"): an unscripted call is a bug in your test, so it fails loudly instead of inventing a verdict |
nonllm.py (FakeJudge() with nothing scripted proves the judge is never called) |
as_json=True |
Returns the answer as JSON text instead of a schema object, which exercises DeepEval's string-parsing path (what most real custom judges return) | 10B.3 |
name |
The model name DeepEval prints ("using fake-judge") and records as evaluation_model |
the outputs of 4.2, 4.3, 5.3 and 6.3 |
calls, schemas(), prompt(i) |
Every (schema name, prompt) pair DeepEval sent, in order; the schema names alone; the i-th prompt |
metric_contract.py and cache_demo.py count calls; 10B.3 prints the prompts |
What DeepEvalBaseLLM requires of any judge (load_model, generate, a_generate, get_model_name), and how to wrap a real provider the same way, is 10B.3, Part 3.
Be clear about what it is for. A fake judge tests the plumbing: that your test cases have the right fields, that metrics, thresholds, runners, caching, results and CI behave as you expect, and that DeepEval's arithmetic does what you think (block 4 proved 3 of 4 is 0.75 and strict mode clamps it). It cannot tell you whether a metric measures anything real, because it decides the verdicts itself. That question needs a real judge and the validation of 10A.5. The same split appeared in 10A.4, 9.5 with FakeCallModel. 10B.3 uses the same FakeJudge (with as_json and the prompt helpers) to print DeepEval's real prompts for every metric it opens up; like this version, it answers only what you scripted.
Not to be confused with evalkit's rag_eval.ScriptedJudge (10A.6) and online.FakeJudge (10A.9): those are plain function-style judge callables for evalkit's own seams, not DeepEvalBaseLLM subclasses, and DeepEval metrics cannot use them.
3.6 The deterministic metrics, and their exact rules#
A handful of DeepEval metrics are plain code. They are fast, free and reproducible, and 10A.3 argued they should carry as much of a suite as possible. Each has an exact rule worth knowing, so this run probes the edges:
# nonllm.py: DeepEval's deterministic metrics, and their exact rules (lesson 10B.2)
from pydantic import BaseModel
from deepeval.metrics import (
ExactMatchMetric, JsonCorrectnessMetric, PatternMatchMetric, ToolCorrectnessMetric,
)
from deepeval.test_case import LLMTestCase, ToolCall, ToolCallParams
from fake_judge import FakeJudge
def run(metric, **fields) -> str:
metric.measure(LLMTestCase(input=fields.pop("input", "q"), **fields))
if isinstance(metric, ToolCorrectnessMetric): # its reason is several lines long
return f"{metric.score}"
return f"{metric.score} ({metric.reason})"
print("ExactMatch: strips whitespace, nothing else")
print(" ' 30 days.\\n' vs '30 days.' ->", run(ExactMatchMetric(), actual_output=" 30 days.\n", expected_output="30 days."))
print(" '30 Days.' vs '30 days.' ->", run(ExactMatchMetric(), actual_output="30 Days.", expected_output="30 days."))
print("PatternMatch: re.fullmatch on the stripped output")
p = r"\d+-\d+ business days\."
print(" '3-5 business days.' ->", run(PatternMatchMetric(pattern=p), actual_output="3-5 business days."))
print(" 'Usually 3-5 business days.' ->", run(PatternMatchMetric(pattern=p), actual_output="Usually 3-5 business days."))
print(" same, pattern wrapped in .* ->", run(PatternMatchMetric(pattern=".*" + p), actual_output="Usually 3-5 business days."))
print(" 'usually...' with ignore_case ->", run(PatternMatchMetric(pattern="Usually.*", ignore_case=True), actual_output="usually 3-5 business days."))
class Triage(BaseModel):
priority: str
category: str
print("JsonCorrectness: Pydantic validation decides the score; the judge only writes the reason")
quiet = FakeJudge() # empty script: any judge call would raise
ok = JsonCorrectnessMetric(expected_schema=Triage, model=quiet, include_reason=False)
print(" valid object ->", run(ok, actual_output='{"priority": "P2", "category": "billing"}'))
bad = JsonCorrectnessMetric(expected_schema=Triage, model=quiet, include_reason=False)
print(" missing key ->", run(bad, actual_output='{"priority": "P2"}'))
fenced = JsonCorrectnessMetric(expected_schema=Triage, model=quiet, include_reason=False)
print(" inside prose ->", run(fenced, actual_output='Here you go: {"priority": "P2", "category": "billing"}'))
print(" threshold/strict defaults:", ok.threshold, ok.strict_mode, "| judge calls:", len(quiet.calls))
print("ToolCorrectness: deterministic by default, but it still builds a judge in __init__")
try:
ToolCorrectnessMetric()
except Exception as e:
print(" ToolCorrectnessMetric() with no key ->", type(e).__name__)
expected = [ToolCall(name="lookup_order", input_parameters={"order_id": "A-1042"}),
ToolCall(name="issue_refund", input_parameters={"order_id": "A-1042"})]
called_extra = [ToolCall(name="lookup_order", input_parameters={"order_id": "A-1042"}),
ToolCall(name="search_faq", input_parameters={"q": "refund"}),
ToolCall(name="issue_refund", input_parameters={"order_id": "A-1042"})]
wrong_args = [ToolCall(name="lookup_order", input_parameters={"order_id": "A-9999"}),
ToolCall(name="issue_refund", input_parameters={"order_id": "A-9999"})]
reversed_ = list(reversed(expected))
for label, called in [("extra search_faq call", called_extra), ("wrong order id", wrong_args),
("reversed order", reversed_)]:
default = run(ToolCorrectnessMetric(model=quiet), tools_called=called, expected_tools=expected)
args = run(ToolCorrectnessMetric(evaluation_params=[ToolCallParams.INPUT_PARAMETERS], model=quiet),
tools_called=called, expected_tools=expected)
exact = run(ToolCorrectnessMetric(should_exact_match=True, model=quiet), tools_called=called, expected_tools=expected)
order = run(ToolCorrectnessMetric(should_consider_ordering=True, model=quiet), tools_called=called, expected_tools=expected)
print(f" {label}:")
print(f" default -> {default}")
print(f" + input params -> {args}")
print(f" should_exact_match -> {exact}")
print(f" consider_ordering -> {order}")
print("judge calls in the whole file:", len(quiet.calls))
m = ToolCorrectnessMetric(model=quiet)
m.measure(LLMTestCase(input="q", tools_called=called_extra, expected_tools=expected))
print("one full reason:", m.reason)ExactMatch: strips whitespace, nothing else
' 30 days.\n' vs '30 days.' -> 1.0 (The actual and expected outputs are exact matches.)
'30 Days.' vs '30 days.' -> 0.0 (The actual and expected outputs are different.)
PatternMatch: re.fullmatch on the stripped output
'3-5 business days.' -> 1.0 (The actual output fully matches the pattern.)
'Usually 3-5 business days.' -> 0.0 (The actual output does not match the pattern.)
same, pattern wrapped in .* -> 1.0 (The actual output fully matches the pattern.)
'usually...' with ignore_case -> 1.0 (The actual output fully matches the pattern.)
JsonCorrectness: Pydantic validation decides the score; the judge only writes the reason
valid object -> 1 (None)
missing key -> 0 (None)
inside prose -> 0 (None)
threshold/strict defaults: 1 True | judge calls: 0
ToolCorrectness: deterministic by default, but it still builds a judge in __init__
ToolCorrectnessMetric() with no key -> DeepEvalError
extra search_faq call:
default -> 1.0
+ input params -> 1.0
should_exact_match -> 0.0
consider_ordering -> 1.0
wrong order id:
default -> 1.0
+ input params -> 0.0
should_exact_match -> 1.0
consider_ordering -> 1.0
reversed order:
default -> 1.0
+ input params -> 1.0
should_exact_match -> 0.0
consider_ordering -> 0.5
judge calls in the whole file: 0
one full reason: [
Tool Calling Reason: All expected tools ['lookup_order', 'issue_refund'] were called (order not considered).
Tool Selection Reason: No available tools were provided to assess tool selection criteria
]The rules, as the run shows them:
| Metric | Exact rule (4.3.5) | Trap | evalkit equivalent (10A.3) |
|---|---|---|---|
ExactMatchMetric() |
expected.strip() == actual.strip(): 1.0 or 0.0; threshold 1 |
Case and punctuation count: "30 Days." fails against "30 days." | between exact_match (no stripping) and normalized_match (case, punctuation, Unicode) |
PatternMatchMetric(pattern, ignore_case=False) |
re.fullmatch of the pattern on the stripped output; threshold 1 |
Full match, not search. A pattern that would find "3-5 business days" inside a sentence scores 0 unless you wrap it in .* |
regex_match uses re.search and ignores case by default: the opposite defaults on both counts |
JsonCorrectnessMetric(expected_schema) |
expected_schema.model_validate_json(actual_output): integer 1 or 0; threshold 1; strict_mode=True by default. A judge is asked to explain only when the JSON is invalid |
JSON inside prose or a code fence scores 0 (no extraction); needs model= without a key |
schema_valid (dict against a JSON Schema) after your own extraction step |
ToolCorrectnessMetric() |
For each expected tool, find an unused called tool with the same name; score = matched / expected | Extra calls are not penalized (the search_faq call costs nothing) and arguments are ignored unless you list ToolCallParams.INPUT_PARAMETERS (or OUTPUT) in evaluation_params; needs model= without a key |
tool_calls_match / tool_call_prf, which can report precision as well as recall |
ToolCorrectnessMetric(should_exact_match=True) |
Same length, same order, same names, else 0 | Still ignores arguments unless evaluation_params lists them ("wrong order id" scores 1.0) |
an exact sequence comparison |
ToolCorrectnessMetric(should_consider_ordering=True) |
Weighted longest common subsequence of names / number expected | Reversing two calls halves the score | 10A.7's trajectory alignment modes |
ToolCorrectnessMetric(available_tools=[...]) |
Adds an LLM "tool selection" score and returns the minimum of the two | No longer deterministic | 10B.5 |
Two community metrics are also rule-based and need no judge: ToolPermissionMetric(allowed_tools, denied_tools) and AgentLoopDetectionMetric(...) (10B.5). For anything richer (numbers with units, dates, sets, overlap scores), DeepEval has no built-in metric; write your own (3.7) or run evalkit's graders inside DeepEval (8.3).
3.7 Writing your own metric#
A custom metric is the cheapest way to put a product rule into a suite, and DeepEval's contract is small. Two metrics for the support assistant, used in the rest of the lesson:
# support_metrics.py: two small custom metrics for the support assistant (lesson 10B.2)
import re
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
class LengthMetric(BaseMetric):
"""Pass when the answer fits the chat widget: at most max_chars characters."""
def __init__(self, max_chars: int = 60, threshold: float = 1.0):
self.max_chars = max_chars
self.threshold = threshold # without this, success is always None
def measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
n = len(test_case.actual_output or "")
self.score = 1.0 if n <= self.max_chars else 0.0
self.reason = f"{n} chars (limit {self.max_chars})"
self.success = self.is_successful()
return self.score
async def a_measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
return self.measure(test_case, *args, **kwargs) # nothing to await
@property
def __name__(self):
return "Length"
class NoInternalLinksMetric(BaseMetric):
"""Fail when the answer leaks an internal URL (partial credit is meaningless here)."""
INTERNAL = re.compile(r"https?://[\w.-]*\.(?:corp|internal)\b", re.IGNORECASE)
def __init__(self, threshold: float = 1.0):
self.threshold = threshold
def measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
hits = self.INTERNAL.findall(test_case.actual_output or "")
self.score = 0.0 if hits else 1.0
self.reason = f"internal links: {hits}" if hits else "no internal links"
self.success = self.is_successful()
return self.score
async def a_measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
return self.measure(test_case, *args, **kwargs)
@property
def __name__(self):
return "No Internal Links"What these two metrics rely on, in brief (the full contract, with the places where the custom-metric docs are wrong, including a constructor example that is a SyntaxError if copied, is 10B.3, 6.1):
- Subclass
BaseMetric(orBaseConversationalMetricfor conversations, as in 4.10) and implementmeasure()anda_measure(); with nothing to await,a_measurereturnsself.measure(...). - Set
self.score,self.reasonandself.successinmeasure()and return the score; the inheritedself.is_successful()applies the pass rule of 3.2. - Set
self.thresholdin__init__. The base class default isNone, which makes the metric informational: it never passes or fails, and a suite of only such metrics is refused (4.4). - Name it with a
__name__property: the name appears in tables and results, and it is part of the cache key (6.1). - Store every constructor argument under an attribute of the same name (
self.max_chars = max_chars, notself.limit = max_chars). This rule is not in the docs, and breaking it is a silent bug: in their default async mode,evaluate()andassert_test()rebuild your metric from those attributes for every test case, as 4.5 reproduces. This lesson owns that rule; the rest of the contract is 10B.3's.
A custom metric can also call other metrics inside measure() (the docs call this a composite metric, for example combining Answer Relevancy and Faithfulness into one gate), or call a judge itself; LLM-based custom metrics, G-Eval and the DAG metric are 10B.3's.
3.8 measure() and a_measure() on their own#
You do not need a runner to use a metric. metric.measure(test_case) scores one case and returns the score; await metric.a_measure(test_case) is the same as a coroutine, so you can score many cases concurrently with asyncio.gather:
# custom_metric.py: measure() one case, then a_measure() many cases concurrently (lesson 10B.2)
import asyncio
from deepeval.test_case import LLMTestCase
from support_metrics import LengthMetric, NoInternalLinksMetric
wordy = LLMTestCase(input="Refund window?",
actual_output="Our generous refund window is thirty days from delivery, "
"no questions asked, always.")
m = LengthMetric(max_chars=60)
m.measure(wordy)
print("measure():", m.score, m.success, m.reason)
cases = [
LLMTestCase(input="Refund window?", actual_output="30 days from delivery."),
LLMTestCase(input="Where is my order?",
actual_output="Check https://tracking.acme.internal/A-1042 for status."),
wordy,
]
async def score_all() -> None:
# One metric object per (case, metric): a metric holds only its latest result.
pairs = [(tc, metric) for tc in cases
for metric in (LengthMetric(max_chars=60), NoInternalLinksMetric())]
await asyncio.gather(*(metric.a_measure(tc) for tc, metric in pairs))
for tc, metric in pairs:
print(f" {tc.input[:18]:18} {metric.__name__:18} {metric.score} {metric.reason}")
print("a_measure() with asyncio.gather:")
asyncio.run(score_all())measure(): 0.0 False 84 chars (limit 60)
a_measure() with asyncio.gather:
Refund window? Length 1.0 22 chars (limit 60)
Refund window? No Internal Links 1.0 no internal links
Where is my order? Length 1.0 55 chars (limit 60)
Where is my order? No Internal Links 0.0 internal links: ['https://tracking.acme.internal']
Refund window? Length 0.0 84 chars (limit 60)
Refund window? No Internal Links 1.0 no internal linksWhen to use the standalone form: in a notebook while you design a metric, inside your own harness (for example as a scorer in evalkit or an Inspect scorer, which 10B.17 shows), or in a production guardrail that scores a live answer. What you give up: a standalone measure() writes no cache entry, no test run and no results file (an empty folder stayed empty in this lesson's check), so there is nothing to aggregate or compare later unless you store it yourself. In a terminal it also prints a progress line per call; set verbose_mode=True on the metric to see its intermediate steps.
Part 4: evaluate(): scoring a suite in code#
4.1 The signature#
evaluate() scores a list of test cases with a list of metrics and returns everything it found. Its 4.3.5 signature, with the defaults:
evaluate(
test_cases, # list[LLMTestCase] or list[ConversationalTestCase], not mixed
metrics=None, # list of metric objects
classifiers=None, # categorical judges (10B.3)
metric_collection=None, # name of a metric collection stored on Confident AI (uploads cases)
hyperparameters=None, # dict of str/int/float/Prompt recorded with the run
mcp_servers=None, # MCP servers for MCP metrics (10B.5)
identifier=None, # a name for this run
official=False, # mark as the baseline on Confident AI
async_config=AsyncConfig(), # concurrency (4.6)
display_config=DisplayConfig(), # printing and saving (4.7)
cache_config=CacheConfig(), # metric-result cache (4.8, Part 6)
error_config=ErrorConfig(), # missing fields and crashing metrics (4.9)
) -> EvaluationResultWhat happens inside one call:
flowchart TD
start["evaluate(test_cases, metrics, configs)"] --> v["Validate inputs<br/>same case type, metric fits case type,<br/>at least one non-flaky metric with a threshold"]
v --> loop["For each test case<br/>(up to max_concurrent at once)"]
loop --> copy["Rebuild each metric from its __init__ arguments<br/>(async mode)"]
copy --> cache{"use_cache and a matching<br/>cache entry?"}
cache -->|yes| hit["Reuse the stored MetricData"]
cache -->|no| fields{"Required fields present?"}
fields -->|no, default| raise["MissingTestCaseParamsError<br/>stops the run"]
fields -->|"no, skip_on_missing_params"| skip["Metric skipped for this case"]
fields -->|yes| measure["a_measure(test case)"]
measure -->|"exception, ignore_errors"| err["MetricData with error<br/>case fails"]
measure -->|"exception, default"| crash["Exception stops the run"]
measure --> md["MetricData: score, reason, success"]
hit --> verdict
skip --> verdict
err --> verdict
md --> verdict["Case passes only if every non-flaky<br/>metric with a threshold passed"]
verdict --> out["TestResult in EvaluationResult<br/>cache write, .deepeval/.latest_run_full.json,<br/>results folder file if configured"]4.2 A first run, and how to read the report#
The support assistant from 3.7 answered three questions; this file records those answers as test cases and builds a G-Eval correctness metric on the fake judge. G-Eval asks its judge for a score from 0 to 10 and a reason, and DeepEval divides by 10; here the judge finds each case's answer in the prompt and returns that case's scripted score, so the scores do not depend on the order in which concurrent cases reach it. What G-Eval sends a real judge is 10B.3's subject; here it is a black box that returns 0.9, 0.6 and 0.3.
# support_cases.py: the three recorded answers and the fake judge, shared by later samples (lesson 10B.2)
from deepeval.metrics import GEval
from deepeval.test_case import LLMTestCase, SingleTurnParams
from fake_judge import FakeJudge
EXPECTED_REFUND = "Unworn shoes can be returned within 30 days of delivery."
def support_cases() -> list[LLMTestCase]:
return [
LLMTestCase(name="refund-ok", input="How long do I have to return shoes?",
actual_output="30 days from delivery, if unworn.",
expected_output=EXPECTED_REFUND, metadata={"intent": "refunds"}),
LLMTestCase(name="refund-wordy", input="How long do I have to return shoes?",
actual_output="Our generous refund window is thirty days from delivery, "
"no questions asked, always.",
expected_output=EXPECTED_REFUND, metadata={"intent": "refunds"}),
LLMTestCase(name="tracking-leak", input="Where is order A-1042?",
actual_output="Check https://tracking.acme.internal/A-1042 for status.",
expected_output="Order A-1042 shipped on 3 March; tracking is in your account.",
metadata={"intent": "orders"}),
]
def correctness_metric(scores=(9, 6, 3)) -> GEval:
"""G-Eval correctness on the fake judge. The judge finds each case's answer
in the prompt and returns that case's (reason, 0-10 score)."""
needles = ["30 days from delivery, if unworn.", "Our generous refund window",
"tracking.acme.internal"]
reasons = ["Matches the 30-day rule and the unworn condition.",
"Right window, but drops the 'unworn' condition.",
"Does not give the shipping date."]
judge = FakeJudge(routes={"ReasonScore": [
(needle, {"reason": reason, "score": score})
for needle, reason, score in zip(needles, reasons, scores)]})
return GEval(
name="Correctness",
evaluation_steps=["Check the actual output states the same facts as the expected output.",
"Penalize missing conditions or wrong numbers."],
evaluation_params=[SingleTurnParams.ACTUAL_OUTPUT, SingleTurnParams.EXPECTED_OUTPUT],
model=judge,
)# first_eval.py: score three finished support answers with evaluate() (lesson 10B.2)
from deepeval import evaluate
from support_cases import correctness_metric, support_cases
from support_metrics import LengthMetric, NoInternalLinksMetric
result = evaluate(
test_cases=support_cases(), # three answers your app already produced
metrics=[correctness_metric(), # G-Eval on the fake judge (10B.3 opens it up)
LengthMetric(max_chars=60),
NoInternalLinksMetric()],
)✨ You're running DeepEval's latest Correctness [GEval] Metric! (using
fake-judge, strict=False, async_mode=True)...
✨ You're running DeepEval's latest Length Metric! (using None, strict=False,
async_mode=True)...
✨ You're running DeepEval's latest No Internal Links Metric! (using None,
strict=False, async_mode=True)...
╭──────────────────────────────────────────────────────────────────────────────╮
│ 🚀 DeepEval Evaluation Results │
╰──────────────────────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────────────────────╮
│ ✅ refund-ok (Passed 3 metrics) │
╰──────────────────────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────────────────────╮
│ │
│ ❌ refund-wordy │
│ ├── Input: How long do I have to return shoes? │
│ │ Actual Output: Our generous refund window is thirty days from │
│ │ delivery, no questions asked, always. │
│ │ Expected Output: Unworn shoes can be returned within 30 days of │
│ │ delivery. │
│ └── Metrics │
│ Status ┃ Metric ┃ Score ┃ Threshold ┃ Reason │
│ ━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━ │
│ PASS │ Correctness │ 0.60 │ 0.50 │ Right window, but │
│ │ [GEval] │ │ │ drops the 'unworn' │
│ │ │ │ │ condition. │
│ FAIL │ Length │ 0.00 │ 1.00 │ 84 chars (limit │
│ │ │ │ │ 60) │
│ PASS │ No Internal Links │ 1.00 │ 1.00 │ no internal links │
│ │
╰──────────────────────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────────────────────╮
│ │
│ ❌ tracking-leak │
│ ├── Input: Where is order A-1042? │
│ │ Actual Output: Check https://tracking.acme.internal/A-1042 │
│ │ for status. │
│ │ Expected Output: Order A-1042 shipped on 3 March; tracking is │
│ │ in your account. │
│ └── Metrics │
│ Status ┃ Metric ┃ Score ┃ Threshold ┃ Reason │
│ ━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━ │
│ FAIL │ Correctness │ 0.30 │ 0.50 │ Does not give the │
│ │ [GEval] │ │ │ shipping date. │
│ PASS │ Length │ 1.00 │ 1.00 │ 55 chars (limit │
│ │ │ │ │ 60) │
│ FAIL │ No Internal Links │ 0.00 │ 1.00 │ internal links: │
│ │ │ │ │ ['https://trackin… │
│ │
╰──────────────────────────────────────────────────────────────────────────────╯
╭──────────────────────────────────────────────────────────────────────────────╮
│ Aggregate Metrics │
│ │
│ Metric ┃ Average Score ┃ Pass Rate ┃ Total │
│ ━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━ │
│ Correctness [GEval] │ 0.60 │ 66.67% | passed=2 | failed=1 │ 3 │
│ Length │ 0.67 │ 66.67% | passed=2 | failed=1 │ 3 │
│ No Internal Links │ 0.67 │ 66.67% | passed=2 | failed=1 │ 3 │
╰──────────────────────────────────────────────────────────────────────────────╯
⚠ WARNING: No hyperparameters logged.
» Log hyperparameters to attribute prompts and models to your test runs.
================================================================================
✓ Evaluation completed 🎉! (time taken: 0.02s | token cost: None)
» Test Results (3 total tests):
» Pass Rate: 33.33% | Passed: 1 | Failed: 2
===============================================================================
=
» Want to share evals with your team, or a place for your test cases to live? ❤️
🏡
» Run 'deepeval view' to analyze and save testing results on Confident AI.
Read it like an engineer:
- One "You're running..." line per metric, naming the judge (
fake-judgefor G-Eval,Nonefor the code metrics) and the mode. This is where you notice that a metric is on the wrong judge. - Passing cases are folded to one line (
refund-ok (Passed 3 metrics)) and failing cases show their fields and every metric's score, threshold and reason.DisplayConfig(truncate_passing_cases=False)unfolds the passing ones. refund-wordyfailed on length alone. Its correctness passed (0.6 against 0.5) but it is 84 characters against a limit of 60. Without per-metric rows you could not tell a wrong answer from a long one.tracking-leakfailed two metrics for two different reasons: it does not answer the question (correctness 0.3) and it leaks an internal URL. Two separate failures, visible separately, which is what error analysis needs (10A.1, Part 4).- The Aggregate Metrics panel reports, per metric, the mean score and the share of cases that passed that metric: each is 66.67% here.
- "Pass Rate: 33.33%" at the bottom is a different number: the share of test cases that passed every metric (one of three). Quote the one you mean, by name (Part 10.1).
token cost: Nonebecause the judge is not a priced built-in wrapper (3.4).- "No hyperparameters logged" is a reminder to record what produced the run (4.10).
- "Run 'deepeval view'..." is an advertisement for the platform.
deepeval viewuploads your latest run (7.5); do not run it on data that must stay local.
4.3 The result objects#
The console is for humans; code reads the returned EvaluationResult. This file runs the same suite quietly, with hyperparameters and an identifier, and walks the objects:
# read_results.py: what evaluate() returns, and what it leaves alone (lesson 10B.2)
import deepeval
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from support_cases import correctness_metric, support_cases
from support_metrics import LengthMetric, NoInternalLinksMetric
correctness = correctness_metric()
length = LengthMetric(max_chars=60)
result = evaluate(
test_cases=support_cases(),
metrics=[correctness, length, NoInternalLinksMetric()],
hyperparameters={"model": "support-bot-v3", "prompt_version": "faq-2026-11",
"deepeval_version": deepeval.__version__},
identifier="faq-smoke",
display_config=DisplayConfig(print_results=False, show_indicator=False),
)
print(type(result).__name__, "| confident_link:", result.confident_link,
"| test_run_id:", result.test_run_id)
for tr in sorted(result.test_results, key=lambda t: t.index): # list order is not guaranteed
print(f"\n{tr.name}: success={tr.success} index={tr.index} metadata={tr.metadata}")
for md in tr.metrics_data:
print(f" {md.name:20} score={md.score} threshold={md.threshold} "
f"success={md.success} model={md.evaluation_model} cost={md.evaluation_cost}")
print(f" {'':20} reason={md.reason!r}")
print("\nThe metric objects you passed in were copied, not used:")
print(" correctness.score =", correctness.score, "| length.score =", length.score)
# Sequential mode takes a different code path: it uses your objects directly.
from deepeval.evaluate import AsyncConfig # noqa: E402
length = LengthMetric(max_chars=60)
evaluate(test_cases=support_cases(), metrics=[length],
async_config=AsyncConfig(run_async=False),
display_config=DisplayConfig(print_results=False, show_indicator=False))
print("With run_async=False the object is used and keeps the LAST case's result:")
print(" length.score =", length.score, "| length.reason =", length.reason)EvaluationResult | confident_link: None | test_run_id: None
refund-ok: success=True index=0 metadata={'intent': 'refunds'}
Correctness [GEval] score=0.9 threshold=0.5 success=True model=fake-judge cost=None
reason='Matches the 30-day rule and the unworn condition.'
Length score=1.0 threshold=1.0 success=True model=None cost=None
reason='33 chars (limit 60)'
No Internal Links score=1.0 threshold=1.0 success=True model=None cost=None
reason='no internal links'
refund-wordy: success=False index=1 metadata={'intent': 'refunds'}
Correctness [GEval] score=0.6 threshold=0.5 success=True model=fake-judge cost=None
reason="Right window, but drops the 'unworn' condition."
Length score=0.0 threshold=1.0 success=False model=None cost=None
reason='84 chars (limit 60)'
No Internal Links score=1.0 threshold=1.0 success=True model=None cost=None
reason='no internal links'
tracking-leak: success=False index=2 metadata={'intent': 'orders'}
Correctness [GEval] score=0.3 threshold=0.5 success=False model=fake-judge cost=None
reason='Does not give the shipping date.'
Length score=1.0 threshold=1.0 success=True model=None cost=None
reason='55 chars (limit 60)'
No Internal Links score=0.0 threshold=1.0 success=False model=None cost=None
reason="internal links: ['https://tracking.acme.internal']"
The metric objects you passed in were copied, not used:
correctness.score = None | length.score = None
... (second run's summary trimmed)
With run_async=False the object is used and keeps the LAST case's result:
length.score = 1.0 | length.reason = 55 chars (limit 60)The three levels:
| Object | Fields you use | Notes |
|---|---|---|
EvaluationResult (Pydantic) |
test_results, confident_link, test_run_id |
The last two are None unless you are logged in to Confident AI |
TestResult (dataclass) |
name, success, metrics_data, index, conversational, multimodal, input, actual_output, expected_output, context, retrieval_context, turns, metadata, classifications, expectations |
index is the case's position in your input list; the list order is not guaranteed in async mode (a run in 4.9 returned them out of order), so sort by index or look up by name. tags are not carried; metadata is |
MetricData (Pydantic) |
name, score, threshold, success, reason, strict_mode, flaky, error, evaluation_model, evaluation_cost, input_tokens, output_tokens, verbose_logs, expectations_data |
Serialized with camelCase keys in JSON files (strictMode, evaluationModel, verboseLogs) |
Metric names in results are display names: G-Eval appends [GEval] (and the DAG metric [DAG]), so look metrics up by the name you see in the output, not by the class. A custom metric's name is its __name__.
4.4 When a test case passes#
A test case passes when every non-flaky metric that has a threshold passed (plus its expectations and expected classifier labels, if it has any). In the first run, refund-wordy scored 0.6 on correctness and 1.0 on internal links, and still failed, because Length failed. This is the same "a row passes only when every scorer passes" rule as evalkit's 10A.1 Row.passed, which makes reconciliation between the two straightforward (Part 8).
Two refinements, both reproduced in the next sample of 4.9: a metric with flaky=True is reported but cannot fail its case, and a metric with threshold=None cannot either. If no metric can fail, evaluate() refuses to start: "You must provide at least one non-flaky metric with a 'threshold', otherwise test cases can never pass or fail."
4.5 The runners rebuild your metrics: the copy rule#
The last two lines of the previous output show something the documentation does not explain: in the default (async) mode, the metric objects you pass to evaluate() are not used. For every test case, evaluate() builds fresh metrics, so concurrent cases cannot overwrite each other's scores. In sequential mode (AsyncConfig(run_async=False)) it uses your objects one case after another, so they end holding the last case's result. Either way, results belong in EvaluationResult.
assert_test() follows the same rule. Its default run_async=True copies your metrics and run_async=False does not, and deepeval test run calls it in the default mode, so under the CI runner your custom metrics are always copies. A custom metric that behaves in a notebook (measure()) or in a sequential evaluate() and misbehaves only in CI is the first thing to check against this section.
How the fresh copy is built matters for every custom metric. Reading copy_metrics() in 4.3.5: DeepEval collects the parameter names of your class's __init__ (and its base classes'), looks for instance attributes with exactly those names, and calls your constructor again with them. An argument you stored under a different name is simply not passed, so the copy gets the default. This run shows the result with a metric that stores max_chars as self.limit:
# copy_pitfall.py: the runners rebuild your metric from its __init__ arguments (lesson 10B.2)
from deepeval import assert_test, evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
class RenamedLengthMetric(BaseMetric):
"""Same as LengthMetric, but stores max_chars under a different attribute name."""
def __init__(self, max_chars: int = 60, threshold: float = 1.0):
self.limit = max_chars # the bug: not self.max_chars
self.threshold = threshold
def measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
n = len(test_case.actual_output or "")
self.score = 1.0 if n <= self.limit else 0.0
self.reason = f"{n} chars (limit {self.limit})"
self.success = self.is_successful()
return self.score
async def a_measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
return self.measure(test_case, *args, **kwargs)
@property
def __name__(self):
return "Length"
wordy = LLMTestCase(input="Refund window?",
actual_output="Our generous refund window is thirty days from delivery, "
"no questions asked, always.")
QUIET = DisplayConfig(print_results=False, show_indicator=False)
for run_async in (True, False):
r = evaluate([wordy], [RenamedLengthMetric(max_chars=100)],
async_config=AsyncConfig(run_async=run_async), display_config=QUIET)
m = r.test_results[0].metrics_data[0]
print(f"run_async={run_async!s:5}: asked for limit 100 -> score {m.score}, reason {m.reason!r}")
# assert_test() follows the same rule: run_async=True (its default) copies, False does not.
for run_async in (True, False):
try:
assert_test(wordy, [RenamedLengthMetric(max_chars=100)], run_async=run_async)
print(f"assert_test(run_async={run_async!s:5}): passed")
except AssertionError as e:
reason = str(e).split("reason: ")[1].removesuffix(") failed.")
print(f"assert_test(run_async={run_async!s:5}): AssertionError, reason {reason!r}")run_async=True : asked for limit 100 -> score 0.0, reason '84 chars (limit 60)'
run_async=False: asked for limit 100 -> score 1.0, reason '84 chars (limit 100)'
assert_test(run_async=True ): AssertionError, reason '84 chars (limit 60)'
assert_test(run_async=False): passedThe same metric gives two different answers depending on a concurrency setting, in both runners, and in the default mode the limit you asked for is silently ignored: no warning, no error, a plausible result. The fix is rule 6 of 3.7: store every constructor argument under its own name (self.max_chars = max_chars). Two related consequences:
- State that does not come from
__init__is lost in the copy. A metric that loads a lookup table in__init__from an argument is fine (the argument is passed again, and the table is loaded again for every case, which can be slow); a metric whose attributes you set after construction (metric.allowed = {...}) loses them. - Built-in LLM metrics are rebuilt too, with their judge object passed along, so a judge you gave them is shared by all copies. That is why
FakeJudgehere finds answers by content (routes) rather than by call order.
4.6 AsyncConfig: concurrency and order#
from deepeval.evaluate import AsyncConfig
AsyncConfig(run_async=True, throttle_value=0, max_concurrent=20) # the defaults| Field | Default | Effect |
|---|---|---|
run_async |
True |
Score test cases concurrently. False scores them one at a time, in order, on your metric objects (4.5) |
max_concurrent |
20 | How many test cases are in flight at once (validated: at least 1). Each LLM metric may make several judge calls per case, so 20 cases can mean 60 or more concurrent requests |
throttle_value |
0 | Seconds to wait between starting test cases (validated: at least 0; the docs call it an integer, but it is a float) |
Choose max_concurrent from your judge provider's rate limit, not from your patience: rate-limit errors surface as metric errors (4.9), and DeepEval's own retries (Tenacity, tuned with the DEEPEVAL_RETRY_* variables in 7.4) cannot fix a limit you exceed on purpose. The engineering of rate limits and backoff is 03.8's. assert_test() uses max_concurrent=100 internally but scores one case per call.
evaluate() also works in a notebook or inside another event loop (checked: called from inside asyncio.run(main()), it returned normally). When DeepEval finds a running loop it calls nest_asyncio.apply(), a global patch that lets loops nest, and the same helper is where the "There is no current event loop" DeprecationWarning of 5.6 comes from. In async application code, prefer a_measure() with asyncio.gather (3.8) to relying on that patch.
4.7 DisplayConfig: what is printed and saved#
from deepeval.evaluate import DisplayConfig
from deepeval.test_run.test_run import TestRunResultDisplay
DisplayConfig(
show_indicator=True, # progress bar while scoring
print_results=True, # the per-case panels and tables
verbose_mode=None, # True/False overrides every metric's verbose_mode
display_option=TestRunResultDisplay.ALL, # or FAILING / PASSING
results_folder=None, # save test_run_<timestamp>.json here (6.4)
results_subfolder=None, # optional subfolder inside it
truncate_passing_cases=True, # fold passing cases to one line
inspect_after_run=True, # offer the trace viewer (only for traced runs in a terminal)
file_type=None, file_output_dir=None, # deprecated per-result .md/.html export
)inspect_after_run only prompts when all of these hold: the run has traces, the output is a terminal, a run file was saved, and DEEPEVAL_NO_INSPECT_PROMPT is not set. Plain metric runs like the ones in this lesson never prompt; set DEEPEVAL_NO_INSPECT_PROMPT=1 in CI anyway.
4.8 CacheConfig (preview of Part 6)#
from deepeval.evaluate import CacheConfig
CacheConfig(write_cache=True, use_cache=False) # the defaultsBy default evaluate() writes every metric result to .deepeval/.deepeval-cache.json but does not read it. use_cache=True reuses stored results for identical test cases and metric configurations, skipping the judge entirely. Part 6 shows exactly what "identical" means, and the trap.
4.9 ErrorConfig: missing fields and crashing metrics#
from deepeval.evaluate import ErrorConfig
ErrorConfig(ignore_errors=False, skip_on_missing_params=False) # the defaultsReal suites have incomplete test cases and judges that time out. This run reproduces each policy, plus the config checks from 4.6 and 4.7 and the pass-rule edges from 4.4:
# configs_and_errors.py: evaluate()'s config objects and its error policies (lesson 10B.2)
from deepeval import evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig, ErrorConfig
from deepeval.metrics import ExactMatchMetric, FaithfulnessMetric
from deepeval.test_case import ConversationalTestCase, LLMTestCase, Turn
from deepeval.test_run.test_run import TestRunResultDisplay
from fake_judge import FakeJudge
from support_cases import correctness_metric
QUIET = DisplayConfig(print_results=False, show_indicator=False)
def show(label, result):
for t in result.test_results:
print(f" {label}: {t.name} success={t.success} ->",
[(m.name, m.score, m.success, (m.error or "")[:40]) for m in t.metrics_data])
print("1. The docs' DisplayConfig(display=...) is not the real field name")
try:
DisplayConfig(display="failing")
except TypeError as e:
print(" ", e)
print(" real field:", DisplayConfig(display_option=TestRunResultDisplay.FAILING).display_option)
print("2. AsyncConfig validates its numbers")
for kwargs in ({"max_concurrent": 0}, {"throttle_value": -1}):
try:
AsyncConfig(**kwargs)
except ValueError as e:
print(" ", kwargs, "->", e)
ok = LLMTestCase(name="has-fields", input="Return window?", actual_output="30 days.",
expected_output="30 days.", retrieval_context=["Returns: 30 days."])
missing = LLMTestCase(name="no-context", input="Return window?", actual_output="30 days.",
expected_output="30 days.") # no retrieval_context
print("3. Default policy: a missing field aborts the whole run")
try:
evaluate([ok, missing], [ExactMatchMetric(), FaithfulnessMetric(model=FakeJudge())],
display_config=QUIET)
except Exception as e:
print(" ", type(e).__name__, "-", e)
print("4. skip_on_missing_params=True: the metric is skipped for that case")
faith_script = {"Truths": [{"truths": ["Returns are accepted within 30 days."]}],
"Claims": [{"claims": ["Returns are accepted within 30 days."]}],
"Verdicts": [{"verdicts": [{"verdict": "yes"}]}],
"FaithfulnessScoreReason": [{"reason": "The claim is supported."}]}
r = evaluate([ok, missing], [ExactMatchMetric(), FaithfulnessMetric(model=FakeJudge(faith_script))],
display_config=DisplayConfig(show_indicator=False, print_results=False),
error_config=ErrorConfig(skip_on_missing_params=True))
show("skip", r)
class BrokenJudge(FakeJudge):
def _answer(self, prompt, schema):
raise RuntimeError("provider down")
print("5. ignore_errors=True: the error is recorded, the case FAILS, the run continues")
from deepeval.metrics import GEval # noqa: E402
from deepeval.test_case import SingleTurnParams # noqa: E402
broken = GEval(name="Correctness", evaluation_steps=["Compare facts."],
evaluation_params=[SingleTurnParams.ACTUAL_OUTPUT], model=BrokenJudge())
r = evaluate([ok], [ExactMatchMetric(), broken], display_config=QUIET,
error_config=ErrorConfig(ignore_errors=True))
show("ignore", r)
print("6. A flaky metric is reported but cannot fail the case")
wrong = LLMTestCase(name="refund-wordy", input="How long do I have to return shoes?",
actual_output="Our generous refund window is thirty days from delivery, "
"no questions asked, always.",
expected_output="Unworn shoes can be returned within 30 days of delivery.")
r = evaluate([wrong], [correctness_metric(), ExactMatchMetric(flaky=True)], display_config=QUIET)
show("flaky", r)
print("7. ...but there must be at least one non-flaky metric with a threshold")
try:
evaluate([ok], [ExactMatchMetric(flaky=True)], display_config=QUIET)
except Exception as e:
print(" ", type(e).__name__, "-", e)
print("8. Single-turn metrics cannot score conversations")
convo = ConversationalTestCase(turns=[Turn(role="user", content="Hi"),
Turn(role="assistant", content="Hello!")])
try:
evaluate([convo], [ExactMatchMetric()], display_config=QUIET)
except Exception as e:
print(" ", type(e).__name__, "-", e)1. The docs' DisplayConfig(display=...) is not the real field name
DisplayConfig.__init__() got an unexpected keyword argument 'display'
real field: TestRunResultDisplay.FAILING
2. AsyncConfig validates its numbers
{'max_concurrent': 0} -> 'max_concurrent' must be at least 1
{'throttle_value': -1} -> 'throttle_value' must be at least 0
3. Default policy: a missing field aborts the whole run
MissingTestCaseParamsError - 'retrieval_context' cannot be None for the 'Faithfulness' metric
4. skip_on_missing_params=True: the metric is skipped for that case
skip: no-context success=True -> [('Exact Match', 1.0, True, '')]
skip: has-fields success=True -> [('Exact Match', 1.0, True, ''), ('Faithfulness', 1.0, True, '')]
5. ignore_errors=True: the error is recorded, the case FAILS, the run continues
ignore: has-fields success=False -> [('Exact Match', 1.0, True, ''), ('Correctness [GEval]', None, False, 'provider down')]
6. A flaky metric is reported but cannot fail the case
flaky: refund-wordy success=True -> [('Correctness [GEval]', 0.6, True, ''), ('Exact Match', 0.0, False, '')]
7. ...but there must be at least one non-flaky metric with a threshold
ValueError - You must provide at least one non-flaky metric with a 'threshold', otherwise test cases can never pass or fail.
8. Single-turn metrics cannot score conversations
<class 'deepeval.metrics.exact_match.exact_match.ExactMatchMetric'>
ValueError - Metric Exact Match is not a valid metric for ConversationalTestCase.What each policy does, and when to use it:
| Situation | Default | skip_on_missing_params=True |
ignore_errors=True |
|---|---|---|---|
| A metric's required field is missing (block 3) | MissingTestCaseParamsError; the whole run stops |
That metric is skipped for that case only; the case is judged on its other metrics (block 4) | Not covered: missing fields are not "errors" for this flag. Skip wins when both are set |
| A metric raises (judge down, bad JSON, your bug) | The exception stops the run | Not covered | Recorded as MetricData(score=None, success=False, error="provider down"); the case fails and the run continues (block 5) |
Rules of thumb. Keep the defaults while you build a suite, so mistakes stop you. Turn on skip_on_missing_params only for suites that deliberately mix case shapes (some cases with retrieval context, some without), and count what was skipped. Turn on ignore_errors for long runs against real judges, so one timeout does not throw away an hour of scoring, then treat errored metrics as failures to investigate, not as noise: DeepEval already counts them as failures, which is the honest choice (10A.8, 2.1 on why errors must not leave the denominator silently).
# skip_only.py: a case whose only metric is skipped (lesson 10B.2)
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig, ErrorConfig
from deepeval.metrics import FaithfulnessMetric
from deepeval.test_case import LLMTestCase
from fake_judge import FakeJudge
ok = LLMTestCase(name="has-context", input="Return window?", actual_output="30 days.",
retrieval_context=["Returns: 30 days."])
missing = LLMTestCase(name="no-context", input="Return window?", actual_output="30 days.")
judge = FakeJudge({"Truths": [{"truths": ["Returns are accepted within 30 days."]}],
"Claims": [{"claims": ["Returns are accepted within 30 days."]}],
"Verdicts": [{"verdicts": [{"verdict": "yes"}]}],
"FaithfulnessScoreReason": [{"reason": "The claim is supported."}]})
r = evaluate([ok, missing], [FaithfulnessMetric(model=judge)],
display_config=DisplayConfig(show_indicator=False, print_results=False),
error_config=ErrorConfig(skip_on_missing_params=True))
for t in r.test_results:
print(f"{t.name}: success={t.success} metrics_data={[(m.name, m.score) for m in t.metrics_data]}")» Test Results (1 total tests):
» Pass Rate: 100.0% | Passed: 1 | Failed: 0
no-context: success=True metrics_data=[]
has-context: success=True metrics_data=[('Faithfulness', 1.0)]Two cases went in; the summary says one test, and the case that was never scored says success=True. If you use skip_on_missing_params, count cases with empty metrics_data yourself and report them as "not evaluated".
That wording holds for evaluate() over plain test cases. In a traced run (evals_iterator over an @observe agent, 10B.5) the skipped case is counted as passed, not dropped from the totals: if the golden's expected_output was not copied into the trace, Exact Match is skipped on every case and the run file records them all as passed with empty metricsData (10B.17, 4.7 runs it).
Block 8 also shows a stray line DeepEval 4.3.5 prints itself (the <class ...ExactMatchMetric> line) before raising: harmless, and a reminder that the library is young and fast-moving.
4.10 Hyperparameters, identifiers and conversations#
hyperparameters is a dictionary of strings, numbers or DeepEval Prompt objects that is stored with the run: in the results file, in the SQLite store, and on Confident AI. Use it for everything that produced the outputs (app model, prompt version, retriever settings) and for the evaluator's own version (deepeval.__version__), as read_results.py did. With hyperparameters given, the "No hyperparameters logged" warning changes to "No prompts logged", which refers to Prompt objects (10B.7). identifier names the run ("faq-smoke"), which matters when you keep many runs.
Conversations go through the same evaluate() call, as a list of ConversationalTestCase with conversational metrics. Block 8 above showed the two type rules (a single-turn metric on a conversation is refused). This run scores two support chats with a keyless conversational metric that checks a turn budget:
# conversation_eval.py: a keyless multi-turn metric over ConversationalTestCase (lesson 10B.2)
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseConversationalMetric
from deepeval.test_case import ConversationalTestCase, Turn
class TurnBudgetMetric(BaseConversationalMetric):
"""Pass when the assistant resolves the chat within max_assistant_turns replies."""
def __init__(self, max_assistant_turns: int = 3, threshold: float = 1.0):
self.max_assistant_turns = max_assistant_turns # same name as the argument
self.threshold = threshold
def measure(self, test_case: ConversationalTestCase, *args, **kwargs) -> float:
replies = sum(t.role == "assistant" for t in test_case.turns)
self.score = 1.0 if replies <= self.max_assistant_turns else 0.0
self.reason = f"{replies} assistant turns (budget {self.max_assistant_turns})"
self.success = self.is_successful()
return self.score
async def a_measure(self, test_case: ConversationalTestCase, *args, **kwargs) -> float:
return self.measure(test_case, *args, **kwargs)
@property
def __name__(self):
return "Turn Budget"
quick = ConversationalTestCase(
name="return-quick", chatbot_role="A polite shoe-store assistant",
scenario="Customer wants to return shoes that do not fit",
expected_outcome="Customer learns how to start a return",
turns=[Turn(role="user", content="These shoes don't fit. Can I return them?"),
Turn(role="assistant", content="Yes, within 30 days if unworn. Start at acme.example/returns."),
Turn(role="user", content="Great, thanks!"),
Turn(role="assistant", content="You're welcome!")],
)
loop = ConversationalTestCase(
name="return-loop", chatbot_role="A polite shoe-store assistant",
turns=[Turn(role="user", content="I want to return my shoes.")]
+ [Turn(role=r, content=c) for _ in range(4)
for r, c in [("assistant", "Could you share your order number?"),
("user", "It's A-1042, I already said that.")]],
)
r = evaluate([quick, loop], [TurnBudgetMetric(max_assistant_turns=3)],
display_config=DisplayConfig(print_results=False, show_indicator=False))
for t in sorted(r.test_results, key=lambda t: t.index):
m = t.metrics_data[0]
print(f"{t.name:13} conversational={t.conversational} success={t.success!s:5} "
f"{m.name}={m.score} ({m.reason}) turns stored={len(t.turns)}")return-quick conversational=True success=True Turn Budget=1.0 (2 assistant turns (budget 3)) turns stored=4
return-loop conversational=True success=False Turn Budget=0.0 (4 assistant turns (budget 3)) turns stored=9The custom conversational metric follows the same contract as 3.7, subclassing BaseConversationalMetric; TestResult.conversational is True and turns carries the conversation. The built-in conversation metrics are judge-based (10B.4), and a judge-free check like this one makes a good first gate: a support bot that needs four replies to get an order number has a problem whatever a judge thinks of its tone.
Part 5: pytest: assert_test() and deepeval test run#
5.1 assert_test()#
assert_test() is the pytest-shaped runner: it scores one test case and raises AssertionError if it fails.
assert_test(test_case=None, metrics=None, golden=None, run_async=True, classifiers=None)Inside, it builds the same machinery as evaluate() for a single case, reading its settings from environment variables that deepeval test run sets (verbose output, ignore errors, skip on missing fields, use the cache), and it writes the cache only when run under deepeval test run. It also applies the copy rule of 4.5: with its default run_async=True it scores fresh copies of your metrics. The golden= form without a test case is for traced agents and belongs to 10B.5.
# assert_demo.py: what assert_test() raises, and what a flaky test case does instead (lesson 10B.2)
import warnings
from deepeval import assert_test
from deepeval.test_case import LLMTestCase
from support_metrics import LengthMetric, NoInternalLinksMetric
leaky = LLMTestCase(input="Where is order A-1042?",
actual_output="Our team logged it at https://tracking.acme.internal/A-1042 "
"and it should arrive soon, probably.")
metrics = [LengthMetric(max_chars=60), NoInternalLinksMetric()]
try:
assert_test(leaky, metrics)
except AssertionError as e:
print("AssertionError:", e)
leaky.flaky = True # e.g. a case you know is noisy and are investigating
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert_test(leaky, metrics) # no exception this time
print("flaky case, no exception; warning:",
[str(w.message)[:75] + "..." for w in caught if "Flaky" in str(w.message)])AssertionError: Metrics: Length (score: 0.0, threshold: 1.0, strict: False, error: None, reason: 96 chars (limit 60)), No Internal Links (score: 0.0, threshold: 1.0, strict: False, error: None, reason: internal links: ['https://tracking.acme.internal']) failed.
flaky case, no exception; warning: ['Flaky test case failed (no assertion raised): Metrics: Length (score: 0.0, ...']The message lists every failing metric with its score, threshold, strict flag, error and reason, which is what a CI log needs. A test case marked flaky=True turns the failure into a UserWarning ("Flaky test case failed (no assertion raised): ...") that pytest shows in its warnings summary. assert_test() also requires at least one non-flaky metric with a threshold, exactly like evaluate().
5.2 A test file for the support assistant#
A DeepEval test file is an ordinary pytest file: a stand-in for the app, parametrized cases, one assert_test() per case, and two optional hooks (5.7). The app is three canned answers so the file runs anywhere:
# support_app.py: a stand-in for the system under test (lesson 10B.2)
ANSWERS = {
"How long do I have to return shoes?": "30 days from delivery, if unworn.",
"Do you ship to Canada?": "Yes, we ship to Canada in 5-8 business days.",
"Where is order A-1042?": "Check https://tracking.acme.internal/A-1042 for status.",
}
def answer(question: str) -> str:
return ANSWERS.get(question, "Sorry, I don't know.")# test_support.py: the support assistant's answers as a DeepEval test file (lesson 10B.2)
import deepeval
import pytest
from deepeval import assert_test
from deepeval.metrics import GEval
from deepeval.test_case import LLMTestCase, SingleTurnParams
from fake_judge import FakeJudge
from support_app import answer
from support_metrics import LengthMetric, NoInternalLinksMetric
CASES = [
("How long do I have to return shoes?",
"Unworn shoes can be returned within 30 days of delivery."),
("Do you ship to Canada?", "Yes; delivery to Canada takes 5-8 business days."),
("Where is order A-1042?", "Order A-1042 shipped on 3 March; tracking is in your account."),
]
# Fake judge: one answer per case, found by a phrase from that case's output.
JUDGE = FakeJudge(routes={"ReasonScore": [
("if unworn", {"reason": "Same facts as expected.", "score": 9}),
("5-8 business days", {"reason": "Same facts as expected.", "score": 10}),
("tracking.acme.internal", {"reason": "Does not give the shipping date.", "score": 3}),
]})
@pytest.mark.parametrize("question,expected", CASES)
def test_support_answer(question: str, expected: str):
test_case = LLMTestCase(input=question, actual_output=answer(question),
expected_output=expected)
correctness = GEval(
name="Correctness",
evaluation_steps=["Check the actual output states the same facts as the expected output."],
evaluation_params=[SingleTurnParams.ACTUAL_OUTPUT, SingleTurnParams.EXPECTED_OUTPUT],
model=JUDGE,
)
assert_test(test_case, [correctness, LengthMetric(max_chars=60), NoInternalLinksMetric()])
@deepeval.log_hyperparameters
def hyperparameters():
return {"app": "support-bot", "prompt_version": "faq-2026-11",
"deepeval_version": deepeval.__version__}
@deepeval.on_test_run_end
def after_run():
print("on_test_run_end: archive the results, post to the team channel, ...")# pytest.ini: silences a pytest-asyncio deprecation warning DeepEval's plugin triggers
[pytest]
asyncio_default_fixture_loop_scope = functionKeep fake_judge.py and support_metrics.py in the same folder. The pattern is the same one 10A.8, 5.1 built with evalkit: each case is a pytest test, so pytest's selection (-k), markers and parallelism apply. The metrics are created inside the test function, one set per case, which keeps each case's results separate.
5.3 Running it with deepeval test run#
sequenceDiagram
participant You as You or CI
participant CLI as deepeval test run
participant Py as pytest with the deepeval plugin
participant T as your test function
participant A as assert_test
You->>CLI: deepeval test run tests/ -n 2 -c
CLI->>CLI: set env flags (cache, ignore errors, verbose, identifier)
CLI->>Py: pytest.main(file, -p deepeval, extra args)
loop every collected test
Py->>T: call test (parametrized case)
T->>A: assert_test(test_case, metrics)
A->>A: score the case, add it to the test run
A-->>Py: return, or raise AssertionError
end
Py-->>CLI: pytest return code
CLI->>You: results table, run summary, files in .deepeval/
CLI-->>You: exit with pytest's code (0, 1, 2 or 5)deepeval test run resets DeepEval's run manager, turns its flags into environment variables, calls pytest.main() with the DeepEval plugin and pytest options of its own (colour output, --durations=10, -s, quiet or verbose), then prints DeepEval's results table and summary and exits with pytest's return code. Run keyless, with plain colours, only failing cases in the final table, and one-line tracebacks (absolute paths shortened):
$ deepeval test run test_support.py --color no -d failing -- --tb=line
.
.
FRunning teardown with pytest sessionfinish...
============================================= FAILURES =============================================
E AssertionError: Metrics: Correctness [GEval] (score: 0.3, threshold: 0.5, strict: False, error: None, reason: Does not give the shipping date.), No Internal Links (score: 0.0, threshold: 1.0, strict: False, error: None, reason: internal links: ['https://tracking.acme.internal']) failed.
---------------------------------------- Captured log call -----------------------------------------
INFO deepeval.evaluate.execute.e2e:e2e.py:742 in _a_execute_llm_test_cases
.../site-packages/deepeval/evaluate/evaluate.py:219: AssertionError: Metrics: Correctness [GEval] (score: 0.3, threshold: 0.5, strict: False, error: None, reason: Does not give the shipping date.), No Internal Links (score: 0.0, threshold: 1.0, strict: False, error: None, reason: internal links: ['https://tracking.acme.internal']) failed.
======================================= slowest 10 durations =======================================
0.31s call test_support.py::test_support_answer[How long do I have to return shoes?-Unworn shoes can be returned within 30 days of delivery.]
(8 durations < 0.005s hidden. Use -vv to show these durations.)
===================================== short test summary info ======================================
FAILED test_support.py::test_support_answer[Where is order A-1042?-Order A-1042 shipped on 3 March; tracking is in your account.]
1 failed, 2 passed, 4 warnings in 0.33s
Test Results
┏━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃ ┃ ┃ ┃ Overall Success ┃
┃ Test case ┃ Metric ┃ Score ┃ Status ┃ Rate ┃
┡━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━┩
│ test_support_answer… │ │ │ │ 33.33% | passed=1 | │
│ is order │ │ │ │ failed=2 │
│ A-1042?-Order A-1042 │ │ │ │ │
│ shipped on 3 March; │ │ │ │ │
│ tracking is in your │ │ │ │ │
│ account.] │ │ │ │ │
│ │ Correctness [GEval] │ 0.3 (threshold=0.5, │ FAILED │ │
│ │ │ evaluation │ │ │
│ │ │ model=fake-judge, │ │ │
│ │ │ reason=Does not give │ │ │
│ │ │ the shipping date., │ │ │
│ │ │ error=None) │ │ │
│ │ Length │ 1.0 (threshold=1.0, │ PASSED │ │
│ │ │ evaluation │ │ │
│ │ │ model=n/a, reason=55 │ │ │
│ │ │ chars (limit 60), │ │ │
│ │ │ error=None) │ │ │
│ │ No Internal Links │ 0.0 (threshold=1.0, │ FAILED │ │
│ │ │ evaluation │ │ │
│ │ │ model=n/a, │ │ │
│ │ │ reason=internal │ │ │
│ │ │ links: │ │ │
│ │ │ ['https://tracking.… │ │ │
│ │ │ error=None) │ │ │
│ Note: Use Confident │ │ │ │ │
│ AI with DeepEval to │ │ │ │ │
│ analyze failed test │ │ │ │ │
│ cases for more │ │ │ │ │
│ details │ │ │ │ │
└──────────────────────┴─────────────────────┴──────────────────────┴────────┴─────────────────────┘
⚠ WARNING: No prompts logged.
» Log prompts to evaluate and optimize your prompt templates and models.
================================================================================
✓ Evaluation completed 🎉! (time taken: 0.51s | token cost: None)
» Test Results (3 total tests):
» Pass Rate: 66.67% | Passed: 2 | Failed: 1
================================================================================
» Want to share evals with your team, or a place for your test cases to live? ❤️ 🏡
» Run 'deepeval view' to analyze and save testing results on Confident AI.
on_test_run_end: archive the results, post to the team channel, ...
exit code: 1Three outputs in one: pytest's own report (two dots and an F, the failure with DeepEval's assertion message, the slowest durations, 1 failed, 2 passed), DeepEval's Test Results table (filtered to failing cases by -d failing, with each metric's score, threshold, judge and reason), and the run summary (Pass Rate: 66.67% of test cases). The hook ran last. The exit code is 1 because a test failed, so a CI step running this command goes red without any extra code.
5.4 The flags#
deepeval test run --help in 4.3.5:
| Flag | Effect | Notes |
|---|---|---|
-n, --num-processes N |
Run tests in N processes with pytest-xdist |
Parallelizes test functions; each judge call still happens inside one test. Fine for CPU-bound metrics and for spreading judge calls; watch your provider's rate limit |
-r, --repeat N |
Run every test N times with pytest-repeat |
Turns the cache off, even with -c (the CLI only enables the cache when no repeat is given) |
-c, --use-cache |
Reuse cached metric results (Part 6) | Sets ENABLE_DEEPEVAL_CACHE |
-i, --ignore-errors |
Record metric errors and continue (the ErrorConfig policy of 4.9) |
Errored metrics still fail their test |
-s, --skip-on-missing-params |
Skip metrics whose fields are missing | Same trap as 4.9: count what was skipped |
-v, --verbose |
Every metric's verbose logs, and pytest's --verbose |
|
-id, --identifier NAME |
Name the run | Recorded in the run file |
-d, --display all|failing|passing |
Filter the final table | Default all |
-m, --mark EXPR |
pytest marker expression | For tiers such as eval_smoke (10A.8, 3.1) |
-x, --exit-on-first-failure |
pytest -x |
|
-w, --show-warnings |
Show pytest's warnings summary | Hidden by default (--disable-warnings) |
--durations, --pdb, and the colour option (yes or no) |
Passed through to pytest | The colour option is spelt the American way on the command line, as in the runs below |
-o, --official |
Mark the run as the baseline on Confident AI | Needs a Confident AI key; ignored with a warning otherwise |
-- <pytest args> |
Everything after -- goes to pytest unchanged |
-- -k Canada, -- --tb=line, -- --junitxml=report.xml |
A few of them, run on the same file (output filtered to the summary lines with grep):
$ deepeval test run test_support.py -n 2 -r 2 -id nightly -d failing --color no -- --tb=no
2 failed, 4 passed, 5 warnings in 1.82s
│ test_support_answer… │ │ │ │ 33.33% | passed=1 | │
│ is order │ │ │ │ failed=2 │
│ test_support_answer… │ │ │ │ 33.33% | passed=1 | │
│ is order │ │ │ │ failed=2 │
│ analyze failed test │ │ │ │ │
» Test Results (6 total tests):
» Pass Rate: 66.67% | Passed: 4 | Failed: 2
exit code: 1
$ deepeval test run test_support.py -x --color no -- --tb=no
1 failed, 2 passed, 4 warnings in 0.06s
│ test_support_answer… │ │ │ │ 100.0% | passed=3 | │
│ long do I have to │ │ │ │ failed=0 │
│ test_support_answer… │ │ │ │ 100.0% | passed=3 | │
│ you ship to │ │ │ │ failed=0 │
│ test_support_answer… │ │ │ │ 33.33% | passed=1 | │
│ is order │ │ │ │ failed=2 │
│ analyze failed test │ │ │ │ │
» Test Results (3 total tests):
» Pass Rate: 66.67% | Passed: 2 | Failed: 1
exit code: 1
$ deepeval test run test_support.py -- -k Canada --tb=no
1 passed, 2 deselected, 4 warnings in 0.04s
│ test_support_answer… │ │ │ │ 100.0% | passed=3 | │
│ you ship to │ │ │ │ failed=0 │
│ analyze failed test │ │ │ │ │
» Test Results (1 total tests):
» Pass Rate: 100.0% | Passed: 1 | Failed: 0
exit code: 0
$ deepeval test run test_support.py -- -k nothing_matches
3 deselected, 3 warnings in 0.00s
exit code: 5
$ pytest test_support.py -q --tb=no (plain pytest, no DeepEval runner)
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
===================================== short test summary info ======================================
FAILED test_support.py::test_support_answer[Where is order A-1042?-Order A-1042 shipped on 3 March; tracking is in your account.]
1 failed, 2 passed, 1 warning in 0.01s
exit code: 1-n 2 -r 2ran six tests in two worker processes (three cases twice each); the two repeats of the failing case both failed, so the table lists it twice.-xstops at the first failure; here the failing case happened to be last, so all three ran.-- -k Canadapassed pytest's own selection through: one test ran, two were deselected, exit 0.- No tests selected gives exit code 5, pytest's "no tests collected", and DeepEval prints no table (it prints "No test cases found, please try again.").
- Plain
pytestran the same file and failed the same test with exit code 1, without DeepEval's table and summary (5.6).
5.5 Exit codes, and what CI sees#
deepeval test run exits with pytest's code: 0 all tests passed, 1 at least one test failed (a metric below threshold, a metric error under -i, or any other test failure), 2 interrupted, 5 no tests collected (a selection that matched nothing, or a wrong path). Three practical consequences:
- Exit 5 should fail your CI job. A typo in a
-kexpression or a renamed folder produces exit 5 and no evaluation at all; most CI systems already treat any non-zero code as failure, so do not wrap the command in|| trueto "allow" flaky results. - The exit code knows nothing about thresholds across cases. It fails if any single test fails. "Fail only if the pass rate drops below 90%" or "fail only if worse than the baseline with confidence" are suite-level gates that you compute from the results file (6.6) with 10A.8's
compare.py; 10B.7 builds the full CI pipeline. - A flaky case or flaky metric never fails the job, by design. Track how many there are, or they become a quiet way to switch tests off.
5.6 Plain pytest versus deepeval test run#
The DeepEval plugin is registered as a pytest entry point, so it loads in every pytest session in an environment where DeepEval is installed, including your ordinary unit tests. It stays inert unless the run was started by deepeval test run, but it does print a line at the end of every session. Plain pytest on the support file, keyless (absolute paths shortened):
$ pytest test_support.py -q --tb=line
..F [100%]Running teardown with pytest sessionfinish...
============================================= FAILURES =============================================
E AssertionError: Metrics: Correctness [GEval] (score: 0.3, threshold: 0.5, strict: False, error: None, reason: Does not give the shipping date.), No Internal Links (score: 0.0, threshold: 1.0, strict: False, error: None, reason: internal links: ['https://tracking.acme.internal']) failed.
--------------------------------------- Captured stdout call ---------------------------------------
---------------------------------------- Captured log call -----------------------------------------
INFO deepeval.evaluate.execute.e2e:e2e.py:742 in _a_execute_llm_test_cases
.../site-packages/deepeval/evaluate/evaluate.py:219: AssertionError: Metrics: Correctness [GEval] (score: 0.3, threshold: 0.5, strict: False, error: None, reason: Does not give the shipping date.), No Internal Links (score: 0.0, threshold: 1.0, strict: False, error: None, reason: internal links: ['https://tracking.acme.internal']) failed.
========================================= warnings summary =========================================
test_support.py::test_support_answer[How long do I have to return shoes?-Unworn shoes can be returned within 30 days of delivery.]
.../site-packages/deepeval/utils.py:211: DeprecationWarning: There is no current event loop
loop = asyncio.get_event_loop()
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
===================================== short test summary info ======================================
FAILED test_support.py::test_support_answer[Where is order A-1042?-Order A-1042 shipped on 3 March; tracking is in your account.]
1 failed, 2 passed, 1 warning in 0.02s
exit code: 1assert_test() still works under plain pytest: the failing test fails with the same message, and the exit code is the same. What you lose is everything DeepEval adds around it: no aggregated results table or run summary, no on_test_run_end hook, no cache writes, and no test-run record. Note the "Running teardown with pytest sessionfinish..." line: that is the plugin, loaded even though DeepEval did not start the run. If you see it in an unrelated project, DeepEval is installed in that environment.
Use deepeval test run for eval suites, and keep your fast unit tests in a separate invocation (or a separate environment) so they do not pay for, or get confused by, the eval plugin. To stop the plugin loading in a particular pytest run, pass -p no:deepeval.
If your project runs pytest with filterwarnings = error, read 10B.7, 2.6 first: DeepEval 4.3.6 trips it twice, with a SyntaxWarning in deepeval.red_team and with PytestAssertRewriteWarning under deepeval test run, and two targeted ignore: lines in pytest.ini fix both.
5.7 Hooks: log_hyperparameters and on_test_run_end#
Two decorators attach run-level information and behaviour to a test file, as test_support.py shows:
@deepeval.log_hyperparametersdecorates a function that returns a dictionary of strings, numbers orPromptobjects; DeepEval records it with the run (the pytest equivalent ofevaluate(..., hyperparameters=...)). Record the app's model and prompt version anddeepeval.__version__.@deepeval.on_test_run_enddecorates a function that runs once after the whole run, underdeepeval test runonly (it did not run under plain pytest). Use it to copy the results file somewhere durable or post a summary; keep it short and make it fail loudly if it fails. Two edges, both seen in this lesson's runs: it runs even when no tests were collected (the-- -k nothing_matchesrun printed the hook line after "No test cases found", with exit 5), so a hook that posts a summary should check that the run has test cases; and it did not run with-n 2, because the decorator registers the hook when your test file is imported, and withpytest-xdistthe file is imported only in the worker processes, not in thedeepevalprocess that calls the hook. If you parallelize with-n, do the end-of-run work in a separate CI step that reads the results file.
5.8 Repeats, parallel workers and flaky cases#
What each tool measures, so you pick the right one:
| Tool | What it gives you | What it does not |
|---|---|---|
-r N (repeat) |
N independent scorings of each case, which exposes judge (and, if your test calls the app, app) variance | Statistics: you get N rows, and the cache is off; aggregate them yourself (10A.8, 2.2) |
-n N (xdist) |
Wall-clock speed across test functions | More judge throughput than your provider allows |
flaky=True on a case or metric |
A way to keep noisy checks visible without blocking merges | A fix; nor a record of how often it failed unless you count it |
pytest-rerunfailures (-- --reruns 2) |
A retry on failure | Honesty: a test that passes on the third try passed one time in three |
Part 6: Caching and local results#
Deep-dive
6.1 What the cache stores, and its key#
DeepEval's cache stores metric results, not model calls. The file .deepeval/.deepeval-cache.json maps a test-case key to a list of cached metric results, and each cached result carries the metric configuration it was computed with. A cached result is reused only when both match.
- The test-case key is the JSON of exactly six things:
input,actual_output,expected_output,context,retrieval_contextand the run'shyperparameters. - The metric must match by name and by configuration, where configuration means these fields when the metric has them:
threshold,evaluation_model,strict_mode,include_reason,n,language,embeddings,evaluation_params,assessment_questions,evaluation_steps(orcriteriafor G-Eval),rubric,expected_schema.
Anything else is invisible to the cache. That includes tools_called, expected_tools, metadata and conversation turns on the test-case side, and every parameter of a custom metric that is not in the list above (the source has a comment saying as much: "TODO: Refactor. This won't work well with custom metrics").
6.2 When the cache is read#
Writing is on by default in evaluate() and in deepeval test run. Reading happens only when you ask:
| Runner | Read the cache | Notes |
|---|---|---|
evaluate() |
cache_config=CacheConfig(use_cache=True) |
|
deepeval test run |
-c / --use-cache |
Ignored when -r is given |
assert_test() under plain pytest |
never | It writes only under deepeval test run |
metric.measure() |
never | Standalone runs neither read nor write |
6.3 The stale-cache trap, reproduced#
This run scores the three support answers four times: once to fill the cache, once from the cache, then with a different length limit with and without the cache:
# cache_demo.py: what DeepEval caches, when it reads it, and how it goes stale (lesson 10B.2)
import json
import shutil
from pathlib import Path
from deepeval import evaluate
from deepeval.evaluate import CacheConfig, DisplayConfig
from support_cases import correctness_metric, support_cases
from support_metrics import LengthMetric
shutil.rmtree(".deepeval", ignore_errors=True) # start from an empty cache
QUIET = DisplayConfig(print_results=False, show_indicator=False)
def run(label: str, max_chars: int, use_cache: bool) -> None:
correctness = correctness_metric()
judge = correctness.model
result = evaluate(test_cases=support_cases(), metrics=[correctness, LengthMetric(max_chars)],
cache_config=CacheConfig(use_cache=use_cache), display_config=QUIET)
length = {t.name: next(m for m in t.metrics_data if m.name == "Length")
for t in result.test_results}
wordy = length["refund-wordy"]
print(f"{label:34} judge calls={len(judge.calls)} "
f"refund-wordy Length: score={wordy.score} reason={wordy.reason!r}")
run("1. first run (cache written)", 60, use_cache=False)
run("2. same run, use_cache=True", 60, use_cache=True)
run("3. max_chars=100, use_cache=True", 100, use_cache=True)
run("4. max_chars=100, use_cache=False", 100, use_cache=False)
cache = json.loads(Path(".deepeval/.deepeval-cache.json").read_text())
key, entry = next(iter(cache["test_cases_lookup_map"].items()))
print("\nOne cache key (the test case part):", json.dumps(json.loads(key), indent=None)[:230], "...")
print("Its metric entries:")
for m in entry["cached_metrics_data"]:
print(" ", m["metric_data"]["name"], "| config:", m["metric_configuration"])1. first run (cache written) judge calls=3 refund-wordy Length: score=0.0 reason='84 chars (limit 60)'
2. same run, use_cache=True judge calls=0 refund-wordy Length: score=0.0 reason='84 chars (limit 60)'
3. max_chars=100, use_cache=True judge calls=0 refund-wordy Length: score=0.0 reason='84 chars (limit 60)'
4. max_chars=100, use_cache=False judge calls=3 refund-wordy Length: score=1.0 reason='84 chars (limit 100)'
One cache key (the test case part): {"actual_output": "30 days from delivery, if unworn.", "context": null, "expected_output": "Unworn shoes can be returned within 30 days of delivery.", "hyperparameters": null, "input": "How long do I have to return shoes?", "retri ...
Its metric entries:
Correctness [GEval] | config: {'threshold': 0.5, 'evaluation_model': 'fake-judge', 'strict_mode': False, 'include_reason': False, 'evaluation_steps': ['Check the actual output states the same facts as the expected output.', 'Penalize missing conditions or wrong numbers.'], 'evaluation_params': ['actual_output', 'expected_output']}
Length | config: {'threshold': 1.0, 'strict_mode': False, 'include_reason': False}- Run 2 shows what the cache is for: same cases, same metric configuration, zero judge calls. With a real judge that is the difference between paying for a suite once and paying on every rerun.
- Run 3 is the trap. The limit changed from 60 to 100, the cache did not notice (
max_charsis not part of the Length metric's configuration as the cache sees it), and the 84-character answer still fails, with the old reason "limit 60". Nothing warns you. - Run 4, without the cache, gives the right answer.
- The printed entries show why: Length's configuration is only
threshold,strict_modeandinclude_reason. Correctness carries itsevaluation_steps, so editing a G-Eval step does invalidate it.
Rules that follow:
- Use the cache for reruns of an unchanged suite (re-rendering a report, re-running after an unrelated failure), never across changes to custom metrics.
- Changing a custom metric? Delete
.deepeval/.deepeval-cache.jsonor run without-c. If you must cache, put a version in the metric's name (__name__returns"Length v2"); the name is part of the match. - Caching makes reruns cheap; it does not make a judge deterministic. The first run's verdicts are frozen, whatever their quality. A cached flaky score is still a flaky score, just a repeatable one.
- Your app's outputs are not cached by DeepEval. Record and replay of the system under test is your adapter's job (10A.8, 3.2).
6.4 Saving every run: results_folder and JSON#
The .deepeval/.latest_run_full.json file is overwritten by every run. To keep a history, give a results folder: DisplayConfig(results_folder="results") in code, or the environment variable DEEPEVAL_RESULTS_FOLDER=results, which is the way to save runs from deepeval test run. Each run writes test_run_<YYYYMMDD_HHMMSS>.json (and a .test_run.lock file):
# save_results.py: keep every run as a file you own (lesson 10B.2)
import json
import sys
from pathlib import Path
import deepeval
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from support_cases import correctness_metric, support_cases
from support_metrics import LengthMetric, NoInternalLinksMetric
folder = sys.argv[1] if len(sys.argv) > 1 else "results"
evaluate(
test_cases=support_cases(),
metrics=[correctness_metric(), LengthMetric(max_chars=60), NoInternalLinksMetric()],
hyperparameters={"app": "support-bot", "prompt_version": "faq-2026-11",
"deepeval_version": deepeval.__version__},
identifier="faq-smoke",
display_config=DisplayConfig(print_results=False, show_indicator=False,
results_folder=folder),
)
for path in sorted(Path(folder).iterdir()):
print("saved:", path)Test run saved at results/test_run_20261124_231110.json
saved: results/.test_run.lock
saved: results/test_run_20261124_231110.jsonThe file is plain JSON with camelCase keys, readable without DeepEval:
# run_file_shape.py: what is inside a saved test_run_*.json (lesson 10B.2)
import json
from pathlib import Path
path = max(Path("results").glob("test_run_*.json"))
run = json.loads(path.read_text())
print("top-level keys:", list(run))
case = run["testCases"][0]
print("one test case:", list(case))
print("one metric entry:", list(case["metricsData"][0]))
print("metricsScores[0]:", run["metricsScores"][0])
print("identifier:", run["identifier"], "| testPassed:", run["testPassed"],
"| testFailed:", run["testFailed"])top-level keys: ['testCases', 'conversationalTestCases', 'metricsScores', 'identifier', 'hyperparameters', 'prompts', 'testPassed', 'testFailed', 'runDuration', 'official']
one test case: ['name', 'input', 'actualOutput', 'expectedOutput', 'flaky', 'success', 'metricsData', 'runDuration', 'order', 'metadata']
one metric entry: ['name', 'threshold', 'success', 'score', 'reason', 'strictMode', 'flaky', 'evaluationModel', 'verboseLogs']
metricsScores[0]: {'metric': 'Correctness [GEval]', 'scores': [0.9, 0.6, 0.3], 'passes': 2, 'fails': 1, 'errors': 0}
identifier: faq-smoke | testPassed: 1 | testFailed: 2Each metric entry in metricsData carries name, threshold, success, score, reason, strictMode, flaky, evaluationModel and, for G-Eval, verboseLogs with the evaluation steps and score: everything you need to reconstruct the run without DeepEval installed.
6.5 The SQLite store#
For many runs, DeepEval 4.3.x can store results in SQLite instead: set DEEPEVAL_LOCAL_STORE=sqlite (or run deepeval set-local-store sqlite --save=dotenv). The database deepeval.db goes in the results folder if one is set, otherwise in .deepeval/. The same script, with the store switched:
$ DEEPEVAL_LOCAL_STORE=sqlite python save_results.py results-sql
Test run saved to results-sql/deepeval.db (run id 1)
saved: results-sql/deepeval.db
$ sqlite3 results-sql/deepeval.db ".tables"
metric_data spans test_cases test_runs traces
$ sqlite3 results-sql/deepeval.db "select name, kind, success from test_cases"
refund-ok|single-turn|1
refund-wordy|single-turn|0
tracking-leak|single-turn|0
$ sqlite3 results-sql/deepeval.db "select name, score, success from metric_data limit 3"
Correctness [GEval]|0.9|1
Length|1.0|1
No Internal Links|1.0|1
$ sqlite3 results-sql/deepeval.db "select id, identifier, test_passed, test_failed, hyperparameters_json from test_runs"
1|faq-smoke|1|2|{"app": "support-bot", "prompt_version": "faq-2026-11", "deepeval_version": "4.3.5"}Five tables: test_runs (one row per run, with identifier, pass and fail counts, hyperparameters and the whole payload as JSON), test_cases, metric_data (one row per metric per case, with score, threshold, success, reason, error, judge and cost), and traces and spans for traced runs (10B.5). DEEPEVAL_SQLITE_INCLUDE_ROW_JSON=1 adds the full JSON to every row. SQL over metric_data across runs is the easiest local way to answer "how has Faithfulness moved over the last twenty runs?", which is otherwise a Confident AI feature.
6.6 Reading a saved run back#
DeepEval prints means and pass rates. It does not print intervals, per-slice breakdowns, or a list of failures with reasons in one place, and it has no statistics for comparing runs. All of that is a short script over the results file, with the standard library only:
# report_run.py: read a saved DeepEval run and add what DeepEval does not print (lesson 10B.2)
# Standard library only: the run file is plain JSON, so any tool can read it.
import json
import math
import sys
from collections import defaultdict
from pathlib import Path
def wilson(passed: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""95% Wilson interval for a pass rate (10A.8 explains why not the normal one)."""
if n == 0:
return (0.0, 1.0)
p = passed / n
centre = (p + z * z / (2 * n)) / (1 + z * z / n)
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return (max(0.0, centre - half), min(1.0, centre + half))
folder = Path(sys.argv[1] if len(sys.argv) > 1 else "results")
path = max(folder.glob("test_run_*.json")) # newest by timestamped name
run = json.loads(path.read_text())
cases = run["testCases"]
print(f"run: {path.name} identifier={run['identifier']} hyperparameters={run['hyperparameters']}")
passed = sum(c["success"] for c in cases)
lo, hi = wilson(passed, len(cases))
print(f"case pass rate: {passed}/{len(cases)} = {passed / len(cases):.1%} (95% CI {lo:.1%} to {hi:.1%})")
print("per metric: mean score, pass rate, errors")
for m in run["metricsScores"]:
n = len(m["scores"])
print(f" {m['metric']:20} mean={sum(m['scores']) / n:.3f} "
f"pass={m['passes']}/{n} errors={m['errors']}")
print("by intent (from each case's metadata):")
groups = defaultdict(list)
for c in cases:
groups[(c.get("metadata") or {}).get("intent", "?")].append(c["success"])
for intent, results in sorted(groups.items()):
print(f" intent={intent:8} n={len(results)} pass={sum(results)}/{len(results)}")
print("failures, with every failing metric's reason:")
for c in cases:
if not c["success"]:
why = [f"{m['name']}={m['score']} ({m['reason']})" for m in c["metricsData"] if not m["success"]]
print(f" {c['name']}: " + "; ".join(why))run: test_run_20261124_231110.json identifier=faq-smoke hyperparameters={'app': 'support-bot', 'prompt_version': 'faq-2026-11', 'deepeval_version': '4.3.5'}
case pass rate: 1/3 = 33.3% (95% CI 6.1% to 79.2%)
per metric: mean score, pass rate, errors
Correctness [GEval] mean=0.600 pass=2/3 errors=0
Length mean=0.667 pass=2/3 errors=0
No Internal Links mean=0.667 pass=2/3 errors=0
by intent (from each case's metadata):
intent=orders n=1 pass=0/1
intent=refunds n=2 pass=1/2
failures, with every failing metric's reason:
refund-wordy: Length=0.0 (84 chars (limit 60))
tracking-leak: Correctness [GEval]=0.3 (Does not give the shipping date.); No Internal Links=0.0 (internal links: ['https://tracking.acme.internal'])The interval is the number to notice: one pass in three is consistent with anything from about 6% to 79%. That is the honest statement of what three cases can tell you (Part 10.4). The by intent breakdown uses the metadata you put on each test case in the adapter, which is why 2.10 insisted on it. For comparing two runs case by case (paired bootstrap, permutation tests, minimum detectable effect), feed the per-case results to 10A.8's compare.py, joining on test-case name.
Part 7: The command line and configuration#
Deep-dive
7.1 The command tour#
deepeval --help in 4.3.5 lists these commands:
| Command | What it does | Local and keyless? |
|---|---|---|
test run <file_or_dir> |
Runs pytest with the DeepEval plugin (Part 5) | Yes, with deterministic metrics or a stand-in judge |
diagnose [--json] |
Shows the effective configuration and where each value came from, secrets masked (7.2) | Yes |
settings [-u KEY=VALUE] [-U NAME] [-l [FILTER]] [--save] |
Sets, unsets or lists any setting, with type validation | Yes |
set-<provider> / unset-<provider> |
Chooses the default judge: openai, azure-openai, anthropic, bedrock, gemini, ollama, local-model, grok, moonshot, deepseek, litellm, portkey, openrouter, typesafe, plus embedding, TTS and STT variants (7.3; the judges themselves are 10B.3) |
Setting is local; using the judge needs its key |
set-local-store json|sqlite |
Chooses the local results backend (6.5) | Yes |
set-debug / unset-debug |
Log levels, verbose mode, retry logging, gRPC logging, trace toggles | Yes |
set-mode stable|experimental |
The feature channel (DEEPEVAL_MODE) |
Yes |
set-eval-mode llm|hybrid|system_one |
Who decides inside LLM metrics; the non-default modes use an external paid decision model (10B.3) | Setting yes; using it no |
inspect [path] [--folder] [--run-id] [--list] |
A terminal viewer for saved runs and traces; needs deepeval[inspect] |
Yes, after the extra |
generate |
Synthetic test data (10B.6) | No (calls a model) |
login, logout, set-confident-region |
Confident AI account and data region | No |
view |
Uploads your latest run to Confident AI (asking you to log in first if needed) and opens it (7.5) | No |
gate |
Checks the project against a governance policy on Confident AI; non-zero exit if failing | No |
setup |
Downloads and runs a setup wizard that drives a coding agent (macOS and Linux) | No |
deepeval --version prints the version (4.3.5), and every command has --help.
7.2 deepeval diagnose#
When a run uses the wrong judge, the wrong store or an unexpected setting, run deepeval diagnose first. In the .env demo folder of 1.6, with no key set (one path shortened):
$ deepeval diagnose
DeepEval 4.3.5 · Python 3.13.14
Default models
╭────────────┬─────────────────────────────────────────────────────────────────╮
│ LLM │ ⚠ unusable until fixed: OpenAI API key is not configured. Set │
│ │ OPENAI_API_KEY in your environment or pass `api_key` to │
│ │ OpenAIModel(...). │
│ │ used by metrics, synthesizer, simulator, benchmarks, prompt │
│ │ optimizer │
│ Embeddings │ ⚠ unusable until fixed: OpenAI API key is not configured. Set │
│ │ OPENAI_API_KEY in your environment or pass `api_key` to │
│ │ OpenAIEmbeddingModel(...). │
│ │ used by synthesizer context construction only (override with │
│ │ embedder=... in ContextConstructionConfig) │
│ TTS │ OpenAI — provider default │
│ │ used by voice simulations │
│ STT │ OpenAI — provider default │
│ │ used by voice simulations │
╰────────────┴─────────────────────────────────────────────────────────────────╯
Global defaults: apply whenever a class is constructed without an explicit
model.
Local storage
╭──────────┬───────────────────────────────────────────────────╮
│ Backend │ json (built-in default) │
│ Location │ .deepeval/.latest_run_full.json (latest run only) │
╰──────────┴───────────────────────────────────────────────────╯
Change with `deepeval set-local-store <json|sqlite> --save=dotenv`.
Eval mode
╭──────────────────┬───────────────────────────────────────╮
│ Eval mode │ llm (built-in default) │
╰──────────────────┴───────────────────────────────────────╯
Change with `deepeval set-eval-mode <llm|hybrid|system_one> --save=dotenv`.
No model/Confident settings configured; everything is on built-in defaults.
Where settings can come from (highest precedence first)
╭───┬─────────────────────────────────────┬───────────────╮
│ # │ Source │ Status │
├───┼─────────────────────────────────────┼───────────────┤
│ 1 │ process environment │ always active │
│ 2 │ .env.local │ found │
│ 3 │ .env.staging │ found │
│ 4 │ .env │ found │
│ 5 │ .deepeval/.deepeval (JSON keystore) │ not found │
│ 6 │ built-in defaults │ fallback │
╰───┴─────────────────────────────────────┴───────────────╯
Each variable is resolved independently: the highest-ranked source that
defines it wins (the "winning source" above). Dotenv files are looked up in
/path/to/your/project/envdemo. Login and set-* commands persist to .env.local
(default).
Confident AI
╭────────────────┬─────────────────────────────────────────╮
│ Status │ ○ Not logged in (run `deepeval login`) │
│ Data region │ US (default) │
│ API endpoint │ https://api.confident-ai.com │
│ OTEL endpoint │ https://otel.confident-ai.com/ │
╰────────────────┴─────────────────────────────────────────╯It answers the questions you actually have: whether the default judge is usable (here: no, there is no OpenAI key, so any LLM metric without model= will fail at construction), which local store is active, the eval mode, which configuration files were found, in precedence order (here all three .env files, including .env.staging because APP_ENV=staging), and whether you are logged in to Confident AI and which endpoints it would use. deepeval diagnose --json gives the same as JSON for a CI log.
7.3 The set commands write .env.local#
The set-* commands make no calls; they write settings. With --save=dotenv they write to .env.local (or --save=dotenv:path); without it, non-secret settings go to the legacy JSON keystore .deepeval/.deepeval. Run in an empty folder, keyless:
$ deepeval set-openai --model gpt-6-luna --save=dotenv
Saved environment variables to .env.local (ensure it's git-ignored).
🙌 Congratulations! You're now using OpenAI's `gpt-6-luna` for all evals that require an LLM.
$ cat .env.local
USE_OPENAI_MODEL=1
OPENAI_MODEL_NAME=gpt-6-luna
$ deepeval set-local-store sqlite --save=dotenv
Saved environment variables to .env.local (ensure it's git-ignored).
💾 Test runs will now be saved to deepeval.db (SQLite). Run `deepeval inspect --list` to browse
them.
$ cat .env.local
USE_OPENAI_MODEL=1
OPENAI_MODEL_NAME=gpt-6-luna
DEEPEVAL_LOCAL_STORE=sqlite
$ deepeval unset-openai --save=dotenv
Removed OpenAI environment variables from .env.local.
OpenAI has been unset. No active provider is configured. Set one with the CLI, or add credentials to
.env[.local].
$ cat .env.local
DEEPEVAL_LOCAL_STORE=sqliteset-openai wrote two variables (USE_OPENAI_MODEL=1 and OPENAI_MODEL_NAME); unset-openai removed them and kept the unrelated store setting. For this lesson the point is where they write, because .env.local outranks .env (1.6). Choosing the default judge with these commands, their options (model, base URL, prices for cost tracking, the hidden key prompt) and how DeepEval then picks a judge are 10B.3, 2.5.
7.4 The environment variables worth knowing#
Every setting is an environment variable (the full list is on the environment variables page). The ones this track uses:
| Variable | Default | Meaning |
|---|---|---|
DEEPEVAL_TELEMETRY_OPT_OUT |
unset (telemetry on) | 1 turns telemetry off (1.5) |
DEEPEVAL_DISABLE_DOTENV |
unset | 1 stops import deepeval loading .env files (1.6) |
ENV_DIR_PATH, APP_ENV |
current folder, unset | Where the .env files are, and which .env.<APP_ENV> is read (none when APP_ENV is unset) |
DEEPEVAL_HOME |
~/.deepeval |
Where the anonymous telemetry id is stored |
DEEPEVAL_CACHE_FOLDER |
.deepeval |
Where cache and latest-run files go |
DEEPEVAL_RESULTS_FOLDER |
unset | Save every run as JSON here (the way to do it under deepeval test run) |
DEEPEVAL_LOCAL_STORE |
json |
sqlite for the SQLite store |
DEEPEVAL_FILE_SYSTEM |
unset | READ_ONLY stops DeepEval writing files |
DEEPEVAL_NO_INSPECT_PROMPT |
unset | 1 suppresses the offer to open the trace viewer after a run |
OPENAI_API_KEY, OPENAI_MODEL_NAME, DEEPEVAL_LLM, TEMPERATURE |
unset | The default judge and its settings (10B.3) |
ENABLE_DEEPEVAL_CACHE, IGNORE_DEEPEVAL_ERRORS, SKIP_DEEPEVAL_MISSING_PARAMS, DEEPEVAL_VERBOSE_MODE, DEEPEVAL_IDENTIFIER |
unset | What the test run flags -c, -i, -s, -v, -id set |
DEEPEVAL_RETRY_MAX_ATTEMPTS, DEEPEVAL_RETRY_INITIAL_SECONDS, DEEPEVAL_RETRY_EXP_BASE, DEEPEVAL_RETRY_JITTER, DEEPEVAL_RETRY_CAP_SECONDS |
package defaults | The retry policy for judge calls (Tenacity) |
DEEPEVAL_PER_TASK_TIMEOUT_SECONDS_OVERRIDE, DEEPEVAL_PER_ATTEMPT_TIMEOUT_SECONDS_OVERRIDE, DEEPEVAL_DISABLE_TIMEOUTS |
automatic (an outer budget of 180 s per metric when unset) | Timeouts per metric and per judge call |
DEEPEVAL_UPDATE_WARNING_OPT_IN |
unset | 1 lets import deepeval check PyPI for a newer version |
CONFIDENT_API_KEY, CONFIDENT_REGION |
unset | The platform (10B.7) |
A reasonable CI environment for a DeepEval suite therefore sets DEEPEVAL_TELEMETRY_OPT_OUT=1, DEEPEVAL_NO_INSPECT_PROMPT=1, DEEPEVAL_RESULTS_FOLDER=<an artefact folder>, the judge's key from the CI secret store, and either DEEPEVAL_DISABLE_DOTENV=1 or a clean checkout with no .env.local.
7.5 Commands to keep out of a keyless setup#
Two commands and one evaluate() argument send data to Confident AI, and one command runs downloaded code:
deepeval viewuploads your latest run (inputs, outputs, scores) to Confident AI unless it was already uploaded, then opens it; if you are not logged in, it first opens the login page in your browser and asks for an API key (read fromcli/main.pyandcli/utils.pyin 4.3.5). The end-of-run banner recommends it; do not run it on data that must stay local.deepeval loginstores a platform key in.env.local; afterwards runs are sent to the platform.evaluate(..., metric_collection=...)sends test cases to be scored remotely (4.1).deepeval setupdownloads a wizard binary (checksum-verified) and runs a coding agent against your project. Read what it does before running it.
Nothing else in this lesson touches the network. Telemetry is separate and covered in 1.5.
Part 8: evalkit ↔ DeepEval: the complete mapping#
Reference
8.1 The mapping table#
Everything in this lesson has a counterpart in the evalkit package you built in 10A.1 to 10A.12 (10A.10, Appendix A lists its files). The right-hand column is what to watch when you move between them.
evalkit (lesson) |
DeepEval 4.3.5 | What differs |
|---|---|---|
Example(id, input, reference, metadata) (10A.1 core.py) |
LLMTestCase(name, input, expected_output, metadata, ...) |
DeepEval's case also holds the output (actual_output) and the RAG and tool fields; evalkit keeps outputs in Row |
EvalExample, EvalDataset (10A.2 dataset.py) |
Golden, EvaluationDataset (10B.6) |
Goldens have no output; test cases do |
task function + call_model seam (10A.1) |
nothing: you call your app and fill actual_output (2.10) |
Generation, its retries and its record/replay stay your code, or move to tracing (10B.5) |
Scorer protocol, FunctionScorer (10A.1) |
BaseMetric subclass (3.7) |
A DeepEval metric is a stateful object with a threshold, rebuilt per case from its constructor arguments in the default async mode of evaluate() and assert_test() (4.5) |
Score(name, value, passed, detail) |
metric.score, metric.success, metric.reason; MetricData in results |
DeepEval derives success from score >= threshold; evalkit scorers decide passed themselves |
exact_match (10A.3) |
ExactMatchMetric |
DeepEval strips whitespace; evalkit's compares raw strings |
normalized_match (10A.3) |
none built in | Bridge it (8.3) |
regex_match (10A.3) |
PatternMatchMetric |
re.search and ignore-case by default vs re.fullmatch and case-sensitive by default |
schema_valid (10A.3) |
JsonCorrectnessMetric(expected_schema=PydanticModel) |
Pydantic model vs JSON Schema; no extraction from prose; builds a judge |
tool_calls_match, tool_call_prf (10A.3), trajectory alignment (10A.7) |
ToolCorrectnessMetric and its options (3.6) |
DeepEval's default ignores extra calls and arguments |
rubric_judge, Rubric (10A.4 judges.py) |
GEval (with Rubric), DAGMetric (10B.3) |
DeepEval writes the prompts; you can override them |
pairwise_judge, win_rates, bradley_terry (10A.4) |
ArenaGEval + compare() (10B.3) |
Win counts only; no Elo or Bradley-Terry |
FakeCallModel (10A.4), rag_eval.ScriptedJudge (10A.6), online.FakeJudge (10A.9) |
FakeJudge, a DeepEvalBaseLLM subclass (3.5) |
Same idea (a keyless judge for plumbing tests), different objects: evalkit's are plain callables for its own judge seams, DeepEval's metrics need a DeepEvalBaseLLM |
judge_validation.py (10A.5): kappa, TPR/TNR, bias correction, bootstrap CIs |
nothing | Validate DeepEval's judges with 10A.5's tools (8.4) |
rag_eval.py metrics (10A.6) |
Faithfulness, Answer Relevancy, Contextual Precision, Recall, Relevancy (10B.4) | Same names, different definitions (10A.6, 7.2) |
run_eval(...) → EvalReport (10A.1); run_suite(...) → CaseResult (10A.8 runner.py) |
evaluate(...) → EvaluationResult.test_results |
DeepEval runs no task and has no repeats inside evaluate() |
Row.passed (every scorer passed) |
TestResult.success (every non-flaky metric with a threshold passed) |
Same rule, plus the flaky and threshold=None exceptions |
CallCache, record/replay (10A.8) |
.deepeval/.deepeval-cache.json with -c or CacheConfig(use_cache=True) (Part 6) |
DeepEval caches metric results, not model calls, and its key ignores custom metric parameters |
save_run / load_run (10A.8) |
results_folder JSON, or the SQLite store |
One JSON file per run vs JSONL per row |
repeats=k (10A.1, 10A.8) |
deepeval test run -r k |
Repeats are separate pytest tests; aggregate them yourself |
compare.py: paired bootstrap, permutation tests, evaluate_gate (10A.8) |
nothing locally (run comparison is a Confident AI feature) | Read the results files and use compare.py (6.6) |
pytest gate, tests/test_eval_smoke.py (10A.8, 5.1) |
assert_test() + deepeval test run |
Same shape; DeepEval adds the results table and hooks |
cli.py gate (10A.8) |
deepeval test run exit code |
Per-test pass/fail only; suite-level thresholds are yours |
report slices from metadata (10A.1, 10A.10 report.py) |
nothing built in; TestResult.metadata carries the labels |
Slice in your own report (6.6) |
8.2 Where the defaults differ#
The differences most likely to make an evalkit number and a DeepEval number disagree on the same data:
- Exact match strips whitespace in DeepEval and not in
evalkit; neither ignores case. - Pattern match is a full match and case-sensitive in DeepEval, a search and case-insensitive in
evalkit. Port a pattern by wrapping it in.*...*and addingignore_case=True, and test both on the same strings. - The tool-call metric's default is lenient in DeepEval (extra calls and wrong arguments both pass).
- Pass rule edges: a flaky metric and a
threshold=Nonemetric never fail a DeepEval case;evalkithas no such exceptions. - Errors: with
ignore_errors=True, an errored metric is a failure in DeepEval;evalkit's runners record errors separately inRow.errorandCaseResultstatus, so decide how each counts before comparing pass rates. - Skipped metrics (
skip_on_missing_params) vanish fromevaluate()'s totals (in a traced run the case is counted as passed), and a case with every metric skipped reports success. - Aggregates: DeepEval prints a per-metric mean and pass rate and a per-case pass rate;
evalkitadds per-slice rates and intervals. Recompute from per-case results, never compare a mean with a pass rate.
8.3 Running an evalkit grader inside DeepEval#
You do not have to choose between evalkit's graders and DeepEval's runner. Any function that returns an evalkit-shaped Score becomes a DeepEval metric with a ten-line adapter. This file includes a cut-down normalized_match so it runs on its own; in your project, import the real one from evalkit.scorers:
# evalkit_bridge.py: run any evalkit-style grader as a DeepEval metric (lesson 10B.2)
import re
import unicodedata
from dataclasses import dataclass
from typing import Callable
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseMetric, ExactMatchMetric
from deepeval.test_case import LLMTestCase
@dataclass(frozen=True)
class Score: # the shape of evalkit.core.Score (10A.1)
name: str
value: float
passed: bool
detail: str = ""
def normalized_match(output: str, expected: str) -> Score:
"""A cut-down 10A.3 normalized_match: NFKC, casefold, drop punctuation, squeeze spaces."""
def norm(s: str) -> str:
s = unicodedata.normalize("NFKC", s).casefold()
return " ".join(re.sub(r"[^\w\s]", " ", s).split())
ok = norm(output) == norm(expected)
return Score("normalized_match", float(ok), ok, f"{norm(output)!r} vs {norm(expected)!r}")
class EvalkitMetric(BaseMetric):
"""Adapter: grade(test_case) -> Score becomes a DeepEval metric.
evalkit's `passed` decides success, so the grader keeps its own pass rule.
Store every __init__ argument under its own name: evaluate() rebuilds the
metric from those attributes for each test case (see 4.5)."""
def __init__(self, name: str, grade: Callable[[LLMTestCase], Score], threshold: float = 1.0):
self.name, self.grade, self.threshold = name, grade, threshold
def measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
try:
s = self.grade(test_case)
except Exception as e: # a grader crash is a recorded failure
self.error, self.score, self.success = f"{type(e).__name__}: {e}", None, False
raise
self.score, self.reason, self.success = s.value, s.detail, s.passed
return self.score
async def a_measure(self, test_case: LLMTestCase, *args, **kwargs) -> float:
return self.measure(test_case, *args, **kwargs)
@property
def __name__(self):
return self.name # also the cache key: keep names unique per grader
norm_metric = EvalkitMetric(
"Normalized Match", lambda tc: normalized_match(tc.actual_output, tc.expected_output))
cases = [
LLMTestCase(name="same", input="Refund window?", actual_output="30 days.", expected_output="30 days."),
LLMTestCase(name="case+punct", input="Refund window?", actual_output="30 Days", expected_output="30 days."),
LLMTestCase(name="words", input="Refund window?", actual_output="Thirty days.", expected_output="30 days."),
]
result = evaluate(cases, [ExactMatchMetric(), norm_metric],
display_config=DisplayConfig(print_results=False, show_indicator=False))
for t in sorted(result.test_results, key=lambda t: t.index):
cells = " ".join(f"{m.name}={m.score:.0f}" for m in t.metrics_data)
detail = next(m.reason for m in t.metrics_data if m.name == "Normalized Match")
print(f"{t.name:11} success={t.success!s:5} {cells} [{detail}]")same success=True Exact Match=1 Normalized Match=1 ['30 days' vs '30 days']
case+punct success=False Exact Match=0 Normalized Match=1 ['30 days' vs '30 days']
words success=False Exact Match=0 Normalized Match=0 ['thirty days' vs '30 days']Three design decisions are worth copying. evalkit's passed decides success, so a grader's own pass rule survives the move (DeepEval's score >= threshold would also work here, but not for graders whose pass rule is not a threshold on the value). Every constructor argument is stored under its own name (self.name, self.grade), so the copy rule of 4.5 rebuilds it correctly: the first version of this file stored the name as self._name, and evaluate() failed with TypeError: EvalkitMetric.__init__() missing 1 required positional argument: 'name', which is the loud version of the same bug. The metric's name doubles as its cache key, so two bridged graders must have different names, and changing what a grader does under the same name serves stale cache entries.
The reverse direction (DeepEval metrics as evalkit scorers, or inside an Inspect scorer) is 10B.17's.
8.4 What DeepEval does not do#
None of these are criticisms of the library's purpose; they are the parts of the methodology you keep doing yourself.
| Missing | Why it matters | Where to get it |
|---|---|---|
| Judge validation: no agreement statistics against human labels, no TPR/TNR, no bias-corrected pass rates | Every LLM metric is an instrument with unknown error until you measure it | 10A.5's judge_validation.py, run on DeepEval's per-case verdicts |
| Uncertainty: no confidence intervals on pass rates or means | A 3-case or 30-case pass rate is a wide interval, not a number | 6.6, 10A.8, Part 2 |
| Run comparison and significance locally | "Better than last week" needs paired comparison | compare.py over the results files; or the platform |
| Running your system | Generation, retries, record/replay of the system under test | Your adapter (2.10), or tracing (10B.5) |
| Determinism for LLM metrics | Temperature 0 does not guarantee identical verdicts; extraction steps vary | Repeats, caching, fixed steps (10B.3), and the flaky-gate tools of 10A.8, 2.5 |
| Sandboxed execution of model-written code | Agent and coding evals that run code need isolation | Inspect's sandboxes (10B.15) |
| Dataset versioning locally | Comparing runs on different case sets is meaningless | 10A.2's dataset cards and fingerprints; or the platform |
What this means for you as an engineer: DeepEval makes it easy to produce a number and to gate CI on it. Defending that number (is the judge right, is the difference real, is the dataset the same) is still the method of 10A.1 to 10A.8, applied to DeepEval's outputs. Part 10 shows the first steps.
8.5 What changed since 10A.10's DeepEval entries#
10A.10 and 10A.8, 5.3 list DeepEval at 4.3.3; as of 24 November 2026 it is 4.3.5. Their descriptions (pytest-style, LLMTestCase, assert_test, GEval, RAG metrics, deepeval test run with --num-processes, --repeat, --use-cache and --official, optional Confident AI) are still correct. Two details from earlier lessons are worth correcting while you read them: the pytest integration is started with deepeval test run (the plugin also loads under plain pytest, but DeepEval's table, hooks and cache need its runner, 5.6); and since 4.2.0 every metric scores higher-is-better, so any older threshold on Bias, Toxicity, Hallucination or Misuse must be re-read. 10B.4 corrects the RAG metric entries in 10A.6, Part 7.
8.6 Decision table: which runner for which job#
| You want to... | Use | Why |
|---|---|---|
| Try a metric on one example while designing it | metric.measure(case) in a notebook |
Immediate; nothing written to disk |
| Score a guardrail on live traffic inside your app | await metric.a_measure(case), one metric object per request |
No run records; store what you need yourself |
| Score a suite and analyse the results in code | evaluate() with a results_folder |
Returns objects, saves a file per run |
| Gate pull requests on per-case thresholds | assert_test() in parametrized tests, run with deepeval test run |
Non-zero exit on any failing case; results table in the CI log |
| Gate on a suite-level pass rate or a regression against a baseline | evaluate() or deepeval test run with DEEPEVAL_RESULTS_FOLDER, then your own gate script with 10A.8's statistics |
DeepEval's exit code is per test, not per suite |
| Rerun an unchanged suite cheaply | -c / CacheConfig(use_cache=True) |
Only if nothing about the metrics changed (6.3) |
| Measure judge noise | deepeval test run -r 5, then aggregate per case |
The cache is off with repeats, as it should be |
| Many models, long agent transcripts, sandboxes, statistics in the log | Inspect (10B.8) | Its data model is built for that |
| A tiny, fully auditable harness | evalkit |
You own every line; DeepEval's metric definitions are someone else's |
Part 9: Pitfalls, reproduced#
Deep-dive
9.1 The checklist of first-week traps#
Every item below was reproduced in this lesson's runs (section in brackets) or, where marked, in the research for this track.
- LLM metrics fail at construction without a key, including the deterministic
ToolCorrectnessMetricandJsonCorrectnessMetric, which still build a judge. Passmodel=(3.4). import deepevalloads.env,.env.<APP_ENV>(only whenAPP_ENVis set) and.env.localfrom the working folder;.env.localwins over.env, and the shell wins over both (1.6).set-*andloginwrite keys in plain text to.env.local(7.3);set-ollamawithout--savemis-routes (10B.3, 2.6).DisplayConfig(display=...)from the docs is aTypeError; the field isdisplay_option(4.7).- A custom metric that stores an argument under another name silently uses the default in the async mode of
evaluate()andassert_test(), which is the modedeepeval test runuses (4.5). - Metric objects passed to
evaluate()are not where results live: unused in async mode, overwritten in sequential mode (4.3). test_resultsorder is not guaranteed; sort byindex(4.3).- The cache ignores custom metric parameters and serves stale scores with
-c(6.3);-rsilently turns-coff (5.4). skip_on_missing_paramscan make an unscored case look like a pass and drops it from the totals ofevaluate(); a traced run counts it as passed (4.9).- Errors under
ignore_errorsfail the case, which is right, but means an outage at the judge provider shows up as quality failures unless you readerror(4.9). - The pytest plugin loads in every pytest session in the environment (5.6).
PatternMatchMetricis a full match;ExactMatchMetricis case-sensitive (3.6).- Thresholds from before August 2026 may be inverted for Bias, Toxicity, Hallucination and Misuse (1.2).
deepeval viewuploads your latest run (7.5).token cost: Noneis normal for custom judges; cost tracking needs a priced built-in wrapper (3.4).tagsdo not come back onTestResult; slice bymetadata(2.2).
9.2 The failure gallery#
| Symptom | Likely cause | Fix |
|---|---|---|
DeepEvalError: OpenAI API key is not configured on the line that creates a metric |
No model= and no default judge configured |
Pass model=, or configure a judge and check with deepeval diagnose |
| A colleague's runs use a different judge from yours | A .env.local written by deepeval set-* on their machine |
deepeval diagnose; delete or ignore .env.local; set the judge explicitly in code or CI |
MissingTestCaseParamsError: 'retrieval_context' cannot be None for the 'Faithfulness' metric |
The adapter does not fill the field | Fill it from real retrieval; use skip_on_missing_params only knowingly |
ValueError: You must provide at least one non-flaky metric with a 'threshold' |
Every metric is flaky or has threshold=None, or a custom metric never sets self.threshold |
Set a threshold on at least one metric |
ValueError: Metric Exact Match is not a valid metric for ConversationalTestCase. |
A single-turn metric on conversations | Use conversational metrics, or score each turn as an LLMTestCase |
TypeError: DisplayConfig.__init__() got an unexpected keyword argument 'display' |
Copied from the docs | display_option=TestRunResultDisplay.FAILING |
A custom metric ignores the parameter you passed, only in async evaluate() or under deepeval test run |
Argument stored under another attribute name | self.<argument> = <argument> for every argument |
TypeError: ...__init__() missing 1 required positional argument from copy_metrics |
Same cause, for an argument without a default | Same fix |
| Scores did not change after you edited a custom metric | Cache hit with -c / use_cache=True |
Delete .deepeval/.deepeval-cache.json; version the metric name |
| A run reports 100% but you expected more cases | Cases whose metrics were all skipped vanished from the totals | Count cases with empty metrics_data |
| The CI job is green but no evaluation ran | Exit code 5 swallowed, or ` | |
| A metric scores above 1 | The judge returned an out-of-range number and the metric does not clamp | Fix or replace the judge; assert 0 <= score <= 1 in your report |
| "Running teardown with pytest sessionfinish..." in an unrelated project | DeepEval installed in that environment | Separate environments or -p no:deepeval |
DeprecationWarning: 'LLMTestCaseParams' is deprecated |
Code from an older tutorial | Part 11 |
Part 10: Methodology: defending a DeepEval number#
Deep-dive
DeepEval makes numbers easy to produce. These steps make them defensible. They apply 10A.1, 10A.5 and 10A.8 to DeepEval's outputs; nothing here is new method, only where it plugs in.
10.1 Name the number#
The first run printed four different kinds of number, and they are easy to confuse in a status update:
| Number | Where | Meaning in the first run |
|---|---|---|
| Per-case pass rate | "Pass Rate: 33.33%" in the summary | 1 of 3 cases passed every metric |
| Per-metric pass rate | Aggregate Metrics, "Pass Rate" column | 2 of 3 cases passed Correctness (and likewise each of the others) |
| Per-metric mean score | Aggregate Metrics, "Average Score" | 0.60 for Correctness |
| One case's score | a metric row | 0.6 for refund-wordy on Correctness |
"We're at 67%" could mean any per-metric pass rate; "33%" is the per-case rate. Always say which, name the metric, the threshold, the judge and the DeepEval version, and give the number of cases: "Correctness (G-Eval, threshold 0.5, judge gpt-6-luna, DeepEval 4.3.5) passed 2 of 3 cases." A mean of a thresholded metric is also worth a second look: 0.60 average correctness says nothing about how many answers were acceptable.
10.2 Controls: oracle and null runs#
Before you trust a suite to measure your app, check that it can measure anything: an oracle run (answer with the reference itself) should pass every quality metric, and a null run (a useless answer) should fail them. Here for the two deterministic metrics:
# controls.py: oracle and null runs for the deterministic support metrics (lesson 10B.2)
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.test_case import LLMTestCase
from support_cases import support_cases
from support_metrics import LengthMetric, NoInternalLinksMetric
QUIET = DisplayConfig(print_results=False, show_indicator=False)
real = support_cases()
# Oracle: answer with the reference itself. Every quality metric should score 1.
oracle = [LLMTestCase(name=c.name, input=c.input, actual_output=c.expected_output,
expected_output=c.expected_output) for c in real]
# Null: a useless answer. A metric that still passes it is a guard rail, not a quality measure.
null = [LLMTestCase(name=c.name, input=c.input, actual_output="Sorry, I don't know.",
expected_output=c.expected_output) for c in real]
for label, cases in [("oracle", oracle), ("null", null)]:
r = evaluate(cases, [LengthMetric(max_chars=60), NoInternalLinksMetric()], display_config=QUIET)
print(f"{label}:")
for t in sorted(r.test_results, key=lambda t: t.index):
print(f" {t.name:14} success={t.success!s:5} " +
" ".join(f"{m.name}={m.score} ({m.reason})" for m in t.metrics_data))oracle:
refund-ok success=True Length=1.0 (56 chars (limit 60)) No Internal Links=1.0 (no internal links)
refund-wordy success=True Length=1.0 (56 chars (limit 60)) No Internal Links=1.0 (no internal links)
tracking-leak success=False Length=0.0 (61 chars (limit 60)) No Internal Links=1.0 (no internal links)
null:
refund-ok success=True Length=1.0 (20 chars (limit 60)) No Internal Links=1.0 (no internal links)
refund-wordy success=True Length=1.0 (20 chars (limit 60)) No Internal Links=1.0 (no internal links)
tracking-leak success=True Length=1.0 (20 chars (limit 60)) No Internal Links=1.0 (no internal links)Both controls found something:
- The oracle failed. The reference answer for
tracking-leakis 61 characters, so the Length metric would fail the ideal answer. Either the limit or the reference is wrong; a suite in which a perfect answer cannot pass will be blamed on the model for months. This is a bug in the eval, found before any model was blamed. - The null run passed everything. "Sorry, I don't know." is short and leaks nothing. That is not a bug: Length and No Internal Links are guard rails, not quality measures. The null run tells you that the suite's ability to fail a bad answer rests entirely on the Correctness metric, so that is the metric whose judge you must validate (with 10A.5) before trusting the suite.
Run the same controls for every LLM metric with the real judge: an oracle well below 1 or a null well above 0 is an instrument problem. With the fake judge they show nothing, because the fake judge decides the verdicts (the reason it is for plumbing only, 3.5).
10.3 Read the reasons, not just the scores#
Every metric row carries a reason, and for verdict-based metrics verbose_mode=True records each extracted statement and verdict in verbose_logs (stored in the results file). Read the reasons of every failing case, and of a sample of passing ones, before you act on a score. In the first run, the reasons separated a wrong answer ("Does not give the shipping date") from a style problem ("84 chars (limit 60)"); the scores alone did not. Reading reasons is also how you catch a judge that is wrong in a consistent direction, which is the start of 10A.5's label set.
10.4 Three cases is an anecdote: intervals#
The report script in 6.6 put a 95% Wilson interval on the one-in-three pass rate: 6.1% to 79.2%. With 30 cases and 10 passes the interval would still be roughly 19% to 52%; with 300, roughly 28% to 39%. DeepEval prints none of this. Size suites with 10A.2's guidance, put an interval on every rate you report, and compare runs case by case, joined on test-case name, with 10A.8's paired tests rather than by eyeballing two percentages.
10.5 Record what produced the number#
A DeepEval score depends on the test cases, the app that produced the outputs, the metric configuration, the judge, and the DeepEval version (prompts and formulas change between releases). Record all of them with every run:
- the app's model and prompt version in each test case's
metadata(from your adapter) and inhyperparameters; - the judge (
evaluation_modelis recorded per metric automatically); deepeval.__version__inhyperparameters, as every sample here did;- the dataset version (a fingerprint as in 10A.8's
dataset_fingerprint) inhyperparameters; - the results file itself, archived by CI.
A number without these is a number you cannot compare with next month's.
10.6 A checklist before you quote a DeepEval number#
- Which number is it (per case or per metric, rate or mean), on how many cases, with what interval?
- Which metric, threshold, judge model and DeepEval version produced it?
- Did the oracle pass and the null fail, with the real judge?
- Has the judge behind each LLM metric been checked against human labels (10A.5)?
- Were any metrics skipped, errored or flaky, and how many cases does that affect?
- Was the cache used, and could it be stale?
- Is the comparison against a baseline paired, on the same cases, with the same metric configuration?
- Have you read the failing cases' reasons?
Part 11: Older code and tutorials#
Reference
DeepEval renames things often, and most tutorials online predate the current names. The old names below still work in 4.3.5 (with a warning, where noted); write the new ones.
| You will see | Use instead | Notes |
|---|---|---|
LLMTestCaseParams.ACTUAL_OUTPUT |
SingleTurnParams.ACTUAL_OUTPUT |
Same object; DeprecationWarning on import (already renamed by 4.0.10) |
TurnParams |
MultiTurnParams |
Same pattern |
LLMTestCase(additional_metadata={...}) |
metadata={...} |
Accepted as an alias and lands in metadata; a DeprecationWarning is raised but hidden by Python's default warning filters (10B.17, 2.2) |
GPTModel(...) |
OpenAIModel(...) |
Same class; DeprecationWarning on import |
MLLMTestCase, MLLMImage(url=..., local=False) |
LLMTestCase with MLLMImage placeholders in strings (2.7) |
No separate multimodal test case any more |
ToxicityMetric(threshold=0.2) meaning "at most 20% toxic" (also Bias, Hallucination, Misuse) |
threshold=0.8 meaning "at least 80% clean" |
Direction flipped in 4.2.0; a DeprecationWarning reminds you once per process |
DisplayConfig(display="failing") (current docs) |
DisplayConfig(display_option=TestRunResultDisplay.FAILING) |
The docs' name never worked in 4.3.5 |
Custom metrics that implement is_successful() themselves (the docs still recommend it) |
Call the inherited self.is_successful() |
In 4.3.5 the base class implements it, including threshold=None |
DAGMetric nodes built with children=[...] |
add_verdict() / add_node() |
10B.3 |
pytest deepeval ... or plain pytest for eval suites |
deepeval test run ... |
5.6 |
deepeval login as step one of every tutorial |
Nothing: everything in this lesson works without an account | The platform is optional (10B.7) |
The warnings, as 4.3.5 prints them (paths shortened):
# older_names.py: names from older tutorials still work in 4.3.5, with warnings (lesson 10B.2)
import warnings
warnings.simplefilter("always") # show every DeprecationWarning once per call site
from deepeval.test_case import LLMTestCase, LLMTestCaseParams, SingleTurnParams # noqa: E402
print("LLMTestCaseParams is SingleTurnParams:", LLMTestCaseParams is SingleTurnParams)
tc = LLMTestCase(input="q", actual_output="a", additional_metadata={"intent": "refunds"})
print("additional_metadata landed in:", tc.metadata)
from deepeval.models import GPTModel, OpenAIModel # noqa: E402
print("GPTModel is OpenAIModel:", GPTModel is OpenAIModel).../older_names.py:6: DeprecationWarning: 'LLMTestCaseParams' is deprecated and will be removed in a future release. Use 'SingleTurnParams' instead.
from deepeval.test_case import LLMTestCase, LLMTestCaseParams, SingleTurnParams # noqa: E402
.../older_names.py:6: DeprecationWarning: 'LLMTestCaseParams' is deprecated and will be removed in a future release. Use 'SingleTurnParams' instead.
from deepeval.test_case import LLMTestCase, LLMTestCaseParams, SingleTurnParams # noqa: E402
.../older_names.py:13: DeprecationWarning: 'GPTModel' is deprecated and will be removed in a future release. Use 'OpenAIModel' instead.
from deepeval.models import GPTModel, OpenAIModel # noqa: E402
.../older_names.py:13: DeprecationWarning: 'GPTModel' is deprecated and will be removed in a future release. Use 'OpenAIModel' instead.
from deepeval.models import GPTModel, OpenAIModel # noqa: E402
LLMTestCaseParams is SingleTurnParams: True
additional_metadata landed in: {'intent': 'refunds'}
GPTModel is OpenAIModel: True(Each warning prints twice because the sample sets warnings.simplefilter("always").) When you find a snippet online, check its date against 1.2's release table and run it with warnings visible (python -W always::DeprecationWarning file.py) before you trust it.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "DeepEval runs my app and evaluates it." | It scores finished test cases. Running your app, and recording its outputs, retrieval and tool calls honestly, is your adapter's job (2.10). |
| "DeepEval needs an API key." | Only its LLM metrics do, and only for a real judge. Deterministic and custom metrics, the runners, the cache and the result files all work offline; a stand-in judge covers the plumbing of LLM metrics. |
| "Deterministic metrics never need a model." | ToolCorrectnessMetric and JsonCorrectnessMetric score with code but build a judge in their constructor, so they fail without a key unless you pass model=. |
"context and retrieval_context are the same thing." |
context is ground truth you write (read by Hallucination); retrieval_context is what your retriever returned, in rank order (read by Faithfulness and the Contextual metrics). |
| "A score equal to the threshold fails." | The rule is score >= threshold, so it passes. |
| "Lower is better for toxicity and bias." | Not since 4.2.0: every metric is higher-is-better and the threshold is a minimum. |
"After evaluate(), my metric object holds the results." |
In the default mode your object was not used; in sequential mode it holds only the last case. Read EvaluationResult. |
"A custom metric only needs measure() to be right." |
It also needs every constructor argument stored under its own name, or the runners (in the default async mode of evaluate() and assert_test()) silently rebuild it with defaults. |
| "The cache makes my evals deterministic." | It makes reruns free by freezing earlier results, including stale ones when a custom metric changed. |
"deepeval test run fails the build when the pass rate drops." |
It fails when any test fails. Suite-level and baseline gates are your script over the results file. |
| "Flaky means the test is retried until it passes." | flaky=True means a failure is reported but cannot fail the case or the build. |
| "Pass Rate in the summary is the metric's pass rate." | The summary's Pass Rate is per test case (all metrics passed); the per-metric rates are in the Aggregate Metrics panel. |
".env.local is only for my machine, so it is harmless." |
It overrides .env for every DeepEval run in that folder, and set-* commands write keys into it in plain text. |
| "DeepEval validates its own judges." | It has no judge-agreement, interval or significance tooling; that is 10A.5 and 10A.8. |
Key takeaways#
- DeepEval (Confident AI, Apache-2.0, 4.3.5 as of 24 November 2026, releases every few days) is a Python library, a pytest runner and a CLI, with an optional paid platform. Pin it with your lock file, record its version with every result, and re-read thresholds across the 4.2.0 direction flip.
- Installing it brings about 80 packages, including pytest and four plugins, the OpenAI SDK, OpenTelemetry and PostHog. Set
DEEPEVAL_TELEMETRY_OPT_OUT=1;import deepevalloads.env,.env.<APP_ENV>(only whenAPP_ENVis set) and.env.localfrom the working folder, with the process environment winning and.env.localbeating.env. - DeepEval writes
.deepeval/(cache and latest run), optional results files or a SQLite store, and.env.local(plain-text keys fromset-*). Git-ignore all of them. - A test case is a finished record:
LLMTestCase(onlyinputrequired),ConversationalTestCaseofTurns,ToolCall(equal on name, arguments and output),MLLMImageplaceholders,ArenaTestCase. Each metric reads specific fields and raisesMissingTestCaseParamsErrorwithout them. - A metric is a stateful object:
score,reason,successof its latest run,success = score >= threshold,threshold=Nonefor tracking only,strict_modefor hard gates,flakyfor checks that may not fail the case. LLM metrics build their judge at construction. - The deterministic metrics have exact rules worth knowing: exact match strips whitespace only, pattern match is a full match, JSON correctness is Pydantic validation, tool correctness ignores extra calls and arguments by default.
- A custom metric is
measure(),a_measure(), a threshold, a name and every constructor argument stored under its own name, becauseevaluate()andassert_test()(in their default async mode) rebuild metrics per case from those attributes. evaluate()returnsEvaluationResult→TestResult→MetricData; a case passes when every non-flaky thresholded metric passes;AsyncConfig,DisplayConfig(display_option,results_folder),CacheConfigandErrorConfigcontrol concurrency, output, caching and failure policy.assert_test()+deepeval test rungate CI with pytest's exit code (0, 1, 2, 5), with flags for workers, repeats, cache, errors, display and markers, extra pytest arguments after--, and hooks for hyperparameters and end-of-run actions.- The cache stores metric results keyed by six test-case fields and a list of metric settings; custom metric parameters are not in the key, so it can serve stale scores. Save runs with
results_folderor SQLite and compute intervals, slices and comparisons yourself. - DeepEval produces numbers easily; defending them is still 10A.1 to 10A.8: name the number, run oracle and null controls, read reasons, put intervals on rates, validate judges, and record what produced every run.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| DeepEval | Confident AI's open-source Python library for evaluating LLM apps as unit tests: test cases, metrics, evaluate(), assert_test() and the deepeval CLI |
| Confident AI | The company behind DeepEval and its optional hosted platform for storing, comparing and monitoring eval runs |
LLMTestCase |
DeepEval's single-turn test case: a finished record of one interaction (input, actual output, optional reference, contexts, tool calls, metadata) |
ConversationalTestCase / Turn |
DeepEval's multi-turn test case, a non-empty list of user and assistant turns plus scenario and role fields |
retrieval_context |
The chunks your retriever actually returned, in rank order; read by Faithfulness and the Contextual metrics (contrast context, ground truth you write) |
ToolCall (DeepEval) |
A recorded tool invocation; two are equal when name, input parameters and output match |
MLLMImage |
DeepEval's image reference, embedded in test-case strings as a placeholder that switches the case to multimodal |
ArenaTestCase |
A set of named contestants answering the same input, for pairwise comparison with ArenaGEval |
| Metric object (DeepEval) | A configured, stateful scorer whose latest score, reason and success live on the object |
| Threshold (DeepEval) | The minimum passing score for a metric; success = score >= threshold, and None makes the metric informational |
strict_mode |
A metric switch that sets the threshold to 1 and turns any imperfect verdict-based score into 0 |
| Flaky metric / flaky test case | A metric or case whose failure is reported but cannot fail the test case or the build |
evaluate() |
DeepEval's in-code runner: scores a list of test cases with metrics and returns an EvaluationResult |
EvaluationResult / TestResult / MetricData |
The three levels of results: the run, one test case, one metric on one case |
assert_test() |
DeepEval's pytest assertion: scores one test case and raises AssertionError if any non-flaky metric fails |
deepeval test run |
The CLI runner that runs pytest with DeepEval's plugin, prints a results table and exits with pytest's code |
| Copy rule (DeepEval) | In their default async mode, evaluate() and assert_test() rebuild each metric per test case from instance attributes named like its constructor arguments (also called the attribute-copy trap) |
| DeepEval cache | .deepeval/.deepeval-cache.json: stored metric results keyed by test-case fields and metric settings, read only with -c or use_cache=True |
| Results folder | A folder where DeepEval writes one test_run_<timestamp>.json per run |
| QAG (DeepEval) | DeepEval's decompose-then-verdict metric design: extract items, judge each yes or no, score the fraction |
| Fake judge (DeepEval) | FakeJudge, this track's DeepEvalBaseLLM subclass that returns scripted answers (by call order or by prompt content) instead of calling a model, for keyless plumbing tests |
deepeval diagnose |
The CLI command that shows the effective configuration and which file or variable each setting came from |
Exercises#
All exercises run keyless with the files from this lesson.
- Field audit (2.3, 2.4). Your
docs_qaadapter fillsinput,actual_outputandretrieval_context. List which of Faithfulness, Answer Relevancy, Contextual Precision, Contextual Recall and Hallucination can run on its test cases, and what you would add for the others. Then check your answer by runningrequired_fields.pywith those five names. - The full-match trap (3.6). Write a
PatternMatchMetricthat passes "Usually 3-5 business days." and "3-5 business days" but fails "5-8 business days". Run it on all three. - Strict mode arithmetic (3.3). In
metric_contract.py, change the scripted verdicts to five statements with one"no". Predict the score with and withoutstrict_mode, then run it. - A third support metric (3.7). Write
MentionsPolicyLinkMetric(url="acme.example/returns")that passes when the answer contains the public returns link. Add it tofirst_eval.py. Which cases fail, and does the case-level pass rate change? - Break and fix the copy rule (4.5). Store your new metric's
urlargument asself.linkand run it with a non-default URL throughevaluate()andassert_test(), each in both modes. Explain the two results, then fix it. - Error policy (4.9). Make
LengthMetricraiseValueErrorwhenactual_outputis empty, and add a case with an empty answer to the three support cases. Runevaluate()withLengthMetricas the only metric, first with the defaultErrorConfigand then withignore_errors=True. What does each do to the run and to that case? - Exit codes (5.5). Run
deepeval test run test_support.pywith-- -k Canada, with-- -k nothing, and with no selection. Record each exit code and say which a CI job should treat as failure. - Stale cache (6.3). Run
cache_demo.pyonce. Then renameLengthMetric's__name__to"Length v2", change the name lookup inrun()to match, and run only run 3, without deleting the cache (comment out thermtreeline and the other three runs). Does the stale result disappear? Why? - A suite gate (6.6). Extend
report_run.pyso it exits with code 1 when the case pass rate's Wilson lower bound is below 0.5, and run it on the saved run. - Fix the oracle (10.2). Decide whether the 60-character limit or the
tracking-leakreference is wrong, change one of them, and reruncontrols.pyuntil the oracle passes every case. Then explain what the null run still tells you.
Answers
- Faithfulness (input, actual_output, retrieval_context) and Answer Relevancy (input, actual_output) can run. Contextual Precision and Contextual Recall also need
expected_output(they do not readactual_output). Hallucination needscontext, the ground-truth passages, which the adapter must not fill from retrieval; add them from your dataset. - For example
PatternMatchMetric(pattern=r"(?:usually )?3-5 business days\.?", ignore_case=True): the optional prefix and full stop make both phrasings full matches, and "5-8" fails. Wrapping in.*would also work but is looser (it accepts "not 3-5 business days"). - Four of five relevant: 0.8 without strict mode (passes at 0.5); with strict mode the threshold is 1 and the score is clamped to 0 (fails). Three judge calls in each run.
refund-ok,refund-wordyandtracking-leakall lack the link, so all fail the new metric; the case-level pass rate drops from 33.33% to 0%. A gate that fails every case tells you the metric expresses a policy the app does not yet follow, not that the answers got worse.- In async mode (the default for both runners) the copy is built with the default URL, because
copy_metricslooks for an attribute namedurland does not find one; in sequential mode (AsyncConfig(run_async=False),assert_test(..., run_async=False)) your object is used and the URL you passed applies. Fix:self.url = url. - Default: the
ValueErrorpropagates andevaluate()stops, with no results. Withignore_errors=True: that case getsMetricData(score=None, success=False, error="...")for Length, the case fails, and the other cases are scored normally. -k Canada: 0 (one test passed).-k nothing: 5 (no tests collected). No selection: 1 (the tracking case fails). A CI job should fail on every non-zero code, including 5, which means "nothing was evaluated".- Yes: run 3 now reports
score=1.0with "limit 100". The metric name is part of the cache match, so "Length v2" has no cached entry and is scored again with the new limit, while Correctness, unchanged, is still served from the cache (zero judge calls). Versioning the name is the cheap way to invalidate a custom metric's cache entries. - Compute
lo, hi = wilson(passed, len(cases))as the script already does andsys.exit(1 if lo < 0.5 else 0). On the saved run the lower bound is 0.061, so it exits 1. This is a suite-level gate thatdeepeval test run's exit code cannot express. - Either choice is defensible if written down: raise the limit (for example to 80) if the widget allows it, or shorten the reference if 60 characters is a hard product limit. The null run still passes every case, which shows that both metrics are guard rails and that the suite's ability to fail a bad answer rests on the correctness metric and its judge.
Check yourself#
- What does
evaluate()do with your application?Nothing: it never calls your app. It scores the test cases you built from your app's outputs. - In what order does
import deepevalload.envfiles, and what always wins?.env, then.env.<APP_ENV>(only whenAPP_ENVis set, in the environment,.env.localor.env; there is no default), then.env.local, with later files winning; variables already in the process environment always win.DEEPEVAL_DISABLE_DOTENV=1stops the loading. - Which setting turns telemetry off, and where should you set it?
DEEPEVAL_TELEMETRY_OPT_OUT=1, in.env(it is loaded at import) and in the CI job's environment. - A metric has threshold 0.7 and scores exactly 0.7. Does it pass?Yes: the rule is
score >= threshold. - What is the difference between
contextandretrieval_context, and which metrics read each?contextis ground-truth context you write; Hallucination reads it.retrieval_contextis what the retriever returned, in rank order; Faithfulness, Contextual Precision, Recall and Relevancy read it. - Why does
AnswerRelevancyMetric()fail before you have created a test case?LLM metrics build their judge in the constructor; with nomodel=and no configured judge, DeepEval builds an OpenAI judge and finds no key. - Which two "deterministic" metrics still need a model argument without a key, and why?
ToolCorrectnessMetricandJsonCorrectnessMetric. Both build a judge in__init__(for optional tool selection, and for explaining invalid JSON), even though their scores are computed in code. - What does
strict_mode=Truedo to a verdict-based metric's threshold and score?It sets the threshold to 1 and turns any score below 1 into 0, so one failing verdict fails the case. - After
evaluate(cases, [m])in the default mode, what doesm.scorecontain, and where should you read results instead?None, becauseevaluate()scored fresh copies of the metric; readEvaluationResult.test_results[i].metrics_data. (Withrun_async=Falseit would hold the last case's result.) - A custom metric stores its
limitargument asself.max_len. What happens inevaluate()and underdeepeval test run?The copy built for each case cannot find an attribute namedlimit, so it is constructed with the default limit, silently, in async mode.deepeval test runcallsassert_test()in its default async mode, so in CI the metric always runs with the default. - When does a test case pass in DeepEval?When every non-flaky metric that has a threshold passed (and its expectations and expected classifier labels, if any).
- What are the two
ErrorConfigpolicies, and how does each treat a failing case?skip_on_missing_paramsskips a metric whose fields are missing for that case (an all-skipped case reports success;evaluate()leaves it out of the totals, a traced run counts it as passed);ignore_errorsrecords a metric's exception as an error and fails the case, and the run continues. - What exit code does
deepeval test runreturn when no tests are selected, and why does it matter for CI?5 ("no tests collected"). It means nothing was evaluated; CI must treat it as a failure, not as "no failures". - What does DeepEval's cache key contain, and name one change it does not notice?The JSON of
input,actual_output,expected_output,context,retrieval_contextand the hyperparameters, plus the metric name and a fixed list of settings (threshold, judge, strict mode, steps and so on). It does not notice a changed custom-metric parameter, or changes totools_called,metadataor turns. - Name three things DeepEval does not do that you still need for a defensible number.Any three of: judge validation against human labels; confidence intervals; paired run comparison and significance tests; running and recording your system; dataset versioning; determinism of LLM metrics; sandboxed code execution.
Further resources#
Official documentation (every URL listed in this track's research sheets and checked on 24 November 2026; llms-full.txt is the whole documentation as one searchable text file):
- Introduction and Getting started: what DeepEval is and the first test.
- Evaluation introduction: end-to-end versus component-level evaluation.
- Test cases, multi-turn test cases and arena test cases: every field (and see 2.2 for where the code differs).
- End-to-end evals:
evaluate()andassert_test()in the docs' own words. - Flags and configs: the four config objects and the
test runflags (remember:display_option, notdisplay). - Unit testing in CI/CD:
deepeval test run, hooks and hyperparameters; 10B.7 builds on it. - Local backend storage: results folders and the SQLite store.
- Metrics introduction: the metric contract, thresholds and the catalogue; more complete than any table in this lesson.
- Custom metrics: the
BaseMetriccontract (do not copy the constructor example; 3.7). - Exact Match, Pattern Match, JSON Correctness and Tool Correctness: the deterministic metrics.
- Command line interface and Environment variables: every command and setting.
- Data privacy: what telemetry collects and how to opt out.
- Troubleshooting: common errors and their fixes.
- Using custom LLMs: the
DeepEvalBaseLLMinterfaceFakeJudgeimplements (10B.3 goes deep).
Code and packages:
- confident-ai/deepeval on GitHub: the source, issues and licence. When the docs and behaviour disagree (as in 4.5 and 4.7), the installed source is the final word for your version.
- GitHub releases (up to 4.2.4) and the PyPI release history (every version, with dates).
Within this course: 10B.1 for why and when to adopt a framework, 10B.3 to 10B.7 for judges, metrics, tracing, datasets and production, 10B.17 for DeepEval versus Inspect, and 10B.18 for a reading plan through the official docs.
← 10B.1: The Eval Framework Track: DeepEval, Inspect AI and Your Setup | Module 10B overview | 10B.3: Judges in DeepEval: Models, G-Eval, DAG and Custom Metrics →