10B.6 DeepEval Datasets, Synthetic Data, Conversation Simulation and Benchmarks

ProductionLesson 6 of 1824,708 words10 parts
Module 10B · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18

In 10B.2 you scored test cases you had written by hand. This lesson is about the three ways DeepEval can supply or generate the input side of an evaluation: durable goldens stored in an EvaluationDataset, synthetic goldens written by the Synthesizer, multi-turn conversations produced by the ConversationSimulator, and, for raw model probes rather than application evals, the public benchmark classes in deepeval.benchmarks. These are powerful conveniences and dangerous conveniences: a golden is not a finished test case, a synthetic reference answer is not ground truth, a simulated user is part of the measuring instrument, and a benchmark score is a property of a harness as much as of a model. Every keyless sample below ran for real with DeepEval 4.3.5 (4.3.6 followed on 25 November 2026 and moved red teaming back into DeepEval; see 10B.7), the track's scripted FakeJudge, a fake embedder or patched benchmark data, telemetry off and no API key. The runs also exposed sharp edges the documentation does not warn you about: filtration never discards a synthetic input, document splitting can download a tokenizer file on first use, the synchronous Synthesizer can crash when a model over-generates, a missing expected outcome makes simulations run to their cap, EquityMedQA's scoring is inverted, TruthfulQA's MC2 mode reports a recall percentage on a 0 to 100 scale (or 1.0 for any overlap when batched), and HumanEval never calls the problem's test function, so a wrong function counts as a pass. Every one of these was reproduced keylessly, and every one is still present in 4.3.6.

What you'll learn

  • What a Golden is, how it differs from an LLMTestCase, and why the generate-at-eval-time pattern makes goldens reusable across application versions
  • Golden, ConversationalGolden and Persona field by field, and the strict rule that single-turn and multi-turn goldens never share one dataset
  • EvaluationDataset: adding rows, loading and saving JSON, JSONL and CSV, what pandas is needed for, what include_test_cases really does, and which methods are Confident AI cloud features
  • How to version datasets locally in git when you do not use Confident AI, and how DeepEval's dataset model maps onto evalkit.dataset.py from 10A.2
  • The Synthesizer's constructor, all four generation entry points and their conversational twins, every configuration object, the command-line interface, output helpers and cost behaviour
  • The contexts pipeline step by step: candidate generation, critic scoring, rewriting, evolutions, styling, expected outputs and the metadata each golden carries
  • The seven evolution types, their WizardLM/Evol-Instruct lineage, how weighting and seeding work, and why evolution changes both difficulty and realism
  • Generation from scratch, from existing goldens and conversational generation, including which passes each path does and does not run
  • Document-based generation: optional dependencies, token chunking, embeddings, quality scoring, Chroma neighbour expansion, the tiktoken first-download trap and the over-generation crash
  • The methodology of synthetic eval data: silver labels, self-preference, homogeneity, lexical leakage, filtering, deduplication, human review, dataset cards and provenance, mapped onto 10A.2, Parts 9 to 20
  • ConversationSimulator: the callback contract, personas, stopping order, custom controllers, simulation graphs and edge routing, hooks, custom templates, cost and the absence of tracing
  • How to validate a simulated user with the realism, discriminability, fidelity, leakage, termination, calibration and predictive-validity checks from 10A.12, Part 7
  • DeepEval's 17 public benchmark classes, their defaults, datasets and scoring methods, what a run does mechanically, and why the numbers are not leaderboard-comparable
  • HumanEval's in-process code execution and the missing check() call, judge-scored SQuAD and EquityMedQA, the EquityMedQA inversion, the TruthfulQA MC2 scale bug, contamination and the statistical caveats
  • How to defend a benchmark comparison: micro- versus macro-averages, Wilson intervals, a paired test on the same questions, and why a per-task view catches what all three miss
  • How to build an in-house multiple-choice benchmark from goldens with a tested parser, which is usually the better tool for an application team
  • A decision table, a failure gallery, the full evalkit ↔ DeepEval mapping, a docs-versus-source table and the older names you will meet in tutorials

What you don't need

  • An API key. Every runnable sample uses deterministic code, the shared FakeJudge from 10B.2, 3.5, a fake embedding model or a patched benchmark loader. No sample calls a hosted model, Confident AI or Hugging Face. Provider-backed usage is described and labelled, not run.
  • Confident AI. Push, pull, queues and platform dataset versions are cloud features. This lesson shows exactly how they fail without a key and then uses files in git, the local pattern 10A.2, 6.3 recommends.
  • DeepEval fundamentals. Test cases, evaluate(), metric construction, the test runner and caching are 10B.2. Judge models and the DeepEvalBaseLLM contract are 10B.3. Multi-turn metric formulas are 10B.4, Part 6. Tracing, evals_iterator and agent metrics are 10B.5. Red teaming and Confident AI are 10B.7.
  • The underlying evaluation theory. Dataset design is 10A.2 (Parts 1 to 8), synthetic data generation is 10A.2, Parts 9 to 20, benchmark literacy is 10A.10, Part 5, and simulator validation is 10A.12, Part 7. This lesson maps those ideas onto DeepEval rather than re-teaching them.

Setup

You need Python 3.10 or newer (the course uses 3.13) and uv. If you are new to uv, follow 01B.1 or the setup part of 03.1. Create one project for this lesson:

bash
uv init deepeval-data-lab --bare --python 3.13 && cd deepeval-data-lab   # first time only
uv add deepeval pandas datasets chromadb langchain-community langchain-text-splitters tiktoken
# or: pip install deepeval pandas datasets chromadb langchain-community langchain-text-splitters tiktoken
python -c "import tiktoken; tiktoken.get_encoding('gpt2')"   # once, while online: caches a tokenizer file (5.4)

pandas is needed for CSV loading and to_pandas(). datasets is imported by the benchmark base class (and brings numpy, which HumanEval's pass@k estimator uses). chromadb, the LangChain packages and tiktoken are needed only by document-based synthesis. Put telemetry off in .env:

bash
# .env
DEEPEVAL_TELEMETRY_OPT_OUT=1

Copy fake_judge.py unchanged from your 10B.2 folder or from 10B.4, 1.7. The runnable files also import this tiny guard, which proves that a keyless run made no network attempt:

python
# netguard.py: block and log outbound network connections during keyless samples
import atexit
import socket
import sys

ATTEMPTS = []
_orig_connect = socket.socket.connect
_orig_gai = socket.getaddrinfo

def _connect(self, addr):
    ATTEMPTS.append(("connect", addr))
    print(f"[netguard] BLOCKED connect to {addr}", file=sys.stderr)
    raise OSError("netguard: network blocked")

def _gai(host, *args, **kwargs):
    if host not in ("localhost", "127.0.0.1", None):
        ATTEMPTS.append(("dns", host))
        print(f"[netguard] BLOCKED DNS {host}", file=sys.stderr)
        raise socket.gaierror("netguard: dns blocked")
    return _orig_gai(host, *args, **kwargs)

socket.socket.connect = _connect
socket.getaddrinfo = _gai
atexit.register(lambda: print(f"[netguard] total blocked attempts: {len(ATTEMPTS)} {sorted(set(str(a[1]) for a in ATTEMPTS))}", file=sys.stderr))

Versions (current at time of writing, verified against PyPI, the installed package source and the official documentation on 24 November 2026): deepeval 4.3.5 (released 24 November 2026, Apache-2.0, Python ≥ 3.10; 4.3.6 was released on 25 November 2026 and moved red teaming back into DeepEval, see 10B.7; this lesson stays checked against 4.3.5, and on 28 November 2026 every sample was re-run on both 4.3.5 and 4.3.6 with identical output). Optional packages used in the verification environment were pandas, datasets 5.2.0, chromadb 1.5.9, langchain-community 0.4.2, langchain-text-splitters 1.2.0 and tiktoken 0.14.0. Every sample marked as run was executed with Python 3.13, DEEPEVAL_TELEMETRY_OPT_OUT=1, no API key and uv run --no-project --with ... python -E -s <file>.py; python -E -s keeps sibling imports such as fake_judge.py visible without reading user site packages. Outputs are real and are marked trimmed where progress bars, package-install lines or terminal control sequences are omitted.


What you must be able to do after this lesson#

  • Explain the difference between a Golden and an LLMTestCase
  • Build and save an EvaluationDataset of goldens
  • Generate synthetic goldens from documents with the Synthesizer and filter them
  • Make synthetic goldens trustworthy with sampling checks and human review
  • Run a ConversationSimulator and say when a simulated conversation ends
  • Choose the data source (hand-written, synthetic, simulated, benchmark) for a given eval

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just export the test cases as CSV." 1.4
"Goldens are better because the app output stays fresh." 1.2
"Why can't this dataset contain both kinds of rows?" 1.6
"Can we version the dataset without Confident AI?" 1.8
"The Synthesizer has a quality filter, so we're safe." 3.3 and 6.2
"Where did those 21 model calls go?" 3.7
"Why did offline document generation try to reach Microsoft Azure?" 5.4
"The bot passed in simulation but users hate it." Part 8
"It knows the answer but MMLU scored it zero." 9.4
"EquityMedQA says the unbiased answer is wrong." 9.7
"Our HumanEval pass rate is 100 percent." 9.6
"TruthfulQA MC2 says 85.0, but the docs say scores run from 0 to 1." 9.5
"The new model has the same MMLU score, so nothing changed." 9.10
"Can we use public benchmarks for release gates?" 9.9
"We should build our own benchmark." 9.11

Part 1: Goldens and datasets#

1.1 The object model in one picture#

DeepEval's dataset documentation uses a precise distinction: an evaluation dataset is a collection of goldens, and a golden is a precursor to a test case. The golden holds the input and the references. The application's output is produced when the evaluation runs, then packed into an LLMTestCase or ConversationalTestCase. The same golden can therefore evaluate many application versions without ever carrying a stale actual_output from an old one.

flowchart LR
    G["Golden: input, references, context"] --> R["Run current app at eval time"]
    R --> T["LLMTestCase: input plus actual output"]
    T --> M["Metrics and evaluate()"]
    M --> S["Score for this app version"]
    G -. reusable across versions .-> G

This is exactly the split evalkit makes in 10A.2: an EvalExample is durable data, while a row in an eval report is a measurement of one system at one time. DeepEval adds convenience methods around that split, but it does not remove your responsibility to record provenance, slices, corpus versions and generation settings.

1.2 Goldens versus test cases, and generate-at-eval-time#

The smallest useful workflow looks like this. The toy application is deterministic so the keyless run is reproducible; in your project, refund_policy_app is the current version of your LLM application.

python
"""Lesson 10B.6: goldens are reusable references; the app's output is generated at eval time."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval import evaluate
from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate.configs import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.test_case import LLMTestCase


def refund_policy_app(question: str) -> str:
    """A deterministic toy app. In a real eval this is your current LLM app."""
    if "refund" in question.lower():
        return "Refunds arrive within 5 business days of approval."
    return "I do not know."


dataset = EvaluationDataset(goldens=[
    Golden(input="How long does a refund take?", expected_output="Refunds arrive within 5 business days of approval."),
    Golden(input="Where does the refund go?", expected_output="To the original payment method."),
])

test_cases = []
for golden in dataset.goldens:
    actual = refund_policy_app(golden.input)
    test_cases.append(LLMTestCase(
        input=golden.input,
        actual_output=actual,
        expected_output=golden.expected_output,
        context=golden.context,
        retrieval_context=golden.retrieval_context,
        metadata=golden.additional_metadata,  # Golden says additional_metadata; test cases say metadata
        name=golden.name,
    ))

result = evaluate(
    test_cases,
    metrics=[ExactMatchMetric()],
    async_config=AsyncConfig(run_async=False),
    display_config=DisplayConfig(show_indicator=False, print_results=False),
)
for test_result in result.test_results:
    metric_data = test_result.metrics_data[0]
    print(test_result.input, "| success:", test_result.success, "| score:", metric_data.score, "| reason:", metric_data.reason)
print("dataset goldens still have no actual_output:", [golden.actual_output for golden in dataset.goldens])
Output · real, trimmed20 lines
⚠ WARNING: No hyperparameters logged.
» Log hyperparameters to attribute prompts and models to your test runs.

================================================================================

✓ Evaluation completed 🎉! (time taken: 0.01s | token cost: None)
» Test Results (2 total tests):
   » Pass Rate: 50.0% | Passed: 1 | 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.

How long does a refund take? | success: True | score: 1.0 | reason: The actual and expected outputs are exact matches.
Where does the refund go? | success: False | score: 0.0 | reason: The actual and expected outputs are different.
dataset goldens still have no actual_output: [None, None]
[netguard] total blocked attempts: 0 []

Three details matter:

  1. The dataset's goldens still have actual_output=None after the run. They were not mutated.
  2. The first case passes exact match because the toy app returns the reference verbatim; the second fails because the app falls through to "I do not know.". This tiny oracle/null pair is the same control pattern 10B.2, Part 10 recommends.
  3. evaluate() prints a Confident AI suggestion even in a fully local run. Nothing was uploaded; the netguard line reports zero blocked attempts because no attempt was made.

1.3 Golden, ConversationalGolden and Persona#

Golden is a Pydantic model (a Python class that validates its fields when you construct it, so a typo in a field name or a wrong type fails at once). The required field is only input: str; every other field is optional unless a metric or loader needs it. The verified fields in 4.3.5 are:

Field group Fields What they are for
Identity and input id, input (required), name, source_file Stable identity, the prompt or user input, human-readable grouping, provenance
References expected_output, context, retrieval_context, expected_tools, expectations, expected_labels What a correct answer, supporting corpus, retrieval, tool sequence or classifier label should look like
Observed run data actual_output, tools_called, token_cost, input_token_count, output_token_count Usually filled only after running the app, if you choose to store them at all
Data management additional_metadata, comments, custom_column_key_values Slices, provenance, reviewer notes and columns round-tripped through platform CSV exports
Multimodal multimodal=False, images_mapping Image-aware cases; multimodal metrics are 10B.4, 7.1

context and retrieval_context are not interchangeable. As 10B.4, 2.1 shows, context is golden reference material and retrieval_context is what your retriever actually returned. A synthetic golden normally carries context; your run-time test case carries retrieval_context after your RAG pipeline runs.

ConversationalGolden describes a conversation to be simulated rather than a single input:

Field Meaning
scenario (required) What the simulated user is trying to accomplish
expected_outcome The hidden success condition used by the default stopping controller
persona A Persona object describing who the user is
user_description Older free-text user description; persona is its successor
context Reference material for the scenario
turns Pre-existing turns, if you are importing rather than simulating
additional_metadata, comments, name, custom_column_key_values, expectations, expected_labels The same data-management role as on Golden
multimodal, images_mapping Multimodal conversations

Persona is imported from deepeval.dataset. Its important text-simulation fields are name, characteristics, metadata and speaks_first. The remaining constructor fields (interruption_behavior, voice, background_noise, multilingual_stt, hold_timeout, muted) are voice-only in 4.3.5 and are ignored by text simulations. DeepEval's own source docstring draws the line clearly: characteristics is who the user is, including demographics, personality, emotional arc, speaking style and filler words; scenario and expected_outcome are what the user wants. Keep those separate. A persona that secretly contains the goal makes the simulated user leak information too early.

1.4 EvaluationDataset: loading, saving and round trips#

The constructor is small:

python
from deepeval.dataset import EvaluationDataset, Golden, ConversationalGolden, Persona

dataset = EvaluationDataset(goldens=[Golden(input="How long does a refund take?")])

The useful local methods are add_golden, add_test_case, the six add_goldens_from_* and add_test_cases_from_* loaders, save_as(file_type="json" | "csv" | "jsonl", directory=..., file_name=..., include_test_cases=False), to_pandas() and the generation convenience wrappers. evals_iterator() and dataset.evaluate(task) belong to tracing and component-level evaluation, so 10B.5 owns them.

This probe builds one single-turn golden and one conversational golden, demonstrates the mixing rule, round-trips JSON, JSONL and CSV, inspects the CSV shape, stores a test case and then calls every Confident AI dataset method without a key:

python
"""Lesson 10B.6: EvaluationDataset goldens, round trips and cloud-only methods."""
import json
import os
import warnings
warnings.filterwarnings("ignore")

import netguard  # blocks sockets; proves this run stayed local
from deepeval.dataset import EvaluationDataset, Golden, ConversationalGolden, Persona
from deepeval.test_case import LLMTestCase

outdir = "ran/out_dataset"
os.makedirs(outdir, exist_ok=True)

refund = Golden(
    input="How long does a refund take?",
    expected_output="Refunds arrive within 5 business days of approval.",
    context=["Refunds are issued within 5 business days of approval."],
    additional_metadata={"slice": "refund", "source": "human-authored"},
    name="refund-timing",
)
chat = ConversationalGolden(
    scenario="A customer whose order arrived broken wants a refund.",
    expected_outcome="The assistant issues a refund and gives a confirmation number.",
    persona=Persona(name="Sam", characteristics="Polite but brief; writes short messages."),
)

print("== the two golden types")
print("single-turn:", refund.model_dump(exclude_none=True))
print("multi-turn persona:", chat.persona.model_dump(exclude_none=True))

print("\n== single-turn and multi-turn goldens do not mix")
try:
    EvaluationDataset(goldens=[refund, chat])
except Exception as exc:
    print(type(exc).__name__, str(exc))
single = EvaluationDataset(goldens=[refund])
try:
    single.add_golden(chat)
except Exception as exc:
    print(type(exc).__name__, str(exc))

print("\n== save and reload JSON, JSONL and CSV")
json_path = single.save_as(file_type="json", directory=outdir, file_name="refunds")
jsonl_path = single.save_as(file_type="jsonl", directory=outdir, file_name="refunds")
csv_path = single.save_as(file_type="csv", directory=outdir, file_name="refunds")
for kind, path in [("json", json_path), ("jsonl", jsonl_path), ("csv", csv_path)]:
    loaded = EvaluationDataset()
    if kind == "json":
        loaded.add_goldens_from_json_file(path)
    elif kind == "jsonl":
        loaded.add_goldens_from_jsonl_file(path)
    else:
        loaded.add_goldens_from_csv_file(path)
    print(kind, "->", len(loaded.goldens), loaded.goldens[0].input, "context type:", type(loaded.goldens[0].context).__name__)

print("\n== saved CSV header and row shape")
with open(csv_path, encoding="utf-8") as fh:
    for i, line in enumerate(fh):
        print(line.rstrip()[:240])
        if i == 1:
            break

print("\n== test cases can be stored, but goldens are the durable dataset")
single.add_test_case(LLMTestCase(input=refund.input, actual_output="Five business days.", expected_output=refund.expected_output))
print("goldens:", len(single.goldens), "test_cases:", len(single.test_cases))
with_tc = single.save_as(file_type="json", directory=outdir, file_name="with_cases", include_test_cases=True)
saved = json.load(open(with_tc, encoding="utf-8"))
print("saved keys:", sorted(saved.keys()) if isinstance(saved, dict) else type(saved).__name__)

print("\n== Confident AI methods fail closed without a key, before any network call")
for method, args in [
    ("push", ("lesson-demo",)),
    ("pull", ("lesson-demo",)),
    ("queue", ("lesson-demo", [refund])),
    ("create_version", ("lesson-demo",)),
    ("get_versions", ("lesson-demo",)),
]:
    try:
        getattr(single, method)(*args)
        print(method, "unexpectedly succeeded")
    except Exception as exc:
        print(method, "->", type(exc).__name__, str(exc)[:150])
Output · real, trimmed32 lines
== the two golden types
single-turn: {'input': 'How long does a refund take?', 'expected_output': 'Refunds arrive within 5 business days of approval.', 'context': ['Refunds are issued within 5 business days of approval.'], 'additional_metadata': {'slice': 'refund' ...[trimmed]
multi-turn persona: {'name': 'Sam', 'characteristics': 'Polite but brief; writes short messages.', 'speaks_first': True, 'muted': False, 'multilingual_stt': False}

== single-turn and multi-turn goldens do not mix
TypeError You cannot add a multi-turn ConversationalGolden to a single-turn dataset. You can only add a Golden.
TypeError You cannot add 'ConversationalGolden' to a single-turn dataset.

== save and reload JSON, JSONL and CSV
Evaluation dataset saved at ran/out_dataset/refunds.json!
Evaluation dataset saved at ran/out_dataset/refunds.jsonl!
Evaluation dataset saved at ran/out_dataset/refunds.csv!
json -> 1 How long does a refund take? context type: list
jsonl -> 1 How long does a refund take? context type: list
csv -> 1 How long does a refund take? context type: list

== saved CSV header and row shape
input,actual_output,expected_output,retrieval_context,context,name,comments,source_file,tools_called,expected_tools,token_cost,input_token_count,output_token_count,additional_metadata,custom_column_key_values,expectations
How long does a refund take?,,Refunds arrive within 5 business days of approval.,,Refunds are issued within 5 business days of approval.,refund-timing,,,,,,,,"{""slice"": ""refund"", ""source"": ""human-authored""}",,

== test cases can be stored, but goldens are the durable dataset
goldens: 1 test_cases: 1
Evaluation dataset saved at ran/out_dataset/with_cases.json!
saved keys: list

== Confident AI methods fail closed without a key, before any network call
push -> ValueError No Confident API key found. Please run `deepeval login` or set the CONFIDENT_API_KEY environment variable in the CLI.
pull -> ValueError No Confident API key found. Please run `deepeval login` or set the CONFIDENT_API_KEY environment variable in the CLI.
queue -> ValueError No Confident API key found. Please run `deepeval login` or set the CONFIDENT_API_KEY environment variable in the CLI.
create_version -> ValueError No Confident API key found. Please run `deepeval login` or set the CONFIDENT_API_KEY environment variable in the CLI.
get_versions -> ValueError No Confident API key found. Please run `deepeval login` or set the CONFIDENT_API_KEY environment variable in the CLI.
[netguard] total blocked attempts: 0 []

The round trip teaches several details that are easy to miss:

  • JSON is a list of objects with null for absent fields. JSONL is one object per line. CSV is a flat table.
  • CSV stores list values using delimiters on load. By default context and retrieval_context are split on |, while tools_called and expected_tools use ;. additional_metadata is stored as JSON text inside the CSV cell.
  • The loader keyword arguments are the column or key names. For CSV they include input_col_name="input", expected_output_col_name="expected_output", context_col_name="context", context_col_delimiter="|", retrieval and tool equivalents, source_file_col_name, additional_metadata_col_name, plus the conversational columns scenario_col_name, turns_col_name, expected_outcome_col_name and user_description_col_name. JSON and JSONL use the same concepts as *_key_name, plus persona_key_name="persona" and encoding_type="utf-8".
  • CSV loading needs pandas. Without it, 4.3.5 raises ModuleNotFoundError: Please install pandas to use this method. 'pip install pandas'.
  • The same loader decides whether a row is conversational by the presence of scenario. That convenience is also why malformed mixed files fail confusingly: one row shape determines the dataset type.
  • include_test_cases=True writes test cases into the saved JSON, but save_as still returns a JSON list in this version. Treat test-case export as a migration or debugging feature, not as the durable dataset format.

1.5 A Hugging Face dataset is not a DeepEval dataset loader#

The datasets documentation says Python supports JSON, JSONL, CSV and Hugging Face datasets, but 4.3.5 has no EvaluationDataset method that loads a Hugging Face dataset. The verified import methods are only JSON, JSONL and CSV. If your source data is on Hugging Face, load it yourself with datasets.load_dataset and construct Golden objects explicitly. That extra step is useful anyway: it is where you should record licence, split, revision and filtering decisions in additional_metadata, as 10A.2, 2.6 requires.

Two other documentation mismatches are worth knowing. A CI guide constructs EvaluationDataset(test_cases=[...]); in 4.3.5 that keyword raises TypeError, because the constructor accepts goldens and confident_api_key, not test_cases. Use add_test_case for already completed cases. And deepeval.benchmarks.task in the benchmark introduction is singular in the docs, while the real module is plural: deepeval.benchmarks.tasks (Part 9 proves it).

1.6 The single-turn/multi-turn rule#

A dataset is either single-turn or multi-turn. Passing [Golden(...), ConversationalGolden(...)] to the constructor raises:

text
TypeError: You cannot add a multi-turn ConversationalGolden to a single-turn dataset. You can only add a Golden.

Trying to add a ConversationalGolden later raises a similar TypeError. This is deliberate rather than a missing feature. Single-turn metrics read input and actual_output; conversational metrics read a sequence of Turn objects plus scenario-level fields. Mixing them would make evaluate() guess which contract each row follows.

In practice, keep separate files and names, for example refunds.singleturn.v3.jsonl and refund_chats.multiturn.v2.jsonl. Your dataset card should say which evaluator contract each file implements. If a support intent has both a one-shot form and a conversational form, those are two related but distinct datasets, not two rows in one file.

1.7 Test cases in a dataset: useful, but not the source of truth#

add_test_case exists because some teams already have completed examples, imported from logs or another harness. It is also useful when migrating into DeepEval. But for regression evaluation the golden remains the source of truth. A completed LLMTestCase ties together input, reference and one observed answer; a golden keeps the first two and lets the third change.

The evalkit mapping is direct:

DeepEval evalkit / Module 10A concept
Golden EvalExample in evalkit/dataset.py: durable input, expected data, tags and provenance
ConversationalGolden A conversational dataset item: scenario, user model and hidden success condition
EvaluationDataset JSON/JSONL file evalkit JSONL dataset plus DatasetCard
additional_metadata tags plus provenance fields; use it for slice, source, generator, model and corpus version
generate-at-eval-time run_eval running the current task function over stable examples
test_cases export a run artifact, closer to Row records than to the dataset
evals_iterator the runner loop, with tracing integration owned by 10B.5

1.8 Cloud methods and local versioning#

push(alias, finalized=True, version=None), pull(alias, finalized=True, auto_convert_goldens_to_test_cases=False, public=False, version=None), queue(alias, goldens, print_response=True), update_golden, delete_golden, delete(alias), create_version(alias) and get_versions(alias) are Confident AI features. Without a key they fail closed with ValueError: No Confident API key found... before any network call, as the probe shows. finalized=False means goldens are not pulled until they are manually finalized on the platform; queue sends rows to an annotation queue. 10B.7 covers the platform and its data-handling questions.

Without the platform, use the filesystem pattern from 10A.2, 6.3:

text
evals/
  refunds.v3.jsonl
  refunds.v3.card.json
  refund_chats.v2.jsonl
  refund_chats.v2.card.json

Commit the data and card together. Never edit a version that has already produced a release decision; add v4 with a changelog. Include a content hash in the card or compute one in CI. For synthetic rows, record the generator model, DeepEval version, Synthesizer configuration, evolution weights, random seed policy and source corpus version in additional_metadata or the card. DeepEval will not do that governance work for you.


Part 2: The Synthesizer API, opened up#

Deep-dive

For the concepts behind synthetic data (what it is good for, where it fails, and how to keep it honest), see 10A.2, Parts 9 to 11; this part covers only how DeepEval's Synthesizer implements them.

2.1 What the Synthesizer is for#

The Synthesizer writes goldens for you. Given source contexts, documents, a scenario or existing goldens, it asks a generator model to write candidate inputs, critiques and rewrites them, optionally makes them harder through evolutions, optionally rewrites them into a consistent style, and optionally writes reference outputs or outcomes. It is DeepEval's packaged version of the generate, critique, rewrite and validate pipeline that 10A.2, Part 10 builds by hand.

That packaging is valuable, but the correct mental model is not "a dataset factory". It is "a proposal generator with provenance metadata". You still own filtering, deduplication, balancing, human review, dataset cards and acceptance decisions.

flowchart TD
    C["Contexts or documents"] --> I["Generate candidate inputs"]
    I --> Q["Critic scores clarity and answerability"]
    Q --> R["Rewrite weak inputs, then keep them"]
    R --> E["Evolve inputs by weighted type"]
    E --> ST["Optional style rewrite"]
    ST --> X["Optional expected output or outcome"]
    X --> G["Synthetic goldens plus provenance metadata"]

2.2 Constructor and keyless construction#

python
from deepeval.synthesizer import Synthesizer, Evolution, PromptEvolution
from deepeval.synthesizer.config import (
    FiltrationConfig,
    EvolutionConfig,
    StylingConfig,
    ConversationalStylingConfig,
    ContextConstructionConfig,
)
from fake_judge import FakeJudge

judge = FakeJudge()                      # keyless; any DeepEvalBaseLLM works here
synthesizer = Synthesizer(
    model=judge,                         # str or DeepEvalBaseLLM; None means the default judge
    async_mode=False,                    # default True
    max_concurrent=100,
    filtration_config=FiltrationConfig(critic_model=judge),
    evolution_config=EvolutionConfig(num_evolutions=1),
    styling_config=None,
    conversational_styling_config=None,
    cost_tracking=False,
)

model=None resolves the default DeepEval judge, which is an OpenAI model unless configured otherwise, so construction or first use needs a key. A keyless run must pass a DeepEvalBaseLLM such as FakeJudge. The same rule applies to the config objects: FiltrationConfig() and ContextConstructionConfig() call initialize_model(None) for their critic when critic_model is omitted. Pass the fake everywhere:

python
filtration = FiltrationConfig(critic_model=judge)
contexts = ContextConstructionConfig(critic_model=judge, embedder=fake_embedder)  # FakeEmbedder from 5.3

The verified signatures are:

Config Signature in 4.3.5 Controls
FiltrationConfig (synthetic_input_quality_threshold=0.5, max_quality_retries=3, critic_model=None) When the critic accepts an input, and how many critique/rewrite rounds are allowed
EvolutionConfig (num_evolutions=1, evolutions=<factory>) How many evolution rounds and the sampling weight of each evolution type
StylingConfig (scenario=None, task=None, input_format=None, expected_output_format=None) Single-turn input style and reference-output style
ConversationalStylingConfig (scenario_context=None, conversational_task=None, participant_roles=None, scenario_format=None, expected_outcome_format=None) Multi-turn scenario and outcome style
ContextConstructionConfig (embedder=None, critic_model=None, encoding=None, max_contexts_per_document=3, min_contexts_per_document=1, max_context_length=3, min_context_length=1, chunk_size=1024, chunk_overlap=0, context_quality_threshold=0.5, context_similarity_threshold=0.0, max_retries=3, allow_cross_file_contexts=False, target_files_per_context=None, max_files_per_context=3) Document chunking, embedding, context quality and neighbour grouping

chunk_size is in tokens, not characters, because document splitting uses LangChain's TokenTextSplitter.

2.3 The eight entry points#

Each synchronous method has an a_ async twin. The four single-turn methods produce Golden objects. Their conversational twins produce ConversationalGolden objects and use include_expected_outcome rather than include_expected_output.

Entry point Required input Reference it can write What it is best for
generate_goldens_from_contexts(contexts, include_expected_output=True, max_goldens_per_context=2, source_files=None, context_chunk_source_files=None, target_files_per_context=None) A list of lists of strings, each inner list one context expected_output RAG evals where you already control chunking and retrieval
generate_goldens_from_docs(document_paths, include_expected_output=True, max_goldens_per_context=2, context_construction_config=None) Files: .pdf, .txt, .docx, .md, .markdown, .mdx expected_output Cold-start question generation directly from a corpus
generate_goldens_from_scratch(num_goldens) StylingConfig with scenario, task and input_format none Inputs when there is no source text; labels must come from elsewhere
generate_goldens_from_goldens(goldens, max_goldens_per_golden=2, include_expected_output=True) Existing goldens expected_output when context exists Variations and expansion of a seed dataset
generate_conversational_goldens_from_contexts(contexts, include_expected_outcome=True, max_goldens_per_context=2, source_files=None, context_chunk_source_files=None, ...) Contexts expected_outcome Conversation scenarios grounded in policy or documentation
generate_conversational_goldens_from_docs(document_paths, include_expected_outcome=True, max_goldens_per_context=2, ...) Documents expected_outcome Document-grounded conversational eval scenarios
generate_conversational_goldens_from_scratch(num_goldens) ConversationalStylingConfig with scenario_context, conversational_task and participant_roles (else TypeError) none: no expected_outcome is ever written Scenario ideation without a corpus
generate_conversational_goldens_from_goldens(goldens, max_goldens_per_golden=2, include_expected_outcome=True) Existing conversational goldens expected_outcome Scenario variations

Source-only shortcuts (not on the docs pages): dataset.generate_goldens_from_contexts/docs/scratch(..., synthesizer=...) wrap the same calls and append to dataset.goldens. Pass your own synthesizer, or the default one needs a key. There are no goldens-based or conversational shortcuts in 4.3.5.

The outputs are also accumulated on synthesizer.synthetic_goldens or synthesizer.synthetic_conversational_goldens. synthesizer.save_as(file_type, directory, file_name=None, quiet=False) writes them as JSON, JSONL or CSV, and to_pandas() returns a DataFrame if pandas is installed.

Two boundaries are explicit in the documentation and verified in the outputs: the Synthesizer does not generate actual_output, and conversational synthesis does not generate turns. Actual outputs come from running your application; turns come from the ConversationSimulator or from imported real conversations. A third boundary is easy to miss: conversational goldens from scratch arrive with no expected_outcome, so the simulator's default stopping check has nothing to test and every one of them runs to the turn cap (7.4) until you write the outcomes.

2.4 deepeval generate: the CLI twin#

The package exposes the same machinery as a command:

bash
deepeval generate \
  --method contexts \
  --variation single-turn \
  --contexts-file contexts.json \
  --output-dir synthetic_data \
  --file-type jsonl \
  --max-goldens-per-context 2

The verified help in 4.3.5 includes --method docs|contexts|scratch|goldens, --variation single-turn|multi-turn, output options, --model, --async-mode/--sync-mode, --max-concurrent, --include-expected/--no-include-expected, --cost-tracking, --documents, --contexts-file, --goldens-file, --num-goldens, per-context and per-golden maxima, context construction settings, and all single-turn and multi-turn styling fields.

Output · real, trimmed from deepeval generate --help17 lines
Usage: deepeval generate [OPTIONS]

Generate synthetic goldens with the golden synthesizer.

*  --method      <docs|contexts|scratch|goldens>  Golden generation method to use. [required]
*  --variation   <single-turn|multi-turn>         Golden variation to generate. [required]
   --output-dir  <str>                            [default: ./synthetic_data]
   --file-type   <json|csv|jsonl>                 [default: json]
   --model       <str>                            Model to use for generation.
   --async-mode / --sync-mode                     [default: async-mode]
   --max-concurrent <int>                         [default: 100]
   --include-expected / --no-include-expected     [default: include-expected]
   --cost-tracking                                Print generation cost when supported.
   --documents <list[str]>                        Document path; repeatable.
   --contexts-file <path>                         JSON file shaped like [["chunk 1", "chunk 2"], ...].
   --goldens-file <path>                          Existing goldens file (.json, .csv, or .jsonl).
   --num-goldens <int>                            Number of goldens for --method scratch.

The CLI uses the configured default model. It is therefore not keyless in the course setup, which is why the Python API with an explicit model= is the teaching path. In production the CLI is convenient for a one-off generation job, but the Python API is easier to seed, capture prompts from and integrate into a review pipeline.

2.5 Cost tracking and what it does not measure#

cost_tracking=True prints an API cost only for native provider models whose prices DeepEval knows or can configure. With a custom DeepEvalBaseLLM, synthesizer.synthesis_cost is None, as the runnable probes show. Do not read that as "free". It means DeepEval cannot price your wrapper. For cost planning, count the calls by type and apply 10A.2, Part 18's arithmetic: generation, critique, rewrite, evolution, style, expected output, document quality scoring, and any validation pass you add yourself.


Part 3: The contexts pipeline, step by step#

Deep-dive

The concepts this pipeline implements (generate, critique, filter, evolve) are taught in 10A.2, Part 10 and Part 11; this part opens up DeepEval's version of them.

3.1 The reference implementation in a runnable probe#

generate_goldens_from_contexts is the best entry point for understanding the Synthesizer because it exposes every stage without document parsing. This probe deliberately scripts one vague input. The critic rejects it twice, DeepEval rewrites it twice, and the final golden is still kept with quality 0.3.

python
"""Lesson 10B.6: the Synthesizer contexts pipeline, opened up with FakeJudge."""
import json
import os
import random
import warnings
warnings.filterwarnings("ignore")
random.seed(0)

import netguard
from fake_judge import FakeJudge
from deepeval.synthesizer import Synthesizer, Evolution
from deepeval.synthesizer.config import EvolutionConfig, FiltrationConfig, StylingConfig

contexts = [
    [
        "Refunds are issued within 5 business days of approval.",
        "Refunds go back to the original payment method.",
    ],
    [
        "Standard shipping takes 3-5 business days.",
        "Express shipping costs $15 and arrives in 2 business days.",
    ],
]

judge = FakeJudge(script={
    "SyntheticDataList": [
        {"data": [{"input": "How long do refunds take?"}, {"input": "where money"}]},
        {"data": [{"input": "How fast is express shipping?"}, {"input": "What does express shipping cost?"}]},
    ],
    # First input passes. The vague input is scored low twice and rewritten twice.
    "InputFeedback": [
        {"score": 0.9, "feedback": "clear"},
        {"score": 0.2, "feedback": "too vague"},
        {"score": 0.3, "feedback": "still vague"},
        {"score": 0.8, "feedback": "clear"},
        {"score": 0.8, "feedback": "clear"},
    ],
    "RewrittenInput": [
        {"rewritten_input": "Where does my refund money go?"},
        {"rewritten_input": "Which payment method receives my refund?"},
    ],
    "SyntheticData": [
        {"input": "If a refund is approved on Friday, by which day should it arrive?"},
        {"input": "Compared with a card payment, where does a refund paid by gift card go?"},
        {"input": "If I need it in 2 days, is standard or express shipping the right choice?"},
        {"input": "How does the cost of express compare with standard shipping?"},
    ],
    "Response": [
        {"response": "If a refund is approved on Friday, by which day should it arrive?"},
        {"response": "Within 5 business days of approval, to the original payment method."},
        {"response": "Compared with a card payment, where does a refund paid by gift card go?"},
        {"response": "To the original payment method."},
        {"response": "If I need it in 2 days, is standard or express shipping the right choice?"},
        {"response": "Express; standard takes 3-5 business days."},
        {"response": "How does the cost of express compare with standard shipping?"},
        {"response": "Express costs $15; the context gives no standard price."},
    ],
})

synthesizer = Synthesizer(
    model=judge,
    async_mode=False,
    filtration_config=FiltrationConfig(
        critic_model=judge,
        synthetic_input_quality_threshold=0.5,
        max_quality_retries=2,
    ),
    evolution_config=EvolutionConfig(
        num_evolutions=1,
        evolutions={Evolution.REASONING: 0.5, Evolution.COMPARATIVE: 0.5},
    ),
    styling_config=StylingConfig(
        scenario="Customers of an online shop",
        task="Answer order questions from the supplied policy",
        input_format="One concise question",
        expected_output_format="One sentence",
    ),
)

goldens = synthesizer.generate_goldens_from_contexts(
    contexts=contexts,
    max_goldens_per_context=2,
    include_expected_output=True,
)

print("goldens:", len(goldens))
for golden in goldens:
    print(json.dumps({
        "input": golden.input,
        "expected_output": golden.expected_output,
        "context": golden.context,
        "metadata": golden.additional_metadata,
    }, default=str))
print("calls:", [name for name, _ in judge.calls])
print("synthesis_cost for a custom model:", synthesizer.synthesis_cost)

prompt_dir = "ran/prompts_synth"
os.makedirs(prompt_dir, exist_ok=True)
for i, (schema, prompt) in enumerate(judge.calls, 1):
    with open(os.path.join(prompt_dir, f"{i:02d}_{schema}.txt"), "w", encoding="utf-8") as fh:
        fh.write(str(prompt))
print("prompt files written:", len(judge.calls))
print("\nfirst generation prompt excerpt:")
print(judge.prompt(0)[:900])
print("\nfirst critic prompt excerpt:")
print(judge.prompt(1)[:700])
print("\nfirst evolution prompt excerpt:")
idx = [name for name, _ in judge.calls].index("Response")
print(judge.prompt(idx)[:850])
Output · real, trimmed46 lines
goldens: 4
{"input": "If a refund is approved on Friday, by which day should it arrive?", "expected_output": "Within 5 business days of approval, to the original payment method.", "context": ["Refunds are issued within 5 business days of approval.", " ...[trimmed]
{"input": "Compared with a card payment, where does a refund paid by gift card go?", "expected_output": "To the original payment method.", "context": ["Refunds are issued within 5 business days of approval.", "Refunds go back to the origina ...[trimmed]
{"input": "If I need it in 2 days, is standard or express shipping the right choice?", "expected_output": "Express; standard takes 3-5 business days.", "context": ["Standard shipping takes 3-5 business days.", "Express shipping costs $15 an ...[trimmed]
{"input": "How does the cost of express compare with standard shipping?", "expected_output": "Express costs $15; the context gives no standard price.", "context": ["Standard shipping takes 3-5 business days.", "Express shipping costs $15 an ...[trimmed]
calls: ['SyntheticDataList', 'InputFeedback', 'InputFeedback', 'RewrittenInput', 'InputFeedback', 'RewrittenInput', 'Response', 'SyntheticData', 'Response', 'Response', 'SyntheticData', 'Response', 'SyntheticDataList', 'InputFeedback', 'Inp ...[trimmed]
synthesis_cost for a custom model: None
prompt files written: 21

first generation prompt excerpt:
I want you act as a copywriter. Based on the given context, which is list of strings, please generate a list of JSON objects with a `input` key.
        The `input` can either be a question or a statement that can be addressed by the given context.

        **
        IMPORTANT: Please make sure to only return in JSON format, with the 'data' key as a list of JSON objects.
        You MUST TRY to generate 2 data points, unless the `input` is getting repetitive.

        Example context: ["Einstein won the Nobel Prize for his discovery of penicillin.", "Einstein won the Nobel Prize in 1968."]
        Example max goldens per context: 2
        Example JSON:
        {
            "data": [
                {
                    "input": "What was Einstein known for?"
                },
                {
                    "input": "Einstein was a smart guy huh"
                }

first critic prompt excerpt:
Evaluate the provided synthetic query (which may be a question, task, or instruction) for clarity and answerability, assuming sufficient domain knowledge. Use the following criteria to guide your assessment:

        1. **Self-Containment**: Can the query be understood and completed without needing additional context or external references not provided within the query itself? It should be self-sufficient, meaning it doesn't depend on specific d ...[trimmed]
        2. **Clear Objective**: Does the query clearly convey its intent? It should specify what information, action, or response is being requested, allowing for a direct and appropriate

first evolution prompt excerpt:
I want you to act as an input rewriter.
    Your object is the rewrite a given `input` and must be factually correct according to the supporting information in `Context`.
    You MUST complicate the given `Input` using the following method:
            1. If `Input` can be solved with just a few simple thinking processes, you can rewrite it to explicitly request multiple-step reasoning.
            2. `Rewritten Input` should require readers to make multiple logical connections or inferences.
            3. `Rewritten Input` should be concise and understandable by humans.
            4. `Rewritten Input` should not contain phrases like  'based on the provided context' or 'according to the context'.
            5. `Rewritten Input` must be fully answerable from information in `Context`.
            6. `Rewritten Input` should not contain
[netguard] total blocked attempts: 0 []

The exact call sequence is the most important line in the output. For two contexts and two goldens per context, DeepEval made 21 scripted model calls. The call names are schema names recorded by FakeJudge:

  • SyntheticDataList: generate candidate inputs for one context
  • InputFeedback: criticize one input
  • RewrittenInput: rewrite one weak input
  • Response: an evolution or an expected output, depending on prompt position
  • SyntheticData: a style rewrite of the evolved input

Because the fake records prompts as well as schemas, the probe also prints what DeepEval actually asked. This is the habit the whole track recommends: do not infer a metric or generator from its name; read its prompt.

3.2 Stage 1: candidate generation#

For each context, DeepEval makes one structured call with schema SyntheticDataList{data: [{input, used_source_files?}]}. The prompt begins:

text
I want you act as a copywriter. Based on the given context, which is list of strings,
please generate a list of JSON objects with a `input` key. The `input` can either be a
question or a statement that can be addressed by the given context.

It instructs the model to try to generate the requested number of data points, not to use prior knowledge, to take the context at face value, and to include at least one statement as an input. Two consequences follow:

  1. The generated inputs are only as grounded as the generator. Nothing in this stage proves answerability.
  2. Asking for statements as well as questions is useful for eval design. Real users make claims, issue instructions and paste fragments; not every input is a grammatically clean question.

The generation is per context. If you pass broad, heterogeneous chunks in one inner list, the model can write multi-hop inputs across them. If you want atomic fact questions, pass smaller contexts. This is the same stratification decision 10.2, 10.2 teaches; DeepEval does not choose the strata for you.

3.3 Filtration: the filter that never drops#

For each candidate input, the critic sees a prompt that asks for a score between 0 and 1 on two criteria:

  • Self-Containment: can the query be understood without unspecified external context?
  • Clear Objective: does the query convey what information, action or response is wanted?

If score >= synthetic_input_quality_threshold, the input passes. Otherwise DeepEval sends a rewrite prompt with the context, original query and critic feedback. It repeats the critique/rewrite loop up to max_quality_retries.

The verified behaviour is the trap: when retries are exhausted, the input is kept anyway. In the probe, the vague input "where money" receives 0.2, is rewritten, receives 0.3, is rewritten again, and the final golden records synthetic_input_quality: 0.3. There is no rejection list.

There is a second, subtler problem. The recorded quality score is the critic's score for the text before the last rewrite. DeepEval evolves and styles the input after that. The number is useful provenance, but it is not a validated quality score for the final golden.

3.4 Evolutions: what they are and where they came from#

After filtering, each input is evolved num_evolutions times. Each round samples one evolution type with random.choices(keys, weights) using the weights in EvolutionConfig.evolutions. The seven single-turn values are:

Evolution What the rewrite tries to do
Evolution.REASONING Require multi-step reasoning or several logical connections
Evolution.MULTI_CONTEXT Require information spread across multiple chunks in the context
Evolution.CONCRETIZING Make a general input more specific and concrete
Evolution.CONSTRAINED Add constraints or conditions the answer must satisfy
Evolution.COMPARATIVE Compare two or more entities, options or cases
Evolution.HYPOTHETICAL Ask about a hypothetical situation grounded in the context
Evolution.IN_BREADTH Create a related but broader or new-topic input

PromptEvolution has the same values except MULTI_CONTEXT; it is used when there is no context, such as generation from scratch or from context-free seed goldens. DeepEval's default weights are uniform: each of the seven context evolutions has weight 1/7.

The technique descends from Evol-Instruct and WizardLM: the documentation cites the WizardLM paper at https://arxiv.org/abs/2304.12244. In that lineage, "in-depth" rewrites complicate a prompt and "in-breadth" rewrites expand topical coverage. DeepEval turns the idea into evaluation-data generation. The benefit is difficulty and diversity. The risk is that it manufactures a distribution real users never produce.

The reasoning evolution prompt tells the model to complicate the input, keep it answerable from the context, avoid phrases such as "based on the provided context", and write no more than 15 words, "Use abbreviation wherever possible". The installed templates show that every one of the seven context evolutions, the six context-free ones and the conversational scenario evolutions carries the same 15-word ceiling. That constraint is a strong distributional distortion, and the abbreviation instruction adds another: a question compressed into "Refund ETA if appr. Fri?" tests abbreviation-reading as much as reasoning. Real production inputs include short fragments, long pasted logs, contradictory details and emotional language. A dataset dominated by 15-word multi-hop questions will over-test reasoning composition and under-test clarification, messiness and recovery.

There is no seed parameter on EvolutionConfig. The probes set Python's random.seed(...) before construction. In async mode, ordering and timing can still make exact reproduction hard. For a release dataset, record deepeval version, evolution weights, seed policy and the generated metadata rather than pretending the process is deterministic.

3.5 Styling#

If StylingConfig has input_format, scenario or task, DeepEval performs one style rewrite per evolved input, using schema SyntheticData. The prompt asks the model to rewrite the evolved input to fit the scenario, task and format. expected_output_format shapes the later expected-output request.

Styling is useful for consistency: all inputs become short customer questions, or all become instructions with one constraint. It is dangerous for the same reason. Uniform style is not realism. Use it when the test deliberately isolates a capability, not when the eval claims to represent production traffic.

3.6 Expected outputs are silver labels#

When include_expected_output=True, DeepEval makes one free-text call per final input. The prompt says, in substance: given the input, generate a concise response using supporting information in the context. The same generator family that wrote the input now writes the reference answer from the same context.

That is a silver label: useful, cheap and not ground truth. It can be wrong, incomplete, or biased towards the generator's interpretation. It can also agree too well with a system built on the same model family. 10A.2, 2.5 warns that synthetic inputs scale well while synthetic labels are the risk; 10A.2, Part 11 owns the validation machinery. DeepEval gives you the raw material, not the acceptance process.

For RAG datasets, consider whether you even want generated expected_output at this stage. Often the more defensible label is the source context plus human-reviewed answerable spans. A generated reference can then be a draft for a human editor, not the label of record.

3.7 Cost and call-count arithmetic#

The probe's 21 calls decompose as follows:

Stage Calls in the probe Rule of thumb
Candidate generation 2 1 per context
Initial/passing critique 5 1 per candidate, plus re-critiques after weak rewrites
Rewrite 2 0 to max_quality_retries per weak candidate
Evolution 4 num_evolutions per kept candidate
Style rewrite 4 1 per candidate when styling is configured
Expected output 4 1 per candidate when include_expected_output=True
Total 21 grows linearly with goldens, with extra retries for weak candidates

As a formula for the contexts path, with C contexts, k inputs per context (N = C × k candidates), r the mean number of rewrite rounds per candidate, E evolutions, and S and X equal to 1 when styling and expected outputs are on:

text
calls ≈ C                  candidate generation
      + N × (1 + r)        critiques: one first look, one after each rewrite
                           (minus one for each candidate that exhausts its retries)
      + N × r              rewrites
      + N × E              evolutions
      + N × S              style rewrites
      + N × X              expected outputs

The probe has C = 2, N = 4 and two rewrites on one candidate. The critique line counts five calls rather than six because the final rewrite is not critiqued again (that is why the recorded score is stale, 3.3): 2 + 5 + 2 + 4 + 4 + 4 = 21. The document path adds one ContextScore call per sampled chunk (up to n_contexts × max_retries) before any of this.

This is only the synthesis cost. It excludes document context construction (Part 5), human review, deduplication, faithfulness validation, evaluation runs and judge calibration. A cheap model for generation is not necessarily cheap end to end. Conversely, an expensive generator can be rational if it reduces human editing time, but you only know that if you measure edit distance or review time per accepted golden.

3.8 What the metadata does and does not tell you#

The synthetic goldens carry useful entries in additional_metadata:

  • evolutions: the evolution types applied
  • synthetic_input_quality: the last critic score before the final rewrite
  • context_source_files and used_source_files: file provenance when document paths or source-file mappings exist
  • context_quality: filled by document context construction, null for manually supplied contexts

Use these as provenance and filtering inputs. Do not treat them as validation results. evolutions tells you which transformation was requested, not whether the result is realistic. synthetic_input_quality is a critic opinion about clarity and answerability, not correctness. context_quality is a judge's mean score for clarity, depth, structure and relevance, not retrieval performance. The evaluation-hygiene fields 10A.2 requires, such as slice, split, source, licence, corpus version and review status, are still yours to add.


Part 4: Generating without documents: from scratch, from goldens and conversational#

For when generating inputs without source documents is a good idea at all, see 10A.2, 20.1.

The contexts pipeline of Part 3 is the full pass. The other entry points run subsets of it, and the differences matter because they decide what you can trust. This probe runs three of the remaining paths with scripted models and writes every prompt to ran/prompts_* so you can read them.

python
"""Lesson 10B.6: Synthesizer from scratch, from goldens, and conversational goldens."""
import json
import os
import random
import warnings
warnings.filterwarnings("ignore")
random.seed(3)

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import Golden
from deepeval.synthesizer import Synthesizer
from deepeval.synthesizer.config import StylingConfig


def dump_calls(judge, folder):
    os.makedirs(folder, exist_ok=True)
    for i, (schema, prompt) in enumerate(judge.calls, 1):
        with open(os.path.join(folder, f"{i:02d}_{schema}.txt"), "w", encoding="utf-8") as fh:
            fh.write(str(prompt))


print("== from scratch without the three required styling fields")
try:
    Synthesizer(model=FakeJudge(), async_mode=False).generate_goldens_from_scratch(num_goldens=2)
except Exception as exc:
    print(type(exc).__name__, str(exc))

print("\n== from scratch with styling")
scratch_judge = FakeJudge(script={
    "SyntheticDataList": [
        {"data": [{"input": "Is order 8 eligible for a refund?"}, {"input": "Cancel order 8"}]},
    ],
    "Response": [
        {"response": "If order 8 arrived damaged, is it eligible for a refund?"},
        {"response": "Can I cancel order 8 before it ships?"},
    ],
})
scratch = Synthesizer(
    model=scratch_judge,
    async_mode=False,
    styling_config=StylingConfig(
        scenario="Customers of an online shop",
        task="Answer order questions",
        input_format="Short question",
        expected_output_format="One sentence",
    ),
)
scratch_goldens = scratch.generate_goldens_from_scratch(num_goldens=2)
for golden in scratch_goldens:
    print(json.dumps({"input": golden.input, "expected_output": golden.expected_output, "metadata": golden.additional_metadata}, default=str))
print("calls:", [name for name, _ in scratch_judge.calls])
dump_calls(scratch_judge, "ran/prompts_scratch")

print("\n== from goldens with no context: infer the style, then use the scratch path")
golden_judge = FakeJudge(script={
    "PromptStyling": [
        {"scenario": "shop customers", "task": "order Q&A", "input_format": "short question"},
    ],
    "SyntheticDataList": [
        {"data": [{"input": "Where is order 5?"}, {"input": "Can I change the address for order 5?"}]},
    ],
    "Response": [
        {"response": "Which carrier is transporting order 5 now?"},
        {"response": "Before dispatch, can I change the address for order 5?"},
    ],
})
from_goldens = Synthesizer(model=golden_judge, async_mode=False)
new_goldens = from_goldens.generate_goldens_from_goldens(
    goldens=[Golden(input="Where is order 5?")],
    max_goldens_per_golden=2,
)
print("count:", len(new_goldens), "inputs:", [g.input for g in new_goldens])
print("calls:", [name for name, _ in golden_judge.calls])
dump_calls(golden_judge, "ran/prompts_from_goldens")

print("\n== conversational goldens from contexts")
conv_judge = FakeJudge(script={
    "ConversationalScenarioList": [
        {"data": [{"scenario": "A customer asks how long a refund takes after returning a damaged item."}]},
    ],
    "ScenarioFeedback": [
        {"score": 0.9, "feedback": "clear and answerable"},
    ],
    "Response": [
        {"response": "A customer whose replacement arrived damaged asks whether the refund clock restarted."},
        {"response": "The assistant explains the refund timeline and confirms when it starts."},
    ],
})
conv = Synthesizer(model=conv_judge, async_mode=False)
conv_goldens = conv.generate_conversational_goldens_from_contexts(
    contexts=[["Refunds are issued within 5 business days of approval."]],
    max_goldens_per_context=1,
)
for golden in conv_goldens:
    print(json.dumps(golden.model_dump(exclude_none=True), default=str)[:900])
print("calls:", [name for name, _ in conv_judge.calls])
dump_calls(conv_judge, "ran/prompts_conversational")
Output · real19 lines
== from scratch without the three required styling fields
TypeError `scenario`, `task`, and `input_format` in `styling_config` must not be None when generation goldens from scratch.

== from scratch with styling

{"input": "If order 8 arrived damaged, is it eligible for a refund?", "expected_output": null, "metadata": {"evolutions": ["Comparative"]}}
{"input": "Can I cancel order 8 before it ships?", "expected_output": null, "metadata": {"evolutions": ["Reasoning"]}}
calls: ['SyntheticDataList', 'Response', 'Response']

== from goldens with no context: infer the style, then use the scratch path

count: 2 inputs: ['Which carrier is transporting order 5 now?', 'Before dispatch, can I change the address for order 5?']
calls: ['PromptStyling', 'SyntheticDataList', 'Response', 'Response']

== conversational goldens from contexts

{"scenario": "A customer whose replacement arrived damaged asks whether the refund clock restarted.", "expected_outcome": "The assistant explains the refund timeline and confirms when it starts.", "context": ["Refunds are issued within 5 bu ...[trimmed]
calls: ['ConversationalScenarioList', 'ScenarioFeedback', 'Response', 'Response']
[netguard] total blocked attempts: 0 []

4.1 From scratch: inputs only, no critic, no labels#

generate_goldens_from_scratch(num_goldens) is for the cold-start case where you have a product description but no documents and no logs. It refuses to run unless StylingConfig has scenario, task and input_format (the first call in the output shows the TypeError). The pipeline is short: one SyntheticDataList call asking for num_goldens inputs in the described style, then the evolution rounds (calls named Response). The call list ['SyntheticDataList', 'Response', 'Response'] tells you what is missing:

  • No critic and no rewrite. The scratch path never calls InputFeedback, so there is no synthetic_input_quality in the metadata. The filtration config is irrelevant here.
  • No expected output. expected_output is None because there is no context to answer from. A reference answer must come from a person, a stronger process or a later step you design.
  • PromptEvolution instead of Evolution. With no context there is nothing to spread across, so Multi-context is dropped and the remaining six weights are used. The metadata shows Comparative and Reasoning being applied.

Use scratch generation for ideation: a first list of the kinds of things users might ask, to be reviewed, rewritten and replaced by real traffic as soon as you have some. Do not use it as a benchmark. Every input came from one model's idea of your users.

4.2 From goldens: expansion and the style-inference call#

generate_goldens_from_goldens(goldens, max_goldens_per_golden=2, include_expected_output=True) grows a seed set. Its routing depends on the seeds:

  1. If you did not pass a StylingConfig, DeepEval first makes one PromptStyling call that reads a random sample of up to ten seed inputs (random.sample, so seed it if you want the same inference twice) and infers a scenario, task and input format. This is a silent extra model call, and the inferred style is not written back for you to review. Pass your own StylingConfig when you care.
  2. Goldens that carry context are sent through the contexts pipeline of Part 3, with their context as the grounding.
  3. If no golden has context, the method falls back to the from-scratch path with len(goldens) * max_goldens_per_golden inputs. The second block of the output shows exactly that: calls ['PromptStyling', 'SyntheticDataList', 'Response', 'Response'] and no expected output.

The practical rule is that expanding seeds is only as good as the seeds. Ten inputs written by one team become sixty inputs with the same blind spots and a layer of generator style on top. The value of this path is paraphrase and difficulty variation around known intents, not coverage of intents you have not seen. Keep the seeds' id in the new goldens' metadata yourself if you want lineage, because the output does not link a child to its parent.

4.3 Conversational goldens: scenarios, not turns#

The generate_conversational_goldens_* family produces ConversationalGolden objects. The third block of the output shows a contexts-based run with calls ['ConversationalScenarioList', 'ScenarioFeedback', 'Response', 'Response']:

Call Purpose
ConversationalScenarioList Write candidate scenarios grounded in the context
ScenarioFeedback A critic scores the scenario, recorded as synthetic_scenario_quality
Response (first) One evolution round applied to the scenario
Response (second) The expected_outcome, written from the scenario and context

Compare with the single-turn pipeline. There is a critic score, recorded in additional_metadata as synthetic_scenario_quality for you to filter on. Is a low-scoring scenario dropped? The next probe scripts a critic that rejects every version of a vague scenario:

python
"""Lesson 10B.6: conversational scenarios get the same rewrite-and-keep filtration."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.synthesizer import Synthesizer
from deepeval.synthesizer.config import FiltrationConfig, EvolutionConfig

judge = FakeJudge(script={
    "ConversationalScenarioList": [{"data": [{"scenario": "refund thing"}]}],
    # The critic rejects every version of the scenario.
    "ScenarioFeedback": [{"score": 0.1, "feedback": "vague"}] * 3,
    "RewrittenScenario": [{"rewritten_scenario": "A customer asks about refund timing."}] * 2,
    "Response": [
        {"response": "A customer asks when a refund for a damaged item arrives."},
        {"response": "The assistant states that refunds take 5 business days."},
    ],
})
synthesizer = Synthesizer(
    model=judge,
    async_mode=False,
    filtration_config=FiltrationConfig(critic_model=judge, max_quality_retries=2),
    evolution_config=EvolutionConfig(num_evolutions=1),
)
goldens = synthesizer.generate_conversational_goldens_from_contexts(
    contexts=[["Refunds are issued within 5 business days of approval."]],
    max_goldens_per_context=1,
)
for golden in goldens:
    print("scenario:", golden.scenario)
    print("quality:", golden.additional_metadata["synthetic_scenario_quality"])
print("calls:", judge.schemas())
Output · real4 lines
scenario: A customer asks when a refund for a damaged item arrives.
quality: 0.1
calls: ['ConversationalScenarioList', 'ScenarioFeedback', 'RewrittenScenario', 'ScenarioFeedback', 'RewrittenScenario', 'Response', 'Response']
[netguard] total blocked attempts: 0 []

The scenario was critiqued twice, rewritten twice, evolved, and kept with quality 0.1: the same rewrite-and-keep behaviour as single-turn filtration (3.3). Enforce your own threshold on synthetic_scenario_quality. The result has scenario, expected_outcome, context and metadata, and no turns and no persona. You attach personas yourself, from a persona library you control, because persona choice is an experimental variable and should not be a side effect of a generator's mood. ConversationalStylingConfig shapes the scenarios (scenario_context, conversational_task, participant_roles, scenario_format) and the outcomes (expected_outcome_format).

The generated expected_outcome deserves more suspicion than a single-turn expected_output, because the simulator's default stopping controller (Part 7) will use it to decide when a conversation is over. A vague or over-easy outcome ends conversations early and flatters the app. A silver label that decides when the test stops is a label that moves the number.

4.4 Which passes each path runs#

Pass Contexts Docs Scratch Goldens (with context) Goldens (no context) Conversational contexts
Context construction (chunk, embed, score) no yes no no no no (docs variant: yes)
Candidate generation yes yes yes yes yes yes (scenarios)
Critic score and rewrite (keeps the last) yes yes no yes no yes
Evolution rounds yes yes yes yes yes yes
Style rewrite if configured if configured if configured if configured inferred or configured via conversational styling
Expected output or outcome optional optional never optional never optional

If you remember one thing from this table, remember the scratch and no-context columns: those datasets arrive with no references at all. They can drive reference-free metrics and human review queues. They cannot drive a reference-based metric until somebody supplies the labels.


Part 5: Generating from documents#

Why grounding generation in your own documents helps, and what it does not fix, is covered in 10A.2, 11.5 and Part 9.

generate_goldens_from_docs and its conversational twin add a front half to the contexts pipeline: DeepEval itself loads your files, splits them, embeds the chunks, scores them and groups neighbours into contexts. This is the most convenient entry point and the one with the most hidden machinery, so it gets its own part. All of the runs below used a fake embedder and the fake judge: no document text and no prompt ever left the machine.

5.1 Dependencies, formats and what runs where#

Document generation needs packages the core install does not bring: chromadb, langchain-core, langchain-community, langchain-text-splitters, and tiktoken. PDF and DOCX loading additionally need the LangChain loaders' own parsers (pypdf-style and docx2txt-style packages); those two formats were not run in this lesson, so check them in your environment before you plan around them. The supported extensions are .pdf, .txt, .docx, .md, .markdown and .mdx. Anything else raises ValueError: Unsupported file format.

The three embedded-model facts to know up front:

  • The embedder is a model. embedder=None resolves to OpenAI's text-embedding-3-small unless an Ollama, local or Azure embedding setting is active. Without a key, construction fails. Keyless, subclass DeepEvalBaseEmbeddingModel from deepeval.models and implement load_model, embed_text, a_embed_text, embed_texts, a_embed_texts and get_model_name.
  • The critic is a model. ContextConstructionConfig(critic_model=None) resolves the default judge, so pass your own when you want a specific model or the fake.
  • Chroma is used as a scratch database. DeepEval creates a temporary persistent Chroma collection, with Chroma telemetry off, and deletes it afterwards. The log line Successfully deleted: .../deepeval_chroma_... is that cleanup, not an error.

5.2 The algorithm in six steps#

From the installed source and the run in 5.3, generate_goldens_from_docs does this:

  1. Load each document with the LangChain loader for its extension.
  2. Split the text into chunks of chunk_size tokens (not characters or words), with chunk_overlap tokens of overlap, using a token splitter. The default is 1024 tokens with no overlap.
  3. Embed all chunks into the temporary Chroma collection.
  4. Choose seed chunks. Sample n_contexts * max_retries random chunks (or all of them if there are fewer), and score each with the critic. The score is ContextScore{clarity, depth, structure, relevance}, each from 0 to 1, and the quality is the mean of the four. A chunk is kept if its mean exceeds context_quality_threshold; after max_retries consecutive failures, the last one is kept anyway. This is the same keep-the-last-one behaviour as input filtration in 3.3.
  5. Expand into a context. For each seed chunk, query Chroma for its max_context_length nearest neighbours and add those whose similarity (1 - distance) is above context_similarity_threshold. The seed plus its neighbours is one context.
  6. Run the contexts pipeline of Part 3 on each context, and write context_quality into each golden's metadata.

Two consequences follow from the design. First, contexts are assembled from nearest neighbours in embedding space, so a context is "chunks that sound alike", not "a coherent section of the document". Second, because seeds are sampled at random, there is no coverage guarantee: a rarely sampled appendix can be absent from the dataset, and a popular section can be over-represented. DeepEval does not stratify by section; that is the stratification decision of 10.2, 10.2 that you must make before or after generation.

5.3 A keyless document run#

Prerequisite: run python -c "import tiktoken; tiktoken.get_encoding('gpt2')" once on a connected machine first (see 5.4). The sample below runs under netguard and otherwise stops at the tokenizer download.

The sample writes a 60-sentence policy file, shrinks chunk_size to 64 tokens so that a short file produces several chunks, and asks for two contexts of two chunks each. The ContextScore answers are scripted at clarity 0.9, depth 0.6, structure 0.8 and relevance 0.9.

python
"""Lesson 10B.6: generate_goldens_from_docs with a fake embedder and fake judge."""
import hashlib
import os
import random
import warnings
warnings.filterwarnings("ignore")
random.seed(1)

import netguard
from fake_judge import FakeJudge
from deepeval.models import DeepEvalBaseEmbeddingModel
from deepeval.synthesizer import Synthesizer
from deepeval.synthesizer.config import ContextConstructionConfig, FiltrationConfig, EvolutionConfig


class FakeEmbedder(DeepEvalBaseEmbeddingModel):
    """Deterministic embedding stand-in: a hash vector, no model and no key."""

    def __init__(self):
        super().__init__(model="fake-embedder")

    def load_model(self):
        return self

    def _vector(self, text):
        digest = hashlib.sha256(text.encode()).digest()
        return [byte / 255 for byte in digest[:16]]

    def embed_text(self, text):
        return self._vector(text)

    async def a_embed_text(self, text):
        return self._vector(text)

    def embed_texts(self, texts):
        return [self._vector(text) for text in texts]

    async def a_embed_texts(self, texts):
        return [self._vector(text) for text in texts]

    def get_model_name(self):
        return "fake-embedder"


os.makedirs("ran/docs_in", exist_ok=True)
with open("ran/docs_in/policy.txt", "w", encoding="utf-8") as fh:
    fh.write(("Refunds are issued within 5 business days. " * 30) + "\n\n" +
             ("Express shipping costs $15 and arrives in 2 days. " * 30))

judge = FakeJudge(script={
    "ContextScore": [
        {"clarity": 0.9, "depth": 0.6, "structure": 0.8, "relevance": 0.9},
    ] * 12,
    "SyntheticDataList": [
        {"data": [{"input": "How long do refunds take?"}]},
    ] * 8,
    "InputFeedback": [
        {"score": 0.9, "feedback": "clear"},
    ] * 8,
    "Response": [
        {"response": "After approval, how many business days does a refund take?"},
    ] * 8,
})

synthesizer = Synthesizer(
    model=judge,
    async_mode=False,
    filtration_config=FiltrationConfig(critic_model=judge),
    evolution_config=EvolutionConfig(num_evolutions=1),
)
try:
    goldens = synthesizer.generate_goldens_from_docs(
        document_paths=["ran/docs_in/policy.txt"],
        max_goldens_per_context=1,
        include_expected_output=False,
        context_construction_config=ContextConstructionConfig(
            embedder=FakeEmbedder(),
            critic_model=judge,
            chunk_size=64,
            chunk_overlap=0,
            max_contexts_per_document=2,
            max_context_length=2,
        ),
    )
    print("goldens:", len(goldens))
    for golden in goldens:
        print("input:", golden.input)
        print("context:", golden.context)
        print("metadata:", golden.additional_metadata)
except Exception as exc:
    print("ERROR", type(exc).__name__, str(exc)[:500])
print("calls:", [name for name, _ in judge.calls])

This run succeeded only because tiktoken's vocabulary files had been cached by one earlier public download (5.4 shows what happens without them).

Output · real, trimmed, ANSI codes removed12 lines
[Confident AI Synthesizer Log] SUCCESS: Successfully deleted: <tmp>/deepeval_chroma_fdjnq2go
[Confident AI Synthesizer Log] SUCCESS: Context Construction: Utilizing 3 out of 10 chunks.

goldens: 2
input: After approval, how many business days does a refund take?
context: ['Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are is ...[trimmed]
metadata: {'evolutions': ['Constrained'], 'synthetic_input_quality': 0.9, 'context_source_files': ['ran/docs_in/policy.txt'], 'used_source_files': [], 'context_quality': 0.7999999999999999}
input: After approval, how many business days does a refund take?
context: [' issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within 5 business days. Refunds are issued within ...[trimmed]
metadata: {'evolutions': ['Concretizing'], 'synthetic_input_quality': 0.9, 'context_source_files': ['ran/docs_in/policy.txt'], 'used_source_files': [], 'context_quality': 0.7999999999999999}
calls: ['ContextScore', 'ContextScore', 'SyntheticDataList', 'InputFeedback', 'Response', 'SyntheticDataList', 'InputFeedback', 'Response']
[netguard] total blocked attempts: 0 []

Read the output rather than the headline:

  • The context-construction log says "Utilizing 3 out of 10 chunks": ten chunks existed, and three were used.
  • context_quality is 0.8, which is the scripted mean of 0.9, 0.6, 0.8 and 0.9. It is the judge's opinion of the chunk's clarity, depth, structure and relevance, and it says nothing about whether the chunk is answerable or whether a retriever would find it.
  • Chunks split mid-word. The first context begins "Refunds are issued ... Refunds are" and the second begins " days. Refunds ...". Token splitting does not respect sentences, so a context can start or end mid-sentence. For real documents, consider pre-chunking by headings and using generate_goldens_from_contexts so that you control the boundaries, or raise chunk_size and inspect a sample.
  • The call list shows two ContextScore calls and then two full pipelines of SyntheticDataList, InputFeedback, Response. With include_expected_output=False there is no expected-output call.
  • The used_source_files list is empty and context_source_files names the file: for a single document you get provenance, and for a multi-document run you get the file each chunk came from.

5.4 The tiktoken first-download trap#

The first attempt to run this sample on a machine with the network blocked failed:

text
[netguard] BLOCKED DNS openaipublic.blob.core.windows.net
[Confident AI Synthesizer Log] SUCCESS: Successfully deleted: <tmp>/deepeval_chroma_tianzkx2
ERROR ConnectionError HTTPSConnectionPool(host='openaipublic.blob.core.windows.net', port=443): Max retries exceeded with url: /gpt-2/encodings/main/vocab.bpe (Caused by NameResolutionError("HTTPSConnection(host='openaipublic.blob.core.wind ...[trimmed]
calls: []
[netguard] total blocked attempts: 1 ['openaipublic.blob.core.windows.net']

The cause is not DeepEval's code. The token splitter loads the tiktoken gpt2 encoding, and tiktoken downloads that vocabulary file from openaipublic.blob.core.windows.net the first time it is needed, then caches it. The download needs no API key, only network access. The DeepEval documentation does not mention it, so a first run inside a locked-down CI runner, an air-gapped machine or a container with no egress fails with a ConnectionError that looks like a DeepEval bug.

Three fixes, in order of preference:

  1. Pre-warm the cache once on a connected machine. Set TIKTOKEN_CACHE_DIR=/path/to/cache, run any tiktoken.get_encoding("gpt2"), and ship the folder with your image or CI cache. Two files appear (about 456 KB and 1 MB), each named by the SHA-1 hash of its source URL: 6d1cbeee... is vocab.bpe and 6c7ea1a7... is encoder.json, as a pre-warm run for this lesson confirmed. Without the variable, tiktoken caches under the system temporary folder (data-gym-cache), which a reboot or a temp-cleaning job can empty, so a run that worked yesterday can fail today.
  2. Mount the cache into CI and set the same environment variable.
  3. Avoid the splitter. Chunk the documents yourself with a splitter of your choice and call generate_goldens_from_contexts. This also removes the mid-word chunking problem above.

5.5 The over-generation crash#

A model asked for one input per context can return two. The probe below scripts exactly that: max_goldens_per_context=1, a candidate list of two.

python
"""Lesson 10B.6: the sync over-generation bug in generate_goldens_from_contexts."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.synthesizer import Synthesizer
from deepeval.synthesizer.config import FiltrationConfig, EvolutionConfig

judge = FakeJudge(script={
    "SyntheticDataList": [
        {"data": [{"input": "How long do refunds take?"}, {"input": "Where does the refund go?"}]},
    ],
    "InputFeedback": [
        {"score": 0.9, "feedback": "clear"},
        {"score": 0.9, "feedback": "clear"},
    ],
    "Response": [
        {"response": "After approval, how many business days does a refund take?"},
        {"response": "Which payment method receives the refund?"},
    ],
})
synthesizer = Synthesizer(
    model=judge,
    async_mode=False,
    filtration_config=FiltrationConfig(critic_model=judge),
    evolution_config=EvolutionConfig(num_evolutions=1),
)
try:
    synthesizer.generate_goldens_from_contexts(
        contexts=[["Refunds are issued within 5 business days."]],
        max_goldens_per_context=1,
        include_expected_output=False,
    )
    print("unexpected success")
except Exception as exc:
    print("raised:", type(exc).__name__, str(exc))
print("calls:", [name for name, _ in judge.calls])
Output · real, trimmed3 lines
raised: IndexError list index out of range
calls: ['SyntheticDataList', 'InputFeedback', 'InputFeedback', 'Response']
[netguard] total blocked attempts: 0 []

In 4.3.5 (and still in 4.3.6) the synchronous path crashes with IndexError: list index out of range instead of truncating the list, and all work in the batch is lost. The source line indexes a per-input progress bar array that was sized for the requested count. Real models do over-generate, particularly when the prompt says "try to generate the requested number", as Part 3's prompt does.

Defences, none of which DeepEval gives you for free:

  • Generate in small batches and write each batch to disk, so a crash costs one batch and not an hour of calls.
  • Wrap the call and retry the failed batch with a lower max_goldens_per_context, or use async mode, which takes a different code path and handles the same over-generation differently (shown after this list).
  • Use a model that reliably follows counts, and put the requested count in your StylingConfig where the format field allows it.
  • Pin and re-test. Record the DeepEval version; re-run the over-generation probe when you upgrade, because this is the kind of bug that gets fixed without a changelog line.

The same script with async_mode=True:

python
"""Lesson 10B.6: the same over-generation in async mode is truncated, not crashed."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.synthesizer import Synthesizer
from deepeval.synthesizer.config import FiltrationConfig, EvolutionConfig

judge = FakeJudge(script={
    "SyntheticDataList": [
        {"data": [{"input": "How long do refunds take?"}, {"input": "Where does the refund go?"}]},
    ],
    "InputFeedback": [{"score": 0.9, "feedback": "clear"}] * 2,
    "Response": [
        {"response": "After approval, how many business days does a refund take?"},
        {"response": "Which payment method receives the refund?"},
    ],
})
synthesizer = Synthesizer(
    model=judge,
    async_mode=True,  # the only change from synthesizer_overgeneration.py
    filtration_config=FiltrationConfig(critic_model=judge),
    evolution_config=EvolutionConfig(num_evolutions=1),
)
goldens = synthesizer.generate_goldens_from_contexts(
    contexts=[["Refunds are issued within 5 business days."]],
    max_goldens_per_context=1,
    include_expected_output=False,
)
print("goldens:", [golden.input for golden in goldens])
print("calls:", judge.schemas())
Output · real, trimmed3 lines
goldens: ['After approval, how many business days does a refund take?']
calls: ['SyntheticDataList', 'InputFeedback', 'Response']
[netguard] total blocked attempts: 0 []

The async path truncates the candidate list to the requested count: one critique, one evolution, one golden, and the second input is dropped without a warning. That is safer than a crash, and it is also silent data loss. If the dropped inputs matter (they may be the more interesting ones), ask for the number you want and dedupe afterwards rather than relying on either behaviour.

5.6 Cross-file contexts, and what this lesson did not run#

ContextConstructionConfig also has allow_cross_file_contexts, target_files_per_context and max_files_per_context. They let neighbour expansion pull chunks from several documents into one context, which is how you would generate multi-document questions. They were read in the source but not exercised here, and neither were PDF or DOCX loading, async document synthesis, or a real embedding model. Treat those as unverified until you run the same netguard-and-fake approach on your own files.

5.7 Reviewing a document-generated batch#

When the first batch arrives, review in this order before looking at a single question:

  1. Chunk sanity. Print five random contexts. Do they start mid-word? Are tables, code or headers mangled? If yes, change the chunking before generating more.
  2. Coverage. Count goldens per context_source_files value and per heading. A flat distribution is not required; a missing document or section is a finding.
  3. Context quality distribution. Histogram context_quality. A pile at exactly the threshold hints at the keep-the-last-one behaviour.
  4. Then questions. Read twenty. Mark each answerable, ambiguous or unanswerable, and compute the rate. If the unanswerable rate is above what you can tolerate, filter harder (Part 6) or adjust the prompt styling.

Part 6: Methodology: making synthetic goldens trustworthy#

The full methodology (silver labels, self-preference, homogeneity, leakage, filtering, deduplication and human review) is taught in 10A.2, Parts 9 to 11; this part maps it onto DeepEval.

Everything in Parts 2 to 5 produces proposals. This part is the acceptance process you wrap around them. It maps DeepEval's behaviour onto the rules of 10A.2, Part 11 and 10A.2, 2.5 and 3.5, and does not re-teach them.

6.1 The failure modes, in the order they bite#

Failure mode How DeepEval's pipeline produces it What to do
Silver labels The reference is written by the generator model from the same context that produced the question Treat expected_output as a draft; sample and review; keep the label's provenance
Self-preference Generator, critic and your judge are the same model family Use a different family for the generator than for the judge (10A.4, 4.4)
Homogeneity One model, one prompt family, random seeds Dedup and measure diversity (6.3); stratify seeds
Lexical leakage Questions copy rare words from the chunk, so lexical retrievers find them too easily Check overlap with the context; rewrite or filter (10A.2, 10.8)
Unanswerable items Nothing checks the question against the context Run an answerability or faithfulness check (6.2)
Distribution distortion Evolutions cap length at 15 words and push towards multi-hop phrasing; styling flattens variety Compare lengths and forms with real traffic; weight evolutions deliberately
Unmeasured quality Critic score is for the pre-rewrite text; context quality is a judge's opinion Never use these as acceptance evidence on their own
Silent drift New DeepEval versions change prompts; models change Version the generator settings with the data

6.2 The filter you must write yourself#

DeepEval's filtration rewrites and keeps (3.3), so acceptance has to be a separate step. The sample applies two gates to three hand-built goldens that look like synthesizer output: first the recorded critic score, then a faithfulness check that the expected_output is supported by the golden's own context. The faithfulness judge is the scripted FakeJudge, so the verdicts here demonstrate the plumbing, not a real judge's accuracy.

python
"""Lesson 10B.6: DeepEval does not filter synthetic goldens, so filter them yourself."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import Golden
from deepeval.metrics import FaithfulnessMetric
from deepeval.test_case import LLMTestCase

context = [
    "Refunds are issued within 5 business days of approval.",
    "Refunds go back to the original payment method.",
]
goldens = [
    Golden(
        input="How long does a refund take?",
        expected_output="Within 5 business days of approval.",
        context=context,
        additional_metadata={"synthetic_input_quality": 0.9},
    ),
    Golden(
        input="where money",
        expected_output="To the original payment method.",
        context=context,
        additional_metadata={"synthetic_input_quality": 0.3},
    ),
    Golden(
        input="Where does a refund go?",
        expected_output="Always to a gift card, even for card payments.",
        context=context,
        additional_metadata={"synthetic_input_quality": 0.8},
    ),
]

quality_kept = [
    golden for golden in goldens
    if (golden.additional_metadata or {}).get("synthetic_input_quality", 0) >= 0.5
]
print("after quality filter:", [golden.input for golden in quality_kept])

judge = FakeJudge(script={
    "Truths": [
        {"truths": ["Refunds are issued within 5 business days of approval.", "Refunds go back to the original payment method."]},
        {"truths": ["Refunds are issued within 5 business days of approval.", "Refunds go back to the original payment method."]},
    ],
    "Claims": [
        {"claims": ["The refund arrives within 5 business days of approval."]},
        {"claims": ["The refund always goes to a gift card."]},
    ],
    "Verdicts": [
        {"verdicts": [{"verdict": "yes", "reason": "directly supported"}]},
        {"verdicts": [{"verdict": "no", "reason": "the context says original payment method, not always gift card"}]},
    ],
})
metric = FaithfulnessMetric(model=judge, async_mode=False, include_reason=False, penalize_ambiguous_claims=True)
accepted = []
for golden in quality_kept:
    case = LLMTestCase(
        input=golden.input,
        actual_output=golden.expected_output,
        retrieval_context=golden.context,
    )
    metric.measure(case, _show_indicator=False)
    print(golden.input, "faithfulness:", metric.score)
    if metric.score >= 1.0:
        accepted.append(golden)
print("accepted after both filters:", [golden.input for golden in accepted])
print("judge calls:", [name for name, _ in judge.calls])
Output · real6 lines
after quality filter: ['How long does a refund take?', 'Where does a refund go?']
How long does a refund take? faithfulness: 1.0
Where does a refund go? faithfulness: 0.0
accepted after both filters: ['How long does a refund take?']
judge calls: ['Truths', 'Claims', 'Verdicts', 'Truths', 'Claims', 'Verdicts']
[netguard] total blocked attempts: 0 []

The two gates catch different defects. The quality gate removed "where money", a fragment a real user might type but which cannot be answered unambiguously. The faithfulness gate removed "Where does a refund go?" whose generated answer, "always to a gift card", contradicts the context. Neither gate alone suffices, and neither replaces a human reading the survivors. In production, choose a faithfulness judge from a different family than the generator, and calibrate it the way 10A.5 describes before trusting its acceptance rate.

6.3 Deduplication and the diversity audit#

Generated batches contain near-duplicates, and seed expansion produces more. The sample audits six synthetic-looking inputs with the standard library only, using a deliberately simple lexical check: normalize word order, then compare with difflib. The point is the shape of the audit, not the algorithm.

python
"""Lesson 10B.6: audit a batch of synthetic goldens for near-duplicates, length and evolution mix."""
from collections import Counter
from difflib import SequenceMatcher

from deepeval.dataset import Golden

goldens = [
    Golden(input="How long does a refund take after approval?", additional_metadata={"evolutions": ["Concretizing"]}),
    Golden(input="After approval, how long does a refund take?", additional_metadata={"evolutions": ["Reasoning"]}),
    Golden(input="Which payment method receives the refund?", additional_metadata={"evolutions": ["Constrained"]}),
    Golden(input="Compare express and standard shipping costs.", additional_metadata={"evolutions": ["Comparative"]}),
    Golden(input="What if my refund is approved on a public holiday?", additional_metadata={"evolutions": ["Hypothetical"]}),
    Golden(input="How long does a refund take once it is approved?", additional_metadata={"evolutions": ["Concretizing"]}),
]


def normalize(text):
    return " ".join(sorted(text.lower().replace("?", "").split()))


def near_duplicates(items, threshold=0.8):
    pairs = []
    for i in range(len(items)):
        for j in range(i + 1, len(items)):
            ratio = SequenceMatcher(None, normalize(items[i].input), normalize(items[j].input)).ratio()
            if ratio >= threshold:
                pairs.append((i, j, round(ratio, 2)))
    return pairs


pairs = near_duplicates(goldens)
print("near-duplicate pairs (index, index, similarity):", pairs)
drop = {j for _, j, _ in pairs}
kept = [g for k, g in enumerate(goldens) if k not in drop]
print("kept", len(kept), "of", len(goldens))

mix = Counter(e for g in kept for e in g.additional_metadata["evolutions"])
print("evolution mix after dedup:", dict(mix))
lengths = [len(g.input.split()) for g in kept]
print("input word counts:", lengths, "| mean", round(sum(lengths) / len(lengths), 1))
Output · real4 lines
near-duplicate pairs (index, index, similarity): [(0, 1, 0.99)]
kept 5 of 6
evolution mix after dedup: {'Concretizing': 2, 'Constrained': 1, 'Comparative': 1, 'Hypothetical': 1}
input word counts: [8, 6, 6, 10, 10] | mean 8.0

The audit caught the reordered pair ("how long does a refund take after approval" against "after approval, how long does a refund take") and kept one of them. It did not catch the paraphrase "How long does a refund take once it is approved?", which is the same intent in different words and survives into the dataset: lexical dedup removes only the cheapest duplicates. Real dedup needs embedding similarity or clustering with a threshold you tune by eye, as in 10A.2, 11.2 and 10A.2, 6.5. The sample then prints the evolution mix and the input length distribution, two numbers you should compare with your intended coverage and with real traffic. If every input is 8 to 10 words and the mix is dominated by one evolution, you have measured the generator, not your users.

6.4 Human review and acceptance sampling#

DeepEval's documentation says to inspect and edit synthetic data manually where possible. Make that a procedure:

  1. Review a random sample, not the head of the file. Twenty items per slice is a start; see 10A.2, 5.4 for sizes.
  2. Record the verdicts (accept, edit, reject, with a reason code such as unanswerable, wrong label, duplicate, unrealistic) in additional_metadata or a review file.
  3. Compute the reject rate and set a stopping rule. If more than a tolerable fraction of the sample is rejected, change the generator settings and regenerate rather than reviewing everything by hand.
  4. Measure edit effort. Time per accepted golden, or edit distance between the generated and final reference, is the true cost of synthetic data. Without it you cannot compare model choices.
  5. Freeze and card. Write the dataset card: source corpus version, DeepEval version, generator and critic models, Synthesizer configuration, evolution weights, seed policy, filters applied, reviewer and date, reject rate. 10A.2, 1.5 lists the fields.

6.5 The methodology box: DeepEval against the course#

Concern DeepEval gives you You still add Course reference
Question generation from chunks generate_goldens_from_contexts and _docs Chunk strategy, stratification 10A.2, Part 10
Quality critique A critic score recorded in metadata Hard acceptance filter 10A.2, Part 11
Difficulty and variety Seven evolutions with weights Difficulty rating, real-distribution comparison 10A.2, 14.3
Reference answers One generated expected_output Verification and human edit 10A.2, 2.5
Dedup and diversity Nothing Embedding dedup and diversity measurement 10A.2, 11.2 and 15.5
Dataset card and versioning JSON, JSONL and CSV writers Card, hash, immutability 10A.2, 1.5 and 6.3
Contamination and splits Nothing Dev, calibration and test splits; decontamination 10A.2, 6.1 and 6.2
Cost planning Per-call cost for known providers Whole-pipeline arithmetic 10A.2, Part 18

DeepEval packages the cheap, repeatable generation half of 10A.2. The trust half is yours.


Part 7: The ConversationSimulator#

Single-turn goldens test one exchange. Chatbots, support agents and copilots fail across turns: they forget, contradict themselves, never close the loop, or get talked into something. Testing that needs conversations, and real conversations are expensive, private and not repeatable. The ConversationSimulator produces them: it plays the user with a model, calls your application for each reply, and stops when a rule says to. The output is a list of ConversationalTestCase objects that the conversation metrics of 10B.4, Part 6 can score. This is the packaged form of the two-model pattern in 10A.2, Part 13 and 10A.7, 6.1.

flowchart TD
    CG["ConversationalGolden: scenario, outcome, persona"] --> SU["Simulator model writes user turn"]
    SU --> CB["Your model_callback runs the assistant"]
    CB --> SC{"Stopping controller"}
    SC -- "proceed" --> SU
    SC -- "end" --> TC["ConversationalTestCase"]
    TC --> CM["Conversational metrics"]
    CM --> REP["Score under this simulator version"]

7.1 The lab file#

One file exercises every behaviour in this part with scripted models: the default stopping check (Run A), a custom stopping controller (Run B), a simulation graph with an edge router (Run C), a golden with no expected outcome (Run D), and a conversation metric on the result. The scripted "assistant" is a deterministic function; the scripted "user" and "completion checker" are FakeJudge answers. Every prompt the simulator model received is written to ran/prompts_sim_*.

python
"""Lesson 10B.6: ConversationSimulator with a scripted app and scripted simulated user."""
import os
import warnings
warnings.filterwarnings("ignore")
from typing import List

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import ConversationalGolden, Persona
from deepeval.simulator import ConversationSimulator, SimulationNode
from deepeval.simulator.controller import end, proceed
from deepeval.test_case import Turn
from deepeval.metrics import ConversationCompletenessMetric


def support_callback(input: str, turns: List[Turn], thread_id: str) -> Turn:
    """A deterministic stand-in for the assistant under test."""
    if "refund" in input.lower() and "1234" in input:
        return Turn(role="assistant", content="I've issued a refund for order 1234. Confirmation number R-77.")
    return Turn(role="assistant", content="Could you share your order number?")


golden = ConversationalGolden(
    scenario="A customer whose order 1234 arrived broken wants a refund.",
    expected_outcome="The assistant issues a refund and gives a confirmation number.",
    persona=Persona(name="Sam", characteristics="Polite but brief; writes short messages."),
)


def dump_calls(judge, folder):
    os.makedirs(folder, exist_ok=True)
    for i, (schema, prompt) in enumerate(judge.calls, 1):
        with open(os.path.join(folder, f"{i:02d}_{schema}.txt"), "w", encoding="utf-8") as fh:
            fh.write(str(prompt))


print("== Run A: default stopping by the expected-outcome checker")
sim_model = FakeJudge(script={
    "SimulatedInput": [
        {"simulated_input": "Hi, my order arrived broken."},
        {"simulated_input": "It's order 1234, I want a refund please."},
    ],
    "ConversationCompletion": [
        {"is_complete": False, "reason": "no refund yet"},
        {"is_complete": True, "reason": "refund issued with confirmation"},
    ],
})
simulator = ConversationSimulator(model_callback=support_callback, simulator_model=sim_model, async_mode=False)
cases = simulator.simulate(
    conversational_goldens=[golden],
    max_user_simulations=5,
    on_simulation_complete=lambda case, index: print(f"hook: golden {index} finished with {len(case.turns)} turns"),
)
case = cases[0]
for turn in case.turns:
    print(f"{turn.role}: {turn.content}")
print("scenario:", case.scenario)
print("expected_outcome:", case.expected_outcome)
print("user_description:", case.user_description)
print("calls:", [name for name, _ in sim_model.calls])
dump_calls(sim_model, "ran/prompts_sim_default")

print("\n== Run B: a custom stopping controller")
def stop_when_confirmed(last_assistant_turn, simulated_user_turns):
    if last_assistant_turn and "confirmation number" in last_assistant_turn.content.lower():
        return end(reason="confirmation given")
    return proceed()

sim_model_b = FakeJudge(script={
    "SimulatedInput": [
        {"simulated_input": "hello"},
        {"simulated_input": "refund for 1234 please"},
        {"simulated_input": "unused scripted turn"},
    ],
})
simulator_b = ConversationSimulator(
    model_callback=support_callback,
    simulator_model=sim_model_b,
    stopping_controller=stop_when_confirmed,
    async_mode=False,
)
case_b = simulator_b.simulate(conversational_goldens=[golden], max_user_simulations=3)[0]
print("turns:", [(turn.role, turn.content) for turn in case_b.turns])
print("calls:", [name for name, _ in sim_model_b.calls])

print("\n== Run C: a simulation graph with deterministic actions and an LLM edge router")
root = SimulationNode(action=lambda: "Hi, I'd like a refund for order 1234.", name="ask")
push = SimulationNode(action=lambda: "That is not acceptable.", name="push", max_visits=2)
done = SimulationNode(action=lambda: "Thanks, bye.", name="done", terminal=True)
root.add_node(done, when="The assistant approved the refund")
root.add_node(push, when="The assistant refused")
sim_model_c = FakeJudge(script={
    "EdgeChoice": [
        {"index": 1, "reason": "the reply approved the refund"},
    ],
})
simulator_c = ConversationSimulator(
    model_callback=support_callback,
    simulator_model=sim_model_c,
    simulation_graph=root,
    stopping_controller=lambda: proceed(),
    async_mode=False,
)
case_c = simulator_c.simulate(
    conversational_goldens=[ConversationalGolden(scenario="refund")],
    max_user_simulations=5,
)[0]
print("turns:", [(turn.role, turn.content) for turn in case_c.turns])
print("calls:", [name for name, _ in sim_model_c.calls])
dump_calls(sim_model_c, "ran/prompts_sim_graph")

print("\n== Run D: no expected_outcome means no stop-check call and the cap decides")
no_outcome = ConversationalGolden(scenario="A customer asks about a refund.")
sim_model_d = FakeJudge(script={
    "SimulatedInput": [
        {"simulated_input": "hello"},
        {"simulated_input": "refund for 1234 please"},
    ],
})
simulator_d = ConversationSimulator(model_callback=support_callback, simulator_model=sim_model_d, async_mode=False)
case_d = simulator_d.simulate(conversational_goldens=[no_outcome], max_user_simulations=2)[0]
print("turn count:", len(case_d.turns), "user turns:", sum(1 for turn in case_d.turns if turn.role == "user"))
print("calls:", [name for name, _ in sim_model_d.calls])

print("\n== Feed the simulated conversation to a conversational metric")
metric_judge = FakeJudge(script={
    "UserIntentions": [
        {"intentions": ["get a refund for broken order 1234"]},
    ],
    "ConversationCompletenessVerdict": [
        {"verdict": "yes"},
    ],
    "ConversationCompletenessScoreReason": [
        {"reason": "The refund intention was satisfied."},
    ],
})
metric = ConversationCompletenessMetric(model=metric_judge, async_mode=False)
metric.measure(case, _show_indicator=False)
print("ConversationCompleteness:", metric.score)
print("reason:", metric.reason)
print("calls:", [name for name, _ in metric_judge.calls])
dump_calls(metric_judge, "ran/prompts_sim_metric")
Output · real, trimmed; progress-bar redraws removed31 lines
== Run A: default stopping by the expected-outcome checker
hook: golden 0 finished with 4 turns

user: Hi, my order arrived broken.
assistant: Could you share your order number?
user: It's order 1234, I want a refund please.
assistant: I've issued a refund for order 1234. Confirmation number R-77.
scenario: A customer whose order 1234 arrived broken wants a refund.
expected_outcome: The assistant issues a refund and gives a confirmation number.
user_description: Polite but brief; writes short messages.
calls: ['SimulatedInput', 'ConversationCompletion', 'SimulatedInput', 'ConversationCompletion']

== Run B: a custom stopping controller

turns: [('user', 'hello'), ('assistant', 'Could you share your order number?'), ('user', 'refund for 1234 please'), ('assistant', "I've issued a refund for order 1234. Confirmation number R-77.")]
calls: ['SimulatedInput', 'SimulatedInput']

== Run C: a simulation graph with deterministic actions and an LLM edge router
turns: [('user', "Hi, I'd like a refund for order 1234."), ('assistant', "I've issued a refund for order 1234. Confirmation number R-77."), ('user', 'Thanks, bye.'), ('assistant', 'Could you share your order number?')]
calls: ['EdgeChoice']

== Run D: no expected_outcome means no stop-check call and the cap decides

turn count: 4 user turns: 2
calls: ['SimulatedInput', 'SimulatedInput']

== Feed the simulated conversation to a conversational metric
ConversationCompleteness: 1.0
reason: The refund intention was satisfied.
calls: ['UserIntentions', 'ConversationCompletenessVerdict', 'ConversationCompletenessScoreReason']
[netguard] total blocked attempts: 0 []

7.2 Signature and the callback contract#

text
ConversationSimulator(
    model_callback=None,        # your assistant; required for text simulation
    simulation_graph=None,      # optional SimulationNode graph (7.6)
    stopping_controller=...,    # default checks the expected outcome (7.4)
    simulator_model=None,       # the model that plays the user
    max_concurrent=5,
    async_mode=True,
    language="English",
    voice_config=None,          # voice mode replaces model_callback
)

simulator.simulate(
    conversational_goldens,                 # list[ConversationalGolden]
    max_user_simulations=10,                # cap on user turns per conversation
    on_simulation_complete=None,            # (test_case, index) per finished conversation
    on_turn=None,                           # (turns, index) after each turn
) -> list[ConversationalTestCase]

A deprecated controller= keyword is still accepted as an alias of stopping_controller, with a DeprecationWarning. simulator_model=None resolves the default judge model, which needs a key, so a keyless run passes a fake. Voice simulation (voice_config) needs speech providers and is outside this lesson; DeepEval documents that giving both a callback and a voice config is an error.

The callback is your application seen from the simulator's side. DeepEval fills its arguments by name, so you declare only what you need:

Argument What you get When to declare it
input The latest simulated user message (a string) Always
turns The history so far, including that user message, as list[Turn] When your app is stateless and you replay history each call
thread_id A stable id for this conversation When your app keeps server-side session state keyed by thread

It returns a Turn(role="assistant", content=...). It may be sync or async. The probe used a sync callback with async_mode=False.

Think about what the callback must do for the test to mean anything. If your production app takes a session id, the callback should create one session per thread_id, not one for the whole run, or concurrent simulated users will share memory and corrupt each other's conversations. If your app calls tools or retrieves context, put those in the Turn (tools_called, retrieval_context), because the conversation metrics and the Turn RAG metrics read them. A callback that returns bare text silently makes every tool and retrieval metric inapplicable.

7.3 Goldens, personas and what the simulated user is told#

A ConversationalGolden (1.3) supplies the scenario, the persona and the hidden expected outcome. The first user message is generated from a prompt you can read in ran/prompts_sim_default/01_SimulatedInput.txt. Its key elements, in the real prompt:

text
Pretend you are a user of an LLM app. Your goal is to start a conversation in English
based on a scenario and persona. ...
2. Match the persona's tone faithfully. If the user is frustrated, impatient, blunt, or
   impolite, reflect that naturally instead of making them warm or courteous.
3. Avoid providing excessive details upfront ...
4. The message should be concise, ideally no more than 1-3 sentences.
...
<persona>
Name: Sam

Polite but brief; writes short messages.
</persona>
Scenario: "A customer whose order 1234 arrived broken wants a refund."
JSON Output:

Three facts follow from the captured prompts:

  • The expected outcome is never shown to the simulated user. It does not appear in SimulatedInput prompts, only in the separate stop-check prompt. That is the right design: a user who knows the success condition would steer the conversation towards it. It also means the persona and scenario must carry all the information the user needs, and that you must not paste the outcome into characteristics.
  • Later turns carry the whole history as JSON, with every Turn field (role, content, user_id, latency_ms, interrupted, retrieval_context, tools_called, mcp_*, metadata). That includes your assistant's tool calls and retrieval context if you put them on the turn. Your simulated user therefore reads internal tool data on every turn, which a real user never sees. If your callback puts private retrieval chunks or system details on its Turn, the simulated user can leak and react to them. Keep the simulation-facing turn clean, or accept the leak knowingly.
  • Prompt cost grows with length. Each user turn re-sends the history with null-heavy JSON, and each stop check does the same. A ten-turn conversation costs far more than ten times a one-turn exchange.

The persona text lands in the test case as user_description (Polite but brief; writes short messages. in the output), not as a Persona object. Any metric that reads it therefore sees a description string.

7.4 Stopping order, and the default outcome check#

The simulator decides whether to continue in a fixed order each iteration:

  1. The cap. max_user_simulations user turns (default 10) always wins.
  2. The stopping_controller. Evaluated before each user turn. The default controller is the expected-outcome check: it asks the simulator model, with a prompt named ConversationCompletion, whether the conversation has achieved the expected outcome.
  3. A graph node's max_visits being exhausted: on the next attempt to enter that node the runner emits nothing and the simulation ends (7.6).
  4. A terminal node (terminal=True): after its user turn and the assistant's reply, the conversation ends.

Run A shows the default path. The call list is ['SimulatedInput', 'ConversationCompletion', 'SimulatedInput', 'ConversationCompletion']: one user turn, one stop check after the first assistant reply (not complete), a second user turn, a second stop check (complete), and the simulation ended with four turns. The stop-check prompt is plain:

text
You are a Conversation Completion Checker.
Your task is to determine whether the conversation has achieved the expected outcome and should be terminated.
...
Expected Outcome: "The assistant issues a refund and gives a confirmation number."
Conversation History:
[ ... the turns as JSON ... ]
JSON Output:

Run D shows the failure mode that matters. The golden has no expected_outcome. The default controller then returns "not complete" without making any model call, and the conversation can only end at the cap. The call list is just two SimulatedInput calls and the conversation has four turns, the cap having been two user turns. With the default cap of 10, every golden without an outcome produces a ten-turn conversation whether or not the task finished at turn two. That wastes tokens and, worse, lets the conversation wander past the point of success into territory the metrics then score: a polite assistant that has already solved the problem is asked to keep talking, and a conversation completeness or turn relevancy score on the padded conversation is a different number from the one on the real task.

Two further properties of the default check are worth knowing:

  • The simulator model grades the outcome. The same model that plays the user also decides whether the conversation succeeded. That is an uncalibrated judge (10A.5) making a stopping decision, and a lenient checker will end conversations early or declare success on a polite refusal. A strict one never ends.
  • The check runs before every user turn after the first. Its cost is one call per turn, with a growing prompt.

7.5 Custom stopping controllers#

Run B replaces the default controller with a function. DeepEval fills the function's declared arguments by name from this set: turns, golden, index, thread_id, simulated_user_turns, max_user_simulations, last_user_turn and last_assistant_turn. It returns end(reason=...) to stop, or proceed() (or anything else, including None) to continue. end and proceed are imported from deepeval.simulator.controller.

python
def stop_when_confirmed(last_assistant_turn, simulated_user_turns):
    if last_assistant_turn and "confirmation number" in last_assistant_turn.content.lower():
        return end(reason="confirmation given")
    return proceed()

In the output, Run B's calls are ['SimulatedInput', 'SimulatedInput']: no ConversationCompletion call at all. A deterministic controller is cheaper, faster and reproducible, and it does not hand the stopping decision to an uncalibrated model. Use one when your success condition is observable in the turn: a tool call was made, a confirmation id was returned, a state was reached, a forbidden phrase appeared (stop and fail), or a turn budget was exhausted. Keep the LLM check for outcomes you can only judge semantically, and validate it (8.5).

A controller can also return end for a failure: an assistant that has repeated itself three times is stuck, and ending the conversation records that fact. Put the reason in end(reason=...), then read it in your analysis; the reasons are your termination taxonomy.

7.6 Simulation graphs: scripted users with an LLM only at the branches#

The free simulator lets a model improvise the user. That is realistic and unrepeatable. For regression tests of specific dialogue shapes, such as "user insists after a refusal" or "user changes their mind", a simulation graph gives you a scripted user whose only model call is the decision at each branch.

python
from deepeval.simulator import SimulationNode

root = SimulationNode(action=lambda: "Hi, I'd like a refund for order 1234.", name="ask")
push = SimulationNode(action=lambda: "That is not acceptable.", name="push", max_visits=2)
done = SimulationNode(action=lambda: "Thanks, bye.", name="done", terminal=True)
root.add_node(done, when="The assistant approved the refund")
root.add_node(push, when="The assistant refused")

A node's action returns the next user message (a string or a user Turn), and may be sync or async. Its arguments are filled by name from simulator, turns, golden, last_assistant_turn, last_user_turn, thread_id and language (the set the SimulationNode docstring lists). add_node(child, when="...") creates an edge with a natural-language condition and returns the child, so calls chain. max_visits caps how many times a node can be emitted; on the next attempt to enter it the simulation ends. terminal=True ends the conversation after that node's turn and the reply.

After the assistant replies, DeepEval classifies the reply against the outgoing edges with one model call named EdgeChoice. The real prompt, captured in Run C:

text
You are routing a simulated conversation. The assistant just said:
<<<
I've issued a refund for order 1234. Confirmation number R-77.
>>>

Which of the following best describes the assistant's reply?
  1) The assistant approved the refund
  2) The assistant refused
  3) None of the above

Pick exactly one option. Respond with the option's number.

The answer is {index, reason}, 1-based, with null for "none of the above", in which case the conversation stays on the current node. A node with no outgoing edges skips the router entirely. In Run C the only model call was a single EdgeChoice, with the stopping controller set to lambda: proceed() so the default outcome check would not add its own calls. The conversation went ask, then done, and ended.

Things to notice in the output:

  • The terminal node does not end the conversation before the assistant answers. The transcript ends with a fourth turn, the assistant's reply to "Thanks, bye." That is by design (the reply is part of the exchange), but it means your metrics will score a final assistant turn written in response to a goodbye. If that turn can be wrong in a way that matters, such as a callback that asks for an order number again, the metric sees it.
  • The router is a judge. EdgeChoice classifies free text into your edge list with an LLM. Write edge conditions that are mutually exclusive and phrased about observable behaviour ("asked a clarifying question", "stated a refusal"), and always consider the unmatched path. Use the router prompt output to debug misroutes.
  • max_visits stops loops. The push node can be entered at most twice, which gives a bounded "insistent user" script.

Hybrid graphs. The simulator argument is how DeepEval's own default node works: default_simulation_node() returns a node whose action calls the simulator model with the standard (or your custom) template. Put one inside a scripted graph and that branch is improvised while the rest stays scripted, which is the usual compromise between repeatability and realism. The probe scripts the opening, hands every reply that asks a clarifying question to the improvising node, and caps that node at one visit:

python
"""Lesson 10B.6: a hybrid simulation graph (scripted turns plus one generated branch) and max_visits."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import ConversationalGolden
from deepeval.simulator import ConversationSimulator, SimulationNode, default_simulation_node
from deepeval.simulator.controller import proceed
from deepeval.test_case import Turn


def stubborn_app(input: str) -> Turn:
    """Always asks for more detail, so the user is pushed around the graph."""
    return Turn(role="assistant", content="Can you tell me more about the problem?")


root = SimulationNode(action=lambda: "My order 1234 arrived broken.", name="ask")
# One branch hands the user turn back to the simulator model (DeepEval's default prompt).
improvise = default_simulation_node(name="improvise", max_visits=1)
root.add_node(improvise, when="The assistant asked a clarifying question")
improvise.add_node(improvise, when="The assistant asked a clarifying question")

sim_model = FakeJudge(script={
    "EdgeChoice": [{"index": 1, "reason": "clarifying question"}] * 3,
    "SimulatedInput": [{"simulated_input": "The screen is cracked, I want a refund."}],
})
simulator = ConversationSimulator(
    model_callback=stubborn_app,
    simulator_model=sim_model,
    simulation_graph=root,
    stopping_controller=lambda: proceed(),
    async_mode=False,
)
case = simulator.simulate(
    conversational_goldens=[ConversationalGolden(scenario="Order 1234 arrived broken.")],
    max_user_simulations=6,
)[0]
for turn in case.turns:
    print(f"{turn.role}: {turn.content}")
print("calls:", sim_model.schemas())
Output · real, trimmed6 lines
user: My order 1234 arrived broken.
assistant: Can you tell me more about the problem?
user: The screen is cracked, I want a refund.
assistant: Can you tell me more about the problem?
calls: ['EdgeChoice', 'SimulatedInput', 'EdgeChoice']
[netguard] total blocked attempts: 0 []

The call list reads as the graph: EdgeChoice after the scripted opening (route to improvise), one SimulatedInput for the improvised turn, then a second EdgeChoice that routes back to improvise. Its one visit is used up, so the simulation ends with four turns although the cap was six user turns. Note what that means for your termination statistics: this conversation ended by max_visits, not by outcome or cap, and nothing in the returned test case says so. Record the reason yourself (8.5).

Use graphs when you need determinism: regression tests for known failure paths, adversarial dialogue shapes, A/B comparisons between app versions where you want the user to behave identically. Use the free simulator for exploration and coverage.

7.7 Hooks and custom templates#

on_simulation_complete(test_case, index) fires once per finished conversation, with the index of the golden. In async mode the completion order can differ from the input order, so use the index, not the arrival order, to match results to goldens. Run A printed hook: golden 0 finished with 4 turns. Typical uses: write each conversation to disk as it completes so a crash loses one, push progress to a log, or stream conversations into a review queue.

on_turn(turns, index) is in the 4.3.5 signature and fires after each turn is appended. The sample below shows that it fires for user and assistant turns alike. DeepEval's lifecycle-hooks documentation page does not describe it, so treat its details as observed behaviour rather than a contract.

Templates. SimulationTemplate is the class that builds the simulator's prompts. Subclass it and override the static methods to change how the user is prompted. The sample overrides simulate_first_user_turn(golden, language) and simulate_user_turn(golden, turns, language), passes the subclass through default_simulation_node(template=...) and prints the prompt the simulator model received, to prove the override took effect.

python
"""Lesson 10B.6: custom simulation templates and the on_turn hook."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import ConversationalGolden
from deepeval.simulator import ConversationSimulator, SimulationTemplate, default_simulation_node
from deepeval.simulator.controller import proceed
from deepeval.test_case import Turn


class TerseTemplate(SimulationTemplate):
    @staticmethod
    def simulate_first_user_turn(golden: ConversationalGolden, language: str) -> str:
        return (
            "CUSTOM TEMPLATE: write one very terse opening user message in "
            f"{language} for this scenario: {golden.scenario}"
        )

    @staticmethod
    def simulate_user_turn(golden: ConversationalGolden, turns: list[Turn], language: str) -> str:
        return "CUSTOM TEMPLATE: continue tersely."


def app_callback(input: str) -> Turn:
    return Turn(role="assistant", content="Sure, I can help with that.")


events = []
def on_turn(turns, index):
    events.append((index, len(turns), turns[-1].role, turns[-1].content))


simulator_model = FakeJudge(script={
    "SimulatedInput": [{"simulated_input": "refund please"}],
})
simulator = ConversationSimulator(
    model_callback=app_callback,
    simulator_model=simulator_model,
    simulation_graph=default_simulation_node(template=TerseTemplate),
    stopping_controller=lambda: proceed(),
    async_mode=False,
)
case = simulator.simulate(
    conversational_goldens=[ConversationalGolden(scenario="A customer wants a refund.")],
    max_user_simulations=1,
    on_turn=on_turn,
)[0]
print("turns:", [(turn.role, turn.content) for turn in case.turns])
print("on_turn events:", events)
print("prompt sent to simulator model:")
print(simulator_model.prompt(0))
Output · real5 lines
turns: [('user', 'refund please'), ('assistant', 'Sure, I can help with that.')]
on_turn events: [(0, 1, 'user', 'refund please'), (0, 2, 'assistant', 'Sure, I can help with that.')]
prompt sent to simulator model:
CUSTOM TEMPLATE: write one very terse opening user message in English for this scenario: A customer wants a refund.
[netguard] total blocked attempts: 0 []

The printed prompt starts with CUSTOM TEMPLATE:, so the override replaced DeepEval's default wording. The on_turn events show (0, 1, 'user', ...) and (0, 2, 'assistant', ...): golden index, turn count, role and content. Custom templates are how you adapt the user to your domain (a particular language register, a regulated-industry persona script, a stricter tone rule) without forking the library. Version your template with your results: a different template is a different instrument (Part 8).

7.8 Feeding simulations to metrics#

Each simulated conversation is a ConversationalTestCase with turns, scenario, expected_outcome, user_description and context. Pass the list to evaluate() with the multi-turn metrics of 10B.4, Part 6, or to assert_test() in a pytest file (10B.2, Part 5). The last block of the Run output scores Run A's conversation with ConversationCompletenessMetric, and the three captured prompts (UserIntentions, ConversationCompletenessVerdict, ConversationCompletenessScoreReason) are in ran/prompts_sim_metric/. Score 1.0 with the scripted verdicts shows plumbing, not quality.

Choose metrics for the failure you are hunting:

You are checking Metrics to start from Needs from the simulation
The user's goal was met ConversationCompletenessMetric, GoalAccuracyMetric expected_outcome or a clear scenario
The assistant forgets earlier facts KnowledgeRetentionMetric Scenarios that state facts early, then depend on them
The assistant stays in role RoleAdherenceMetric A system prompt or role description in the test case
Replies stay on topic TurnRelevancyMetric Nothing extra
Tool use across a conversation ToolUseMetric (and the multi-turn MCP metrics), GoalAccuracyMetric (10B.5) tools_called on the assistant Turns
Domain-specific criteria ConversationalGEval (10B.3) A written rubric

TaskCompletionMetric and ToolCorrectnessMetric score single-turn or traced LLMTestCases (10B.5); do not hand them a simulated conversation. The probe below attaches a tool call to the assistant Turn, scores the simulated case with ToolUseMetric and the fake judge, and shows TaskCompletionMetric refusing the same object (real run, DeepEval 4.3.5):

python
"""Lesson 10B.6: score a simulated conversation with ToolUseMetric; TaskCompletionMetric rejects it."""
import warnings

warnings.filterwarnings("ignore")
import netguard  # noqa: F401
from typing import List

from fake_judge import FakeJudge
from deepeval.dataset import ConversationalGolden
from deepeval.metrics import TaskCompletionMetric, ToolUseMetric
from deepeval.simulator import ConversationSimulator
from deepeval.test_case import ToolCall, Turn


def app(input: str, turns: List[Turn], thread_id: str) -> Turn:
    """Assistant stand-in that records the tool it called on its Turn."""
    return Turn(role="assistant", content="Refund issued. Confirmation R-77.",
                tools_called=[ToolCall(name="issue_refund", input_parameters={"order": "1234"})])


golden = ConversationalGolden(scenario="Order 1234 arrived broken; the customer wants a refund.",
                              expected_outcome="A refund is issued with a confirmation number.")
sim_model = FakeJudge(script={
    "SimulatedInput": [{"simulated_input": "Refund order 1234 please."}],
    "ConversationCompletion": [{"is_complete": True, "reason": "refund issued"}],
})
case = ConversationSimulator(model_callback=app, simulator_model=sim_model,
                             async_mode=False).simulate(conversational_goldens=[golden],
                                                        max_user_simulations=3)[0]
print("turns:", [(t.role, [c.name for c in (t.tools_called or [])]) for t in case.turns])

judge = FakeJudge(script={
    "ToolSelectionScore": [{"score": 1.0, "reason": "right tool"}],
    "ArgumentCorrectnessScore": [{"score": 1.0, "reason": "arguments fit"}],
    "Reason": [{"reason": "selection was right"}, {"reason": "arguments were right"}],
})
metric = ToolUseMetric(available_tools=[ToolCall(name="issue_refund")], model=judge, async_mode=False)
metric.measure(case, _show_indicator=False)
print("ToolUseMetric:", metric.score, metric.success, judge.schemas())

try:
    TaskCompletionMetric(model=FakeJudge(), async_mode=False).measure(case, _show_indicator=False)
except Exception as exc:
    print("TaskCompletionMetric:", type(exc).__name__, str(exc)[:110])
Output · real4 lines
turns: [('user', []), ('assistant', ['issue_refund'])]
ToolUseMetric: 1.0 None ['ToolSelectionScore', 'ArgumentCorrectnessScore', 'Reason', 'Reason']
TaskCompletionMetric: ValueError Unable to evaluate test cases that are not of type 'LLMTestCase' using the non-conversational 'Task Completion
[netguard] total blocked attempts: 0 []

Two cautions. First, a conversation metric is a judge, so it inherits 10A.4's biases, and 10A.5 applies. Second, the metric sees the transcript the simulator produced. If the simulator never pushed the assistant into the hard case, a high score says only that an easy conversation went well. Scenario design is where simulation tests are won: write goldens for the failure paths, not the happy ones.

7.9 What the simulator does not give you#

  • No tracing. The simulator calls your callback and records turns. It does not create spans, so component-level and trace-aware metrics (10B.5) see nothing unless your callback itself calls instrumented code, in which case traces come from your @observe decorators and not from the simulator. Attach tool calls and retrieval context to the Turn objects to get Turn RAG and tool metrics.
  • No cost report for custom models. The runs here surfaced no cost figure for the simulator's calls. Count calls: one SimulatedInput per user turn, one stop check per turn after the first (default controller), one EdgeChoice per graph step with outgoing edges, and your callback's own calls.
  • No seeds. Temperature and sampling are whatever your simulator model does, so two runs of the same golden differ. Record the simulator model name and version, the template, the language, the persona text and the cap with every result.
  • Concurrency. max_concurrent=5 bounds simultaneous conversations in async mode. Raise it with care: a callback that shares state across conversations will mix them.
  • A cap, not a time limit. max_user_simulations limits user turns. A callback that hangs or returns slowly is your responsibility.

Part 8: Validating the simulator before you trust it#

Deep-dive

DeepEval ships the instrument, not its validation. 10A.12, Part 7 argues that a user simulator is part of the measurement, and gives the full battery of checks with sim_validation.py. This part maps those checks onto the DeepEval objects, says what you can do cheaply with the simulator's own output, and is honest about what DeepEval cannot tell you.

8.1 The instrument and its versions#

A simulated score depends on the simulator model, its sampling settings, the template, the persona text, the language, the cap, the stopping controller, the callback adapter and the DeepEval version. Report all of them: "completeness 0.82 under simulator X, template T, persona set P, DeepEval 4.3.5". Comparing two app versions under different simulators compares nothing. This is the discipline of 10A.12, 7.1 applied to DeepEval's fields.

8.2 The checks, mapped#

10A.12 check What it asks DeepEval gives You add
Realism (7.5) Do simulated user turns look like real ones? Nothing Compare turn length, politeness and repetition with real transcripts against a noise floor
Discriminability (7.6) Can a classifier tell simulated from real? Nothing Train the classifier on your transcripts
Goal and persona fidelity (7.7) Does the user pursue the scenario and keep the persona? A persona prompt block A judge or rubric per conversation; check invented facts
Leakage (7.8) Does the user help the app too much? The outcome is hidden from the user Unhelpful-user and no-user controls (8.4), plus a null-app floor
Termination (7.9) Do conversations end for the right reason? end(reason=...) and the cap Reason taxonomy and rates (8.5)
Difficulty calibration (7.11) Is the sim harder or easier than reality? Nothing Score the same app on real and simulated conversations
Predictive validity (7.12) Does the sim ranking match real outcomes? Nothing A human study or production outcomes
Panels and versioning (7.14) Does the result survive a change of simulator? One simulator_model argument Run a panel of simulators and compare

Be clear about what this table says: DeepEval gives you a convenient way to produce conversations, and no validity evidence. Everything from realism to predictive validity is evidence you generate.

8.3 Cheap checks you can run today#

Most of the checks need real transcripts, which many teams do not yet have. Three checks need only the simulator's own output and are cheap enough to run every time:

  1. Termination mix. For every run, report the share of conversations that ended by outcome, by custom controller reason and by cap.
  2. Null-app control. Run the simulator against an app that does nothing useful. If the null app "passes", the test is broken.
  3. Leakage proxy. Measure lexical overlap between the simulated user's turns and the hidden expected outcome. High overlap means the user is saying the answer.

The next sample implements all three over two deterministic apps, an oracle that can finish the task and a null app that always asks for the order number. The simulated user and the completion checker are scripted (the checker says "complete" only when a confirmation number appears), so this shows the harness, not a real simulator's behaviour.

python
"""Lesson 10B.6: cheap validity checks on simulated conversations (termination, null app, leakage)."""
import re
import warnings
warnings.filterwarnings("ignore")
from typing import List

import netguard
from fake_judge import FakeJudge
from deepeval.dataset import ConversationalGolden, Persona
from deepeval.simulator import ConversationSimulator
from deepeval.test_case import Turn

golden = ConversationalGolden(
    scenario="A customer whose order 1234 arrived broken wants a refund.",
    expected_outcome="The assistant issues a refund and gives a confirmation number.",
    persona=Persona(name="Sam", characteristics="Polite but brief; writes short messages."),
)
MAX_TURNS = 4


def oracle_app(input: str, turns: List[Turn]) -> Turn:
    if "1234" in input:
        return Turn(role="assistant", content="Refund issued for order 1234. Confirmation number R-77.")
    return Turn(role="assistant", content="Could you share your order number?")


def null_app(input: str) -> Turn:
    return Turn(role="assistant", content="Could you share your order number?")


USER_LINES = [
    {"simulated_input": "Hi, my order arrived broken."},
    {"simulated_input": "It is order 1234."},
    {"simulated_input": "Order 1234, please."},
    {"simulated_input": "Still order 1234."},
]
WORDS = lambda text: set(re.findall(r"[a-z]{4,}", text.lower()))


def run(app):
    user = FakeJudge(
        script={"SimulatedInput": list(USER_LINES)},
        routes={"ConversationCompletion": [("Confirmation number", {"is_complete": True, "reason": "confirmed"})]},
    )
    user.script["ConversationCompletion"] = [{"is_complete": False, "reason": "not yet"}] * 6
    simulator = ConversationSimulator(model_callback=app, simulator_model=user, async_mode=False)
    case = simulator.simulate(conversational_goldens=[golden], max_user_simulations=MAX_TURNS)[0]
    users = [t.content for t in case.turns if t.role == "user"]
    return case, users


for name, app in [("oracle", oracle_app), ("null", null_app)]:
    case, users = run(app)
    hit_cap = len(users) >= MAX_TURNS
    leak = len(WORDS(" ".join(users)) & WORDS(golden.expected_outcome)) / len(WORDS(golden.expected_outcome))
    print(f"{name:7} user_turns={len(users)} stopped_by={'cap' if hit_cap else 'outcome'} "
          f"outcome_word_overlap_in_user_turns={leak:.2f}")
Output · real4 lines
oracle  user_turns=2 stopped_by=outcome outcome_word_overlap_in_user_turns=0.00

null    user_turns=4 stopped_by=cap outcome_word_overlap_in_user_turns=0.00
[netguard] total blocked attempts: 0 []

The oracle app finishes in two user turns and stops by outcome. The null app never finishes: it runs to the cap of four user turns. That is the right result for a null app, and it is also the signal worth tracking: a rising share of conversations ending at the cap means the app is failing to resolve, or the stopping check is failing to notice that it did. The two causes look identical in a summary and need transcript reading to separate. The leakage proxy reads 0.00 for both because the scripted user never says "refund", "issues", "gives", "confirmation" or "number"; a user that parroted the outcome would score high.

8.4 Controls: unhelpful user, no user and null app#

10A.12, 7.8 names two controls (the unhelpful user and no user), and both are easy with DeepEval's objects. A third, the null app, is specific to a simulator-driven chat and defines the floor of the metric:

  • Unhelpful user. Use a persona or template that withholds information and ignores hints, or a graph that never volunteers the order number. If the app still scores highly, the simulator was doing the app's work.
  • No user. For a single-turn-resolvable scenario, compare the app's score when the first user message already contains everything. This separates "the app handles conversation well" from "the user message made the task easy".
  • Null app (added here, not in 10A.12). Use a callback that returns a fixed non-answer, as above. Its conversation-metric scores define the floor. A metric that gives a null app 0.7 cannot discriminate.

If a control scores close to a real run, the simulation is measuring the user and the metric, not the app.

8.5 Termination and the stop check#

The default stop check is the least visible piece of the instrument, so test it directly. Build 30 to 50 conversations by hand or from logs, label each "outcome reached" or "not reached", run the ConversationCompletion prompt on them with your chosen simulator model, and compute agreement and the error direction. Early stops flatter the app; late stops waste money and distort turn-level averages. The procedure is the judge-calibration of 10A.5 applied to a stopping decision. If agreement is poor, replace the LLM check with a deterministic controller (7.5), or ask the simulator model for a stricter outcome definition.

Also report termination reasons. A table with outcome, controller:<reason>, node:max_visits, terminal and cap rows per release is a one-glance health check on the instrument and on the app.

8.6 Using the simulator responsibly#

A short protocol that follows from the above:

  1. Write goldens for failure paths first: refusals, ambiguity, hostile users, topic switches, corrections.
  2. Version the persona set, template, simulator model, language and cap alongside the dataset card (1.8).
  3. Prefer deterministic controllers and graphs for regression gates; use the free simulator for discovery.
  4. Run controls (8.4) whenever the simulator, template or metric changes.
  5. Report conversation-metric scores with the termination mix and an interval, never as a bare mean.
  6. Spot-read conversations from every slice and from both tails of the score distribution. Fix the instrument when you find a conversation no real user would have.
  7. Periodically compare simulated outcomes with real ones (calibration and predictive validity). Until you do, say "simulated pass rate", not "success rate".

Part 9: Public benchmarks in deepeval.benchmarks#

Reference

Everything so far evaluated your application on your data. deepeval.benchmarks does something different: it runs a raw model through a published benchmark such as MMLU, GSM8K or HumanEval, using DeepEval's prompt templates, a Hugging Face dataset and a scoring function. It is a convenience for quick model comparisons and regression checks of your own model wrapper. It is not an application eval, and its numbers are properties of the harness as much as of the model. 10A.10, Part 5 teaches how to read benchmarks in general; this part opens up DeepEval's implementation.

flowchart LR
    HF["Benchmark dataset"] --> SH["Fixed n-shot examples"]
    SH --> PR["Benchmark prompt template"]
    PR --> LM["DeepEvalBaseLLM wrapper"]
    LM --> PA["Exact, rule, execution or judge scoring"]
    PA --> DF["predictions and task_scores"]
    DF --> OA["micro-averaged overall accuracy"]

9.1 What a benchmark run is for#

Use it to answer questions about a model: does the new quantized checkpoint lose accuracy on high-school maths, is this provider's model better at multiple-choice reasoning than my current one, did my wrapper break anything? Do not use it to answer questions about your product: whether answers are faithful to your documents, whether the agent calls the right tool, whether users are satisfied. For those, use goldens, simulations and the metrics of 10B.4. The third thing a benchmark run is useful for is a smoke test of your DeepEvalBaseLLM wrapper (the contract of 10B.3): if a trivially easy benchmark scores near chance, the wrapper or the output format is the suspect.

9.2 The inventory#

The package exports 17 benchmark classes. This probe prints their real signatures and the size of each task enum, with no dataset download:

python
"""Lesson 10B.6: inspect the benchmark catalogue without downloading datasets."""
import inspect
import warnings
warnings.filterwarnings("ignore")

import netguard
import deepeval.benchmarks as benchmarks
import deepeval.benchmarks.tasks as tasks

print("exported benchmark classes:", len(benchmarks.__all__))
for name in benchmarks.__all__:
    cls = getattr(benchmarks, name)
    print(f"{name}{inspect.signature(cls)}")

print("\ntask enum import path: deepeval.benchmarks.tasks")
for name in sorted(x for x in dir(tasks) if x.endswith("Task")):
    enum = getattr(tasks, name)
    print(name, "members:", len(list(enum)))

print("\nold singular import path from the docs:")
try:
    import deepeval.benchmarks.task  # noqa: F401
    print("deepeval.benchmarks.task imported unexpectedly")
except Exception as exc:
    print(type(exc).__name__, str(exc))
Output · real, with the package-install line removed34 lines
exported benchmark classes: 17
BigBenchHard(tasks: List[deepeval.benchmarks.big_bench_hard.task.BigBenchHardTask] = None, n_shots: int = 3, enable_cot: bool = True, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions_dict: Opti ...[trimmed]
MMLU(tasks: Optional[List[deepeval.benchmarks.mmlu.task.MMLUTask]] = None, n_shots: int = 5, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
HellaSwag(tasks: List[deepeval.benchmarks.hellaswag.task.HellaSwagTask] = None, n_shots: int = 10, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
DROP(tasks: List[deepeval.benchmarks.drop.task.DROPTask] = None, n_shots: int = 5, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, **kwargs)
TruthfulQA(tasks: List[deepeval.benchmarks.truthful_qa.task.TruthfulQATask] = None, mode: deepeval.benchmarks.truthful_qa.mode.TruthfulQAMode = <TruthfulQAMode.MC1: 'mc1'>, n_problems_per_task: Optional[int] = None, verbose_mode: bool = Fal ...[trimmed]
HumanEval(tasks: List[deepeval.benchmarks.human_eval.task.HumanEvalTask] = None, n: int = 200, verbose_mode: bool = False, **kwargs)
SQuAD(tasks: List[deepeval.benchmarks.squad.task.SQuADTask] = None, n_shots: int = 5, n_problems_per_task: Optional[int] = None, evaluation_model: Union[str, deepeval.models.base_model.DeepEvalBaseLLM, NoneType] = None, verbose_mode: bool = ...[trimmed]
GSM8K(n_shots: int = 3, enable_cot: bool = True, n_problems: int = 1319, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
MathQA(tasks: List[deepeval.benchmarks.math_qa.task.MathQATask] = None, n_shots: int = 5, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
LogiQA(tasks: List[deepeval.benchmarks.logi_qa.task.LogiQATask] = None, n_shots: int = 5, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
BoolQ(n_shots: int = 5, n_problems: int = 3270, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
ARC(n_shots: int = 5, n_problems: Optional[int] = None, mode: deepeval.benchmarks.arc.mode.ARCMode = <ARCMode.EASY: 'ARC-Easy'>, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
BBQ(n_shots: int = 5, tasks: List[deepeval.benchmarks.bbq.task.BBQTask] = None, n_problems_per_task: Optional[int] = None, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
LAMBADA(n_shots: int = 5, n_problems: int = 5153, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
Winogrande(n_shots: int = 5, n_problems: int = 1267, verbose_mode: bool = False, confinement_instructions: Optional[str] = None, **kwargs)
EquityMedQA(tasks: List[deepeval.benchmarks.equity_med_qa.task.EquityMedQATask] = None, model: Union[str, deepeval.models.base_model.DeepEvalBaseLLM, NoneType] = None, **kwargs)
IFEval(n_problems: Optional[int] = None, verbose_mode: bool = False, **kwargs)

task enum import path: deepeval.benchmarks.tasks
BBQTask members: 11
BigBenchHardTask members: 27
DROPTask members: 582
HellaSwagTask members: 192
HumanEvalTask members: 157
LogiQATask members: 5
MMLUTask members: 57
MathQATask members: 6
SQuADTask members: 48
TruthfulQATask members: 38

old singular import path from the docs:
ModuleNotFoundError No module named 'deepeval.benchmarks.task'
[netguard] total blocked attempts: 0 []

The verified table, combining the signatures above with the dataset identifiers in the loader code:

Class Key defaults Tasks or modes Hugging Face source Scoring batch_size used
MMLU n_shots=5 (max 5) 57 MMLUTask cais/mmlu Exact match on a letter Yes
HellaSwag n_shots=10 192 HellaSwagTask Rowan/hellaswag Exact match Yes
BigBenchHard n_shots=3, enable_cot=True 27 BigBenchHardTask lukaemon/bbh Exact match Yes
DROP n_shots=5 582 DROPTask ucinlp/drop Normalized exact match against any accepted answer (quasi_contains_score) Yes
TruthfulQA mode=MC1 38 TruthfulQATask; modes mc1, mc2 truthful_qa Exact match (MC1); a 0 to 100 recall percentage, truth_identification_score (MC2, see 9.5) Yes
HumanEval n=200; evaluate(model, k=1); temperature fixed at 0.8 157 HumanEvalTask openai_humaneval pass@k per problem; the overall score counts problems with any passing sample (see 9.6) No (ignored)
GSM8K n_shots=3, enable_cot=True, n_problems=1319 none gsm8k (main) Exact match on an extracted number No (ignored)
SQuAD n_shots=5, evaluation_model=None 48 SQuADTask rajpurkar/squad LLM judge (squad_score, 0 or 1) Yes
MathQA n_shots=5 6 MathQATask regisss/math_qa Exact match Yes
LogiQA n_shots=5 (max 5) 5 LogiQATask a raw GitHub file of LogiQA 2.0, not Hugging Face Exact match Yes
BoolQ n_shots=5, n_problems=3270 none boolq Exact match No (ignored)
ARC n_shots=5, mode=ARC-Easy modes ARC-Easy, ARC-Challenge ai2_arc Exact match No (ignored)
BBQ n_shots=5 11 BBQTask heegyu/bbq Exact match No (ignored)
LAMBADA n_shots=5, n_problems=5153 none EleutherAI/lambada_openai Exact match No (ignored)
Winogrande n_shots=5, n_problems=1267 none allenai/winogrande (winogrande_xs) Exact match No (ignored)
EquityMedQA model=None (judge) 9 tasks katielink/EquityMedQA BiasMetric judge (see 9.7) No (ignored)
IFEval n_problems=None none google/IFEval DeepEval's own rule-based instruction checks, prompt-level strict No (ignored)

Three practical notes from the table. Defaults are not uniform: shots range from 3 to 10, some classes take n_problems_per_task (a cap per task) and others a single n_problems, so "I ran DeepEval's benchmarks" is not one configuration. Some benchmarks need a judge: SQuAD and EquityMedQA call a model to score, so they are not keyless and they inherit judge biases (10A.4). Task enums have a different import path from the documentation. The introduction page imports from deepeval.benchmarks.task import ...; the last lines of the output show that this raises ModuleNotFoundError. The real path is deepeval.benchmarks.tasks (plural), or the per-benchmark module such as deepeval.benchmarks.mmlu.task.

9.3 What a run does, mechanically#

For MMLU (the other multiple-choice classes follow the same template), benchmark.evaluate(model, batch_size=None) does this per task:

  1. Download the Hugging Face dataset for the task. This needs the network and, for some datasets, a licence click-through, but no API key. The base class imports datasets at construction, so datasets and pandas must be installed.
  2. Choose shots. The first n_shots examples of the dev split become the few-shot examples. They are the same examples every time: not sampled, not seeded.
  3. Build the prompt from a template: a header line, the shots with answers, then the test question ending in Answer:.
  4. Generate. First try model.generate(prompt=prompt, schema=MultipleChoiceSchema), where the schema constrains answer to "A", "B", "C" or "D". If your generate has no schema parameter and raises TypeError, DeepEval appends a confinement instruction ("Output 'A', 'B', 'C', or 'D'. Full answer not needed.") and calls generate(prompt), using the raw string as the prediction.
  5. Score with exact_match_score(target, prediction): 1 if prediction.strip() == target.strip(), else 0.
  6. Aggregate. Task accuracy is correct over total for the task. The overall score is correct over total across tasks, a micro-average: a task with 1,000 questions counts ten times as much as a task with 100.

After the run you can read benchmark.overall_score, benchmark.task_scores (a DataFrame of Task, Score) and benchmark.predictions (a DataFrame of Task, Input, Prediction, Expected Output, Correct). batch_size uses your model's batch_generate(prompts, schemas) if implemented; the docs say batch_size works for every benchmark except HumanEval and GSM8K, but the source disagrees. In 4.3.5 only eight classes (MMLU, HellaSwag, BigBenchHard, DROP, LogiQA, MathQA, SQuAD, TruthfulQA) declare and use it; BoolQ, ARC, Winogrande, LAMBADA, BBQ, IFEval and EquityMedQA accept it through **kwargs and silently ignore it. Check the class before relying on it. Note that the wrapper receives a prompt string, not a chat template: the benchmark exercises your DeepEvalBaseLLM code path, not a provider's chat formatting unless your wrapper adds it.

9.4 A tiny patched MMLU run: format is part of the score#

You cannot download MMLU in a keyless, network-free lesson, so the sample monkey-patches MMLU.load_benchmark_dataset to return one shot and two hand-written questions, then runs two fake models through the real prompt, schema fallback, exact-match scoring and aggregation code. SchemaModel honours schema= and always answers B. ChattyModel has no schema parameter and answers "The answer is B".

python
"""Lesson 10B.6: a tiny patched MMLU run showing schema fallback and exact-match scoring."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval.benchmarks import MMLU
from deepeval.benchmarks.tasks import MMLUTask
from deepeval.benchmarks.mmlu.template import MMLUTemplate
from deepeval.dataset import Golden
from deepeval.models import DeepEvalBaseLLM

SHOTS = [
    {
        "question": "What does CPU stand for?",
        "choices": ["Central Processing Unit", "Core Power Unit", "Central Power Utility", "Control Process Unit"],
        "answer": 0,
    },
]
TEST = [
    {"question": "Which data structure is FIFO?", "choices": ["Stack", "Queue", "Tree", "Graph"], "answer": 1},
    {"question": "What is 2**3?", "choices": ["6", "9", "8", "5"], "answer": 2},
]


def tiny_load(self, task):
    """Replace the Hugging Face download with one shot and two test rows."""
    self.shots_dataset = SHOTS
    return [
        Golden(
            input=MMLUTemplate.format_question(row, include_answer=False),
            expected_output="ABCD"[row["answer"]],
        )
        for row in TEST
    ]


MMLU.load_benchmark_dataset = tiny_load


class SchemaModel(DeepEvalBaseLLM):
    """Honours schema= structured output and always answers B."""

    def __init__(self):
        self.prompts = []
        super().__init__(model="schema-model")

    def load_model(self):
        return self

    def generate(self, prompt, schema=None):
        self.prompts.append(prompt)
        return schema(answer="B")

    async def a_generate(self, prompt, schema=None):
        return self.generate(prompt, schema)

    def get_model_name(self):
        return "schema-model"


class ChattyModel(DeepEvalBaseLLM):
    """Does not accept schema=, then answers the right letter inside a sentence."""

    def __init__(self):
        self.prompts = []
        super().__init__(model="chatty-model")

    def load_model(self):
        return self

    def generate(self, prompt):
        self.prompts.append(prompt)
        return "The answer is B"

    async def a_generate(self, prompt):
        return self.generate(prompt)

    def get_model_name(self):
        return "chatty-model"


for model in [SchemaModel(), ChattyModel()]:
    benchmark = MMLU(tasks=[MMLUTask.HIGH_SCHOOL_COMPUTER_SCIENCE], n_shots=1)
    result = benchmark.evaluate(model=model)
    print(type(model).__name__, "overall:", result.overall_accuracy, "| result type:", type(result).__name__)
    print(benchmark.predictions.to_string(index=False))
    print(benchmark.task_scores.to_string(index=False))

schema_model = SchemaModel()
benchmark = MMLU(tasks=[MMLUTask.HIGH_SCHOOL_COMPUTER_SCIENCE], n_shots=1)
benchmark.evaluate(model=schema_model)
print("\nfirst prompt sent to SchemaModel:")
print(schema_model.prompts[0])

chatty = ChattyModel()
benchmark = MMLU(tasks=[MMLUTask.HIGH_SCHOOL_COMPUTER_SCIENCE], n_shots=1)
benchmark.evaluate(model=chatty)
print("\nchatty prompt tail:")
print(repr(chatty.prompts[0][-140:]))
Output · real, trimmed; progress bars collapsed44 lines
MMLU Task Accuracy (task=high_school_computer_science): 0.5
Overall MMLU Accuracy: 0.5
SchemaModel overall: 0.5 | result type: DeepEvalBaseBenchmarkResult
                        Task                                                                         Input Prediction Expected Output  Correct
high_school_computer_science Which data structure is FIFO?\nA. Stack\nB. Queue\nC. Tree\nD. Graph\nAnswer:          B               B        1
high_school_computer_science                                What is 2**3?\nA. 6\nB. 9\nC. 8\nD. 5\nAnswer:          B               C        0
                        Task  Score
high_school_computer_science    0.5

MMLU Task Accuracy (task=high_school_computer_science): 0.0
Overall MMLU Accuracy: 0.0
ChattyModel overall: 0.0 | result type: DeepEvalBaseBenchmarkResult
                        Task                                                                         Input      Prediction Expected Output  Correct
high_school_computer_science Which data structure is FIFO?\nA. Stack\nB. Queue\nC. Tree\nD. Graph\nAnswer: The answer is B               B        0
high_school_computer_science                                What is 2**3?\nA. 6\nB. 9\nC. 8\nD. 5\nAnswer: The answer is B               C        0
                        Task  Score
high_school_computer_science    0.0

MMLU Task Accuracy (task=high_school_computer_science): 0.5
Overall MMLU Accuracy: 0.5

first prompt sent to SchemaModel:
The following are multiple choice questions (with answers) about high school computer science.

What does CPU stand for?
A. Central Processing Unit
B. Core Power Unit
C. Central Power Utility
D. Control Process Unit
Answer: A

Which data structure is FIFO?
A. Stack
B. Queue
C. Tree
D. Graph
Answer:

MMLU Task Accuracy (task=high_school_computer_science): 0.0
Overall MMLU Accuracy: 0.0

chatty prompt tail:
"t\nAnswer: A\n\nWhich data structure is FIFO?\nA. Stack\nB. Queue\nC. Tree\nD. Graph\nAnswer:\n\nOutput 'A', 'B', 'C', or 'D'. Full answer not needed."
[netguard] total blocked attempts: 0 []

Read the two runs side by side.

  • SchemaModel scored 0.5: right on the FIFO question (answer B), wrong on 2**3 (it said B, the answer is C). The prediction column holds the bare letter.
  • ChattyModel scored 0.0, although it answers B in both cases and B is correct for the first question. Its prediction is the string "The answer is B", and exact match compares the whole string with "B". The model knew the answer. The harness did not credit it.
  • The prompt printed for SchemaModel is the real template: the header "The following are multiple choice questions (with answers) about high school computer science.", the one shot with Answer: A, then the test question ending Answer:. The tail for ChattyModel shows the confinement sentence DeepEval added when schema= failed.

That is the lesson of this part in one picture: a benchmark number is a property of model plus prompt plus parser plus aggregation. Change your wrapper from returning schema(answer=...) to returning free text, and your "MMLU score" changes without the model changing. DeepEval's own documentation warns that if scores are absurdly low, the model is probably not generating valid outputs; treat that as a diagnostic: when a benchmark result is far below published results, look at benchmark.predictions before concluding anything about the model.

9.5 Reading the other scorers#

All the multiple-choice classes share the exact-match design of 9.4 and therefore its sensitivities: prompt template, letter-versus-text answers, whitespace, and the model's tendency to add words. The others differ in ways worth knowing before you trust them. The rows below were read from the installed 4.3.5 scorers and benchmark classes (deepeval/scorer/scorer.py and deepeval/benchmarks/*/); the TruthfulQA row was also run:

Benchmark What the code actually does
GSM8K Asks for NumberSchema (answer: int) and compares str(answer) with the reference by exact match. Without schema= support it appends "Make sure to output only the numerical answer." and compares the whole raw reply: there is no number extraction at all, so a model that shows its working scores 0. With enable_cot=True (the default) the prompt ends "Let's think step-by-step." while the schema allows only an integer, so the chain of thought is requested and then forbidden
BigBenchHard A per-task schema, then exact match; without schema support a per-task confinement sentence is appended. The same enable_cot tension as GSM8K
DROP quasi_contains_score is not containment: it normalizes the prediction and each accepted answer (lower case, punctuation and the articles a, an, the removed, whitespace collapsed) and requires the prediction to equal one of them. Verbose answers fail. The original DROP paper also reports a token-level F1 that gives partial credit; DeepEval reports only this normalized exact match, so its DROP number is stricter than a published one
TruthfulQA mc1 is exact match on one option number. mc2 asks for a list of the true options and scores the share of true options the prediction includes, as a rounded percentage from 0 to 100. Wrong extra options are not penalized, so listing every option scores 100. The sequential loop then adds these percentages, so the overall MC2 "accuracy" is on a 0 to 100 scale, while the batched loop counts any non-zero score as one correct answer. The docs say overall_score ranges from 0 to 1. The original MC2 is a probability mass on the true answers computed from log-probabilities; this is a different measurement (run below)
IFEval DeepEval's own re-implementation of the instruction checks, not Google's reference code. The overall score is prompt-level strict accuracy (a prompt passes only if every instruction passes); per-instruction accuracies are in benchmark.instruction_breakdown. There is no "loose" variant, and an unknown instruction id or a checker exception counts as a failure without raising
LogiQA Loaded from a raw GitHub file rather than Hugging Face, so it depends on a different availability and licence path
LAMBADA, Winogrande, BoolQ, ARC, BBQ, HellaSwag, MathQA Standard exact-match designs; check n_problems, shots and the mode before comparing runs. MathQA uses a five-letter schema (a to e)

The TruthfulQA probe patches the loader with two questions whose true options are 1 and 2, and runs four fixed pickers in both loops:

python
"""Lesson 10B.6: TruthfulQA MC2 scoring in DeepEval: a recall percentage, aggregated two different ways."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval.benchmarks import TruthfulQA
from deepeval.benchmarks.modes import TruthfulQAMode
from deepeval.benchmarks.tasks import TruthfulQATask
from deepeval.dataset import Golden
from deepeval.models import DeepEvalBaseLLM

# Two patched questions; options 1 and 2 are the true ones in both.
ROWS = [
    Golden(input="Q1 with four options", expected_output="[1, 2]"),
    Golden(input="Q2 with four options", expected_output="[1, 2]"),
]
TruthfulQA.load_benchmark_dataset = lambda self, task, mode: list(ROWS)


class Picker(DeepEvalBaseLLM):
    """A stand-in model that answers MC2 with a fixed list of option indices."""

    def __init__(self, name, picks):
        self.name, self.picks = name, picks
        super().__init__(model=name)

    def load_model(self):
        return self

    def get_model_name(self):
        return self.name

    def generate(self, prompt, schema=None):
        return schema(answer=self.picks)

    async def a_generate(self, prompt, schema=None):
        return self.generate(prompt, schema)

    def batch_generate(self, prompts, schemas):
        return [schema(answer=self.picks) for schema in schemas]


models = [
    Picker("precise [1, 2]", [1, 2]),
    Picker("half [1]", [1]),
    Picker("everything [1, 2, 3, 4]", [1, 2, 3, 4]),
    Picker("wrong [3, 4]", [3, 4]),
]
for model in models:
    scores = []
    for batch_size in (None, 2):
        benchmark = TruthfulQA(tasks=[TruthfulQATask.MISCONCEPTIONS], mode=TruthfulQAMode.MC2)
        scores.append(benchmark.evaluate(model, batch_size=batch_size).overall_accuracy)
    print(f"{model.name:24} per-question score: {benchmark.predictions['Correct'].tolist()} "
          f"| overall sequential: {scores[0]} | overall batch_size=2: {scores[1]}")
Output · real, progress lines removed5 lines
precise [1, 2]           per-question score: [100, 100] | overall sequential: 100.0 | overall batch_size=2: 1.0
half [1]                 per-question score: [50, 50] | overall sequential: 50.0 | overall batch_size=2: 1.0
everything [1, 2, 3, 4]  per-question score: [100, 100] | overall sequential: 100.0 | overall batch_size=2: 1.0
wrong [3, 4]             per-question score: [0, 0] | overall sequential: 0.0 | overall batch_size=2: 0.0
[netguard] total blocked attempts: 0 []

Read it row by row. The precise picker and the one that lists every option score the same 100: MC2 here rewards recall and ignores precision. The half-right picker scores 50.0 sequentially and 1.0 batched. A team that switches on batch_size to speed up a run silently changes the number from a 0 to 100 recall average to a 0 to 1 "any overlap" rate. If you need MC2 at all, take benchmark.predictions, recompute your own metric (precision and recall per question, then average), and report that.

For any benchmark class, the method is the same as in 9.4 and this probe: patch the loader to return two or three rows, run it with your wrapper, and read benchmark.predictions. Ten minutes of that tells you whether the parser and wrapper agree before you spend an hour of GPU or API budget on the real dataset.

9.6 HumanEval: code execution, and why this is not a sandbox#

HumanEval is the one benchmark that executes model-written code. Its interface differs from the others: your model must implement generate_samples(prompt, n, temperature), DeepEval calls it with n=200 samples per problem by default and a temperature fixed at 0.8 inside the class, and evaluate(model, k=1) computes pass@k for each problem.

Each generated function plus the problem's test code is run with a helper called secure_exec: an in-process exec with an allow-listed __builtins__ dictionary (a few dozen safe builtins plus the math module). That is not a sandbox. It restricts which builtin names the code can reach directly; it does not isolate the filesystem, the network, memory or CPU, and it has no timeout, so one sample with an infinite loop hangs the whole run.

Reading the class closely turns up three measurement problems, and a patched run shows all of them. The probe builds one problem shaped exactly like a row of the openai_humaneval dataset (its test field defines check(candidate) but does not call it; all of the first 100 dataset rows checked for this lesson end that way, because the reference harness appends check(<entry_point>) itself) and returns four fixed samples: two wrong functions, one correct function that copies the typed signature, one correct untyped function.

python
"""Lesson 10B.6: a patched HumanEval run. What gets executed, what counts as a pass, what the overall number is."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval.benchmarks import HumanEval
from deepeval.benchmarks.tasks import HumanEvalTask
from deepeval.dataset import Golden
from deepeval.models import DeepEvalBaseLLM
from deepeval.scorer import Scorer

# Shaped like a row of openai_humaneval: the prompt starts with an import, and the
# `test` field DEFINES check() but never CALLS it (the reference harness appends
# `check(<entry_point>)` itself).
PROMPT = 'from typing import List\n\n\ndef has_close_elements(numbers: List[float], threshold: float) -> bool:\n    """True if any two numbers are closer than threshold."""\n'
TEST = "\n\ndef check(candidate):\n    assert candidate([1.0, 2.0, 3.9, 4.0], 0.3) == True\n    assert candidate([1.0, 2.0, 3.0], 0.5) == False\n"


def tiny_load(self, task):
    return Golden(input=PROMPT, expected_output=TEST)


HumanEval.load_benchmark_dataset = tiny_load

SAMPLES = [
    # 1. Wrong: always True. It defines a function and raises nothing.
    "def has_close_elements(numbers, threshold):\n    return True\n",
    # 2. Correct, but copies the typed signature; List is undefined here.
    "def has_close_elements(numbers: List[float], threshold: float) -> bool:\n"
    "    return any(abs(a - b) < threshold for i, a in enumerate(numbers) for b in numbers[i + 1:])\n",
    # 3. Correct and untyped.
    "def has_close_elements(numbers, threshold):\n"
    "    return any(abs(a - b) < threshold for i, a in enumerate(numbers) for b in numbers[i + 1:])\n",
    # 4. Wrong: always False.
    "def has_close_elements(numbers, threshold):\n    return False\n",
]


class FixedSampler(DeepEvalBaseLLM):
    """Returns the four samples above instead of calling a model."""

    def __init__(self):
        super().__init__(model="fixed-sampler")

    def load_model(self):
        return self

    def generate(self, prompt, schema=None):
        return SAMPLES[0]

    async def a_generate(self, prompt, schema=None):
        return SAMPLES[0]

    def generate_samples(self, prompt, n, temperature):
        print(f"generate_samples(n={n}, temperature={temperature})")
        return SAMPLES[:n]

    def get_model_name(self):
        return "fixed-sampler"


benchmark = HumanEval(tasks=[HumanEvalTask.HAS_CLOSE_ELEMENTS], n=4)
result = benchmark.evaluate(model=FixedSampler(), k=1)
print("samples counted as passing (c):", benchmark.c)
print(benchmark.predictions[["Task", "Correct", "Score"]].to_string(index=False))
print("overall_accuracy:", result.overall_accuracy)

# The same four samples with the reference harness's extra line, check(entry_point):
passed = 0
for code in SAMPLES:
    namespace = {}
    try:
        exec(PROMPT.split("def ")[0] + code + TEST + "\ncheck(has_close_elements)\n", namespace)
        passed += 1
    except Exception:
        pass
print("with the check() call and the prompt's import, c =", passed,
      "| pass@1 =", Scorer().pass_at_k(4, passed, 1))
Output · real, progress lines removed7 lines
generate_samples(n=4, temperature=0.8)
samples counted as passing (c): {'has_close_elements': 3}
              Task  Correct  Score
has_close_elements        1   0.75
overall_accuracy: 1.0
with the check() call and the prompt's import, c = 2 | pass@1 = 0.5
[netguard] total blocked attempts: 0 []
  1. The tests never run. DeepEval executes function + "\n" + test and never appends the check(...) call. Defining check is not calling it, so any sample that compiles and defines its function without raising counts as passing. Both wrong functions passed. Only the reference harness's extra line (the last output line) separates right from wrong: two of four correct, pass@1 0.5 rather than 0.75.
  2. Correct code can fail for a reason unrelated to correctness. The prompt is asked for output that "begins with 'def'", so the prompt's own from typing import List is not executed. A model that faithfully copies the signature numbers: List[float] raises NameError: name 'List' is not defined when the function is defined on Python 3.13, and the sample counts as failed. (Even an import line in the sample would fail, because __import__ is not on the allow-list.) The same model can therefore score differently on different Python versions, since Python 3.14 evaluates annotations lazily (the same definition succeeds there; checked for this lesson).
  3. The overall number is not pass@k. The per-problem Score column is pass@k (0.75 here). The overall accuracy instead counts a problem as solved when its pass@k is above zero, that is, when any of the n samples passed. With the default n = 200 the headline number is close to pass@200 whatever k you pass. Combined with problem 1, it reports 1.0 for nearly any model that writes syntactically valid functions.

All three are present in 4.3.6 as well. Until they are fixed, do not report DeepEval's HumanEval overall score. If you need a code benchmark, keep the samples from benchmark.functions, run them with the reference harness's check(entry_point) in an isolated environment, and compute pass@k from the per-problem counts yourself, or use inspect_evals/humaneval, which runs the tests in a sandbox (10B.16, Part 9).

Two further methodological notes. First, pass@1 with n=200 samples at temperature 0.8 is an average over a distribution of outputs, not one answer; compare only runs with the same n and temperature, and the temperature here is not yours to choose without subclassing. Second, the original HumanEval paper describes 164 problems, while DeepEval's task enum has 157 entries, so check which problems your installed version actually covers before comparing with a paper. Fewer than a few hundred problems gives wide intervals (9.10).

9.7 Judge-scored benchmarks and the EquityMedQA inversion#

DeepEval's documentation describes benchmark scorers as a universal standard. Two classes break that: SQuAD is scored by an LLM judge (evaluation_model, default the OpenAI judge) with a 0 or 1 squad_score, and EquityMedQA is scored by BiasMetric. Both therefore need a model, both inherit judge bias and drift, and neither is keyless. Check the judge's prompt with the fake-judge technique before trusting a SQuAD number; if you change the evaluation model, you changed the benchmark.

EquityMedQA also has a verified scoring bug in DeepEval 4.3.5. The benchmark's predict method scores each answer with BiasMetric(strict_mode=True) and then flips the result: flipped_score = 1 - metric.score if metric.score in [0, 1] else metric.score. That flip was written for the old convention, where a Bias score of 1 meant "biased". Since DeepEval 4.2.0, every metric is higher-is-better and BiasMetric returns 1 for unbiased (10B.4 lists the flip). The result is an inverted benchmark. The probe reproduces it with a scripted judge that finds no opinions in an answer, which BiasMetric scores as 1.0 (unbiased), and a careful, unbiased app answer.

python
"""Lesson 10B.6: reproduce the EquityMedQA score inversion in DeepEval 4.3.5."""
import warnings
warnings.filterwarnings("ignore")

import netguard
from fake_judge import FakeJudge
from deepeval.benchmarks import EquityMedQA
from deepeval.dataset import Golden

# No opinions in the answer -> BiasMetric scores 1.0 (unbiased) since the 4.2.0 direction flip.
judge = FakeJudge(script={
    "Opinions": [{"opinions": []}],
    "BiasScoreReason": [{"reason": "No opinions were found, so there is nothing biased to penalize."}],
})


class CarefulApp(FakeJudge):
    def generate(self, prompt, schema=None):
        return "Please consult a clinician; treatment does not depend on ethnicity."


benchmark = EquityMedQA(model=judge)
result = benchmark.predict(
    CarefulApp(),
    Golden(input="Is condition X treated differently by ethnicity?"),
)
print("predict ->", result)
print("judge calls:", [name for name, _ in judge.calls])
Output · real3 lines
predict -> {'prediction': 'Please consult a clinician; treatment does not depend on ethnicity.', 'score': 0}
judge calls: ['Opinions', 'BiasScoreReason']
[netguard] total blocked attempts: 0 []

The careful answer, which the metric rated as unbiased, comes back with 'score': 0, so it counts as incorrect. In 4.3.5 an EquityMedQA accuracy measures the share of answers the Bias judge found biased. The fix is two lines: remove the flip, or patch the judge direction. Until you have confirmed that your installed version has fixed it, do not publish or gate on an EquityMedQA number. There is also no documentation page for this benchmark at the time of writing (it is absent from the docs index), which is one reason such a bug can sit unnoticed.

The wider lesson is the same one the whole lesson keeps teaching: a library's scoring direction is a fact you must check by running a known-good and a known-bad input through it. A single oracle/null pair, as in 10B.2, Part 10, would have caught this.

9.8 Loading, tasks and cost#

  • Tasks. tasks=[MMLUTask.HIGH_SCHOOL_COMPUTER_SCIENCE, ...] restricts the run. If you omit it, all tasks run: 57 for MMLU, 582 for DROP, which is a very large run.
  • Problem caps. n_problems_per_task (and n_problems on the single-task classes) keeps the first rows of each task (goldens[:n] in the 4.3.5 source), not a random sample. If a dataset is ordered by difficulty, topic or source, a capped run is a biased subset, and two caps of different sizes measure different questions. Small caps also give very noisy numbers (9.10).
  • verbose_mode prints per-problem details. confinement_instructions (or confinement_instructions_dict for benchmarks with several modes) overrides the sentence that tells a non-schema model how to format its answer. Adjust it if your model needs a different instruction, and record that you did.
  • Cost. A run makes one generation per problem, plus the shots in every prompt. Five shots multiplies prompt tokens roughly six times. MMLU has over fourteen thousand test questions across its tasks, so a full run on a paid model is a real bill; estimate tokens before you start, using 10A.2, Part 18's arithmetic.
  • Network and licence. First use downloads datasets from Hugging Face (and LogiQA from GitHub); some datasets have terms of use. Download once, cache, and record the revision.

9.9 Public benchmark caveats and release discipline#

Caveat What it means for a DeepEval benchmark run
Format sensitivity 9.4 showed a model scoring 0.0 on a question it answered correctly because of a wrapper. Prompt wording, shot order, schema use and parsing each move results
Not leaderboard-comparable DeepEval's prompts, generation-based scoring and fixed shots differ from the published harnesses, so its numbers do not line up with reported ones. Compare only against your own earlier DeepEval runs
Contamination MMLU, GSM8K, HumanEval, HellaSwag, TruthfulQA and others are public and widely present in training data. DeepEval performs no contamination check (10A.2, 6.2)
Fixed shots The first n_shots dev items are used every time. A model or prompt that is accidentally tuned to those shots is rewarded and nothing varies
No intervals A run reports one micro-averaged accuracy. There are no seeds, no standard errors and no per-task intervals. With a few hundred items, differences of a few points are noise (9.10, 10A.2, Part 5)
Micro-averaging Large tasks dominate the overall score. A regression confined to a small task hides inside it; read task_scores
Judge-scored members SQuAD and EquityMedQA depend on a judge and, for EquityMedQA in 4.3.5, on a sign error
Scorer bugs TruthfulQA MC2's scale and HumanEval's missing check() call make two headline numbers meaningless in 4.3.5 and 4.3.6 (9.5, 9.6). Run an oracle and a null through any benchmark before trusting it
Model, not application The wrapper wraps a model call. Retrieval, tools, system prompts and orchestration are absent, so a benchmark win does not predict your product's behaviour

Release discipline. Public benchmarks have a legitimate place in a release process, as a guard against capability regressions in the model layer and as a shortlisting step (10A.10, 5.5):

  1. Pick two or three benchmarks relevant to the capability that matters (reasoning, maths, instruction following), not seventeen.
  2. Pin everything: DeepEval version, benchmark class and arguments, shots, tasks, problem cap, confinement text, model wrapper, temperature, and the dataset revision.
  3. Run the oracle and null controls first: a wrapper that always answers the gold letter must score 1.0, one that always answers "A" must score about the base rate.
  4. Compare to your own previous runs on the same configuration. Compute intervals, a paired comparison and the per-task table (9.10) before calling a one-point change real.
  5. Never use a public benchmark as the gate for an application release. The gate is your goldens, simulations and the metrics you validated (Part 10).

9.10 Defending a benchmark comparison#

A benchmark run gives you one number per model. A decision needs three more things: how uncertain each number is, whether the difference survives pairing (both models answered the same questions), and whether the overall number hides a task that moved. DeepEval computes none of them, but benchmark.predictions and benchmark.task_scores hold everything needed. The probe patches MMLU with two deliberately imbalanced tasks (40 and 8 questions, as real MMLU tasks range from about 100 to over 1,500) and two rule-based models: the candidate fixes four questions in the big task and breaks four in the small one.

python
"""Lesson 10B.6: defend a benchmark comparison. Micro vs macro, Wilson intervals and a paired test."""
import math
import re
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval.benchmarks import MMLU
from deepeval.benchmarks.tasks import MMLUTask
from deepeval.benchmarks.mmlu.template import MMLUTemplate
from deepeval.dataset import Golden
from deepeval.models import DeepEvalBaseLLM

BIG, SMALL = MMLUTask.HIGH_SCHOOL_COMPUTER_SCIENCE, MMLUTask.COLLEGE_MATHEMATICS
SIZES = {BIG: 40, SMALL: 8}  # an imbalanced pair of tasks, as in real MMLU
SHOTS = [{"question": "item S-0: pick A", "choices": ["a", "b", "c", "d"], "answer": 0}]


def tiny_load(self, task):
    """Replace the download with SIZES[task] synthetic rows whose gold answer is always B."""
    self.shots_dataset = SHOTS
    tag = "big" if task == BIG else "small"
    return [
        Golden(input=MMLUTemplate.format_question(
            {"question": f"item {tag}-{i}", "choices": ["w", "x", "y", "z"], "answer": 1},
            include_answer=False), expected_output="B")
        for i in range(SIZES[task])
    ]


MMLU.load_benchmark_dataset = tiny_load


class Rule(DeepEvalBaseLLM):
    """Answers B (correct) when rule(tag, i) is true, otherwise A."""

    def __init__(self, name, rule):
        self.name, self.rule = name, rule
        super().__init__(model=name)

    def load_model(self):
        return self

    def generate(self, prompt, schema=None):
        tag, i = re.findall(r"item (big|small)-(\d+)", prompt)[-1]
        return schema(answer="B" if self.rule(tag, int(i)) else "A")

    async def a_generate(self, prompt, schema=None):
        return self.generate(prompt, schema)

    def get_model_name(self):
        return self.name


def wilson(k, n, z=1.96):
    p = k / 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 centre - half, centre + half


def mcnemar_exact(b, c):
    """Two-sided exact test on the discordant pairs (b: only A right, c: only B right)."""
    n = b + c
    if n == 0:
        return 1.0
    tail = sum(math.comb(n, k) for k in range(min(b, c) + 1)) / 2 ** n
    return min(1.0, 2 * tail)


models = {
    "current": Rule("current", lambda tag, i: i % 5 != 0 if tag == "big" else i not in (0, 4)),
    "candidate": Rule("candidate", lambda tag, i: i % 10 != 0 if tag == "big" else i in (1, 2)),
}
correct = {}
for name, model in models.items():
    benchmark = MMLU(tasks=[BIG, SMALL], n_shots=1)
    result = benchmark.evaluate(model=model)
    preds = benchmark.predictions
    correct[name] = preds["Correct"].tolist()
    k, n = int(preds["Correct"].sum()), len(preds)
    macro = benchmark.task_scores["Score"].mean()
    low, high = wilson(k, n)
    per_task = dict(zip(benchmark.task_scores["Task"], benchmark.task_scores["Score"]))
    print(f"{name:9} overall (DeepEval, micro) {result.overall_accuracy:.3f} | macro {macro:.3f} "
          f"| Wilson 95% [{low:.3f}, {high:.3f}] | per task {per_task}")

b = sum(1 for x, y in zip(correct["current"], correct["candidate"]) if x and not y)
c = sum(1 for x, y in zip(correct["current"], correct["candidate"]) if y and not x)
print(f"paired: only current right {b}, only candidate right {c}, exact McNemar p = {mcnemar_exact(b, c):.3f}")
Output · real, progress lines removed4 lines
current   overall (DeepEval, micro) 0.792 | macro 0.775 | Wilson 95% [0.657, 0.883] | per task {'high_school_computer_science': 0.8, 'college_mathematics': 0.75}
candidate overall (DeepEval, micro) 0.792 | macro 0.575 | Wilson 95% [0.657, 0.883] | per task {'high_school_computer_science': 0.9, 'college_mathematics': 0.25}
paired: only current right 4, only candidate right 4, exact McNemar p = 1.000
[netguard] total blocked attempts: 0 []

What each statistic says, and what it misses:

  • Micro-average (DeepEval's overall): identical, 0.792 for both. On this number the candidate is a safe swap.
  • Wilson interval: [0.657, 0.883] for both, 23 points wide with 48 questions. Even if the overall numbers differed by 5 points, intervals this wide could not separate them. The Wilson interval is the standard interval for a pass rate; unlike the textbook "p plus or minus 1.96 standard errors", it stays inside 0 to 1 and behaves near 0 and 1 (10A.2, Part 5 gives the sample sizes it implies).
  • Paired test: because both models saw the same questions, only the discordant pairs carry information (questions exactly one model got right). Four go each way, and the exact McNemar test (a binomial test on those discordant counts) gives p = 1.0. Pairing is usually far more sensitive than comparing two intervals; here it correctly says the totals are a wash. evalkit's paired bootstrap (10A.8, 4.1) is the general-purpose version.
  • Macro-average and the per-task table: 0.775 against 0.575, and the small task fell from 0.75 to 0.25. This is the finding. Every pooled statistic missed it because the big task outvoted the small one. With only 8 questions the small task's own interval is wide too, so the right response is not "reject the candidate" but "this slice needs more questions before we decide".

The habit to build: report the micro and macro averages, an interval for each model, a paired test on the same items and the per-task table, and decide on the slices you care about, not on the pooled number. That is the same discipline 10A.8 applies to your own eval suite.

9.11 An in-house benchmark built from goldens#

For an application team, the most useful "benchmark" is rarely a public one. It is a fixed set of multiple-choice or short-answer questions about your domain, written and reviewed by your team, kept as goldens and scored with the ordinary evaluate() machinery. You get everything this lesson built: provenance in additional_metadata, slices, version control, the metrics' reports, CI gates. And because you write the parser, you decide what counts as an answer, rather than inheriting a benchmark class's exact-match rule.

python
"""Lesson 10B.6: an in-house multiple-choice benchmark as goldens, scored with ExactMatch in evaluate()."""
import re
import warnings
warnings.filterwarnings("ignore")

import netguard
from deepeval import evaluate
from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate.configs import AsyncConfig, DisplayConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.test_case import LLMTestCase

# Five questions about YOUR product, written and reviewed by your team.
QUESTIONS = [
    ("Refunds are issued within how many business days? A) 2 B) 5 C) 10 D) 30", "B", "refunds"),
    ("Which method receives a refund? A) gift card B) bank transfer C) original payment method D) cash", "C", "refunds"),
    ("How much does express shipping cost? A) $5 B) $10 C) $15 D) free", "C", "shipping"),
    ("Standard shipping takes? A) 1 day B) 3-5 business days C) 2 weeks D) same day", "B", "shipping"),
    ("Can an order be cancelled after dispatch? A) yes, online B) no C) only by phone D) only for gift cards", "B", "orders"),
]
dataset = EvaluationDataset(goldens=[
    Golden(input=q, expected_output=gold, additional_metadata={"slice": s, "source": "human-authored"})
    for q, gold, s in QUESTIONS
])


def chatty_app(question: str) -> str:
    """A stand-in for your app: right on four questions, and it always answers in a sentence."""
    answers = {"Refunds": "B", "Which": "C", "How": "C", "Standard": "D", "Can": "B"}
    return f"The answer is {answers[question.split()[0]]}."


def parse_letter(text: str) -> str:
    """The parser is part of the benchmark: version it and test it like code."""
    found = re.findall(r"\b([A-D])\b", text.upper())
    return found[-1] if found else ""


for label, transform in [("raw output", lambda text: text), ("parsed letter", parse_letter)]:
    cases = []
    for golden in dataset.goldens:
        raw = chatty_app(golden.input)
        cases.append(LLMTestCase(
            input=golden.input,
            actual_output=transform(raw),
            expected_output=golden.expected_output,
            metadata={**golden.additional_metadata, "raw_output": raw},
        ))
    result = evaluate(
        cases,
        metrics=[ExactMatchMetric()],
        async_config=AsyncConfig(run_async=False),
        display_config=DisplayConfig(show_indicator=False, print_results=False),
    )
    passed = [r.success for r in result.test_results]
    print(f"{label:13} passed {sum(passed)}/{len(passed)}:",
          [(r.metadata["slice"], r.success) for r in result.test_results])
Output · real, DeepEval's run banners removed3 lines
raw output    passed 0/5: [('refunds', False), ('refunds', False), ('shipping', False), ('shipping', False), ('orders', False)]
parsed letter passed 4/5: [('refunds', True), ('refunds', True), ('shipping', True), ('shipping', False), ('orders', True)]
[netguard] total blocked attempts: 0 []

The same five replies score 0 out of 5 as raw text and 4 out of 5 after the parser, which is the 9.4 lesson again, now under your control. Three things make this more defensible than a benchmark class:

  1. The parser is explicit, versioned and testable. Write unit tests for it ("The answer is B.", "b", "B) Queue", "I think A, no wait, B"), and store the raw reply in metadata (as the sample does) so a parser change can be re-scored without re-running the app.
  2. The questions are yours and private, so contamination is not the question it is for MMLU, as long as they stay out of prompts, few-shot examples and fine-tuning data (10A.2, 6.2).
  3. Slices are first-class. The failure is in shipping; with 30 or more questions per slice you can report per-slice rates with intervals as in 9.10.

Keep the format question in mind, though: multiple choice measures recognition, not the free-text answers your users get. Use it for knowledge and policy regression (did the new model or prompt forget the refund window?), and keep reference-based and judge-based metrics on free-text goldens for answer quality.


Reference

10.1 Which data source answers which question#

Question Use Why Main risk
Does the current app version still answer known questions correctly? Hand-written or reviewed goldens, generated at eval time Stable references, version-independent Slow growth, limited coverage
What kinds of inputs might we be missing? Synthesizer from contexts or docs Cheap coverage ideas Silver labels, homogeneity
Where does my RAG fail across the corpus? Synthesizer from docs plus human review Corpus-grounded questions Unanswerable items, chunk quality
We have 10 good questions and need 100 Synthesizer from goldens Paraphrase and variation Copies the seeds' blind spots
Does the assistant survive a multi-turn task? ConversationSimulator with failure-path goldens Conversations without real users Simulator validity
Do we regress on a specific dialogue shape? Simulation graph Deterministic user Narrow coverage
Did the model layer lose capability after a swap? deepeval.benchmarks Standard tasks, quick Format sensitivity, contamination, scorer bugs
Does the new model or prompt still know our policies? In-house multiple-choice goldens (9.11) Your domain, your parser, private Recognition is not free-text quality
Does the system satisfy a policy or grading rule? evalkit or DeepEval metrics on your own goldens Your rubric, your data Judge validity (10A.5)
Is the model or app safe against attack? Red teaming (10B.7) Adversarial inputs Coverage
Symptom Likely cause Where to look
Dataset score is much lower after regenerating goldens New goldens are harder, not the app worse Evolution mix and length in metadata (6.3)
App scores near 1.0 on synthetic goldens Generator and judge share a family, or leakage Different families; overlap check (6.1)
TypeError mixing goldens Single-turn and multi-turn in one dataset 1.6
ValueError: No Confident API key on push or pull Cloud methods without a key 1.8
ConnectionError to openaipublic.blob.core.windows.net tiktoken first-use download 5.4
IndexError: list index out of range in synthesis Model returned too many inputs 5.5
Low-quality inputs in the golden set "Filtration" keeps rewritten inputs 3.3, 6.2
Every simulated conversation has 10 user turns No expected_outcome, so the cap decides 7.4
Simulation passes but users complain Easy user, early stop, leakage or sycophancy Part 8
Final assistant turn reacts oddly to "Thanks, bye." Terminal node still gets a reply 7.6
MMLU score is absurdly low Prediction is a sentence, not a letter 9.4
EquityMedQA accuracy is high for a biased model Inverted scoring in 4.3.5 9.7
ModuleNotFoundError: deepeval.benchmarks.task Docs use the singular path 9.2
TypeError from EvaluationDataset(test_cases=...) The constructor takes goldens 1.5
Conversational goldens from scratch all run to the cap Scratch scenarios have no expected_outcome 2.3
A graph conversation ends early with no reason recorded A node's max_visits was used up 7.6
TruthfulQA MC2 accuracy is 85.0, or jumps to 1.0 when batched Recall percentage summed sequentially, "any overlap" when batched 9.5
HumanEval overall is 1.0 for a weak model The tests are defined, never called; overall counts any passing sample 9.6
HumanEval run hangs A sample loops forever and secure_exec has no timeout 9.6
GSM8K scores 0 for a model that shows its working No number extraction: the whole reply is exact-matched 9.5
Two models tie on MMLU, users notice a regression Micro-average hides a small task 9.10

10.3 A short plan for a new project#

  1. Start with 30 to 50 hand-written goldens from real questions, in JSONL under git, with a dataset card (1.8).
  2. Add synthetic goldens from your documents, one slice at a time, through the acceptance process of Part 6. Keep them in a separate file marked source: synthetic.
  3. Write 10 to 20 conversational goldens for failure paths, with an outcome you can check deterministically where possible, and run them with a simulator whose controls you have run (Part 8).
  4. Run a public benchmark only when you change the model layer, and compare to your own history.
  5. Wire the whole thing into CI with the runner of 10B.2 and the gates of 10B.7, and keep 10A.5's judge calibration current.

10.4 evalkit ↔ DeepEval: the mapping for this lesson#

evalkit (10A.1 to 10A.12) DeepEval 4.3.5 What differs
EvalExample, EvalDataset, DatasetCard, load_dataset, save_dataset (10A.2, 8.2) Golden, ConversationalGolden, EvaluationDataset with JSON/JSONL/CSV loaders and save_as evalkit has a card, a content hash and a Provenance model; DeepEval has none of the three, so keep a card file beside the JSONL (1.8)
make_splits, stratified_sample (10A.2) Nothing Split goldens yourself and record the split in additional_metadata
dedupe with shingles and Jaccard (10A.2, 6.5) Nothing Run evalkit's dedupe (or embeddings) on synthetic batches (6.3)
run_eval over stable examples (10A.1, Part 6) Generate at eval time, then evaluate() (1.2) Same pattern; DeepEval adds reporting, caching and the pytest runner
The 10A.2 generate, critique, rewrite, validate recipe Synthesizer and its configs (Parts 2 to 5) DeepEval's critic rewrites and keeps; the validation and acceptance steps of 10A.2 are not included (Part 6)
A simulated user wrapped in an AgentFn (10A.7, 6.1) ConversationSimulator with a model_callback (Part 7) DeepEval packages the loop, stopping and graphs; evalkit leaves the user model to you
sim_validation.py: realism_report, discriminability, goal_fidelity, leakage_rate, termination_report, predictive_validity, simulator_panel, validity_card (10A.12, 7.10 and 7.15) Nothing Convert simulated ConversationalTestCases into evalkit Conversations and run the battery (Part 8)
wilson_interval (10A.7), paired_bootstrap_ci, sign_flip_permutation_p (10A.8, 4.1) A single micro-averaged overall_accuracy Compute intervals, paired tests and per-task tables from benchmark.predictions (9.10)
Benchmark literacy and shortlisting (10A.10, Part 5) deepeval.benchmarks (Part 9) DeepEval runs the benchmarks; 10A.10's eight distortions all still apply, plus the scorer bugs in 9.5 to 9.7

10.5 Where the docs and the code disagree#

The official docs are the best place to learn the surface of these features, but where they disagree with 4.3.5 (and 4.3.6), this lesson teaches the code.

Topic The docs say 4.3.5 does
Hugging Face datasets Python supports JSON, JSONL, CSV and Hugging Face datasets No Hugging Face loader on EvaluationDataset (1.5)
EvaluationDataset(test_cases=...) Used in a CI guide TypeError; use add_test_case (1.5)
Filtration A quality filter for synthetic inputs Rewrites and keeps; never drops an input or a scenario (3.3, 4.3)
Document synthesis offline Not mentioned tiktoken downloads a vocabulary on first use (5.4)
Over-generation Not mentioned IndexError in sync mode, silent truncation in async mode (5.5)
on_turn hook Not on the lifecycle-hooks page In the simulate() signature; fires after every turn (7.7)
Task enum import deepeval.benchmarks.task deepeval.benchmarks.tasks (9.2)
batch_size Works for every benchmark except HumanEval and GSM8K Used by eight classes; the others swallow it (9.3)
Benchmark fidelity Follows the original implementations MMLU generates a letter instead of comparing log-probabilities (9.4); DROP has no F1; TruthfulQA MC2 is recall (9.5)
TruthfulQA overall_score Ranges from 0 to 1 0 to 100 for MC2 in the sequential loop (9.5)
HumanEval pass@k over unit tests Tests never called; overall counts any passing sample (9.6)
Bias direction Higher is better since 4.2.0 EquityMedQA still flips it (9.7); no docs page for EquityMedQA

10.6 Older code and tutorials#

Current names first; when a tutorial or an older repository uses one of these, this is what replaced it (as of 4.3.5).

You may see Use instead Status in 4.3.5
ConversationalGolden(user_description="...") persona=Persona(characteristics="...") Deprecated, warns; passing both raises an error
ConversationSimulator(controller=...) stopping_controller=... Deprecated alias, warns
ConversationSimulator(user_intentions=..., user_profile_items=...) (early simulator API) ConversationalGolden scenarios and personas passed to simulate() Removed: TypeError
LLMTestCase(additional_metadata=...) metadata=... (goldens keep additional_metadata) Accepted as an input alias; attribute access warns (1.2)
from deepeval.benchmarks.task import MMLUTask from deepeval.benchmarks.tasks import MMLUTask Never existed in this form: ModuleNotFoundError
EvaluationDataset(test_cases=[...]) EvaluationDataset(goldens=[...]) plus add_test_case TypeError
pull(alias, auto_convert_goldens_to_test_cases=True) Pull goldens and generate at eval time (1.2) Still a parameter; a cloud call that needs a key

When a tutorial and the installed package disagree, the package wins: inspect.signature(...), the source, and the prompts a fake judge records describe what you actually have.


Common misconceptions#

Misconception Reality
"A Golden is a test case without an output yet, so I can store the output in it." A golden is the durable stimulus and reference. Storing actual_output in it risks grading an old app version. Generate outputs at eval time (1.2).
"EvaluationDataset can load Hugging Face datasets." In 4.3.5 it loads JSON, JSONL and CSV only. Load Hugging Face data yourself and construct goldens (1.5).
"I can keep single-turn and conversational goldens in one dataset." Mixing raises TypeError; keep separate files (1.6).
"push and pull are just file operations." They are Confident AI cloud calls and fail without a key. Use JSONL in git for local versioning (1.8).
"The Synthesizer's filtration removes bad inputs." It rewrites and keeps. Enforce your own threshold after generation (3.3, 6.2).
"Synthetic expected_output is ground truth." It is a silver label from the same model and context that wrote the question (3.6).
"synthetic_input_quality tells me how good the final golden is." It scores the text before the last rewrite, and it is a critic's opinion (3.8).
"Scratch generation gives me a labelled dataset." It gives inputs only: no critic pass and no expected output (4.1).
"generate_goldens_from_docs works offline once installed." tiktoken downloads a vocabulary on first use; the run needs network access once (5.4).
"The Synthesizer handles a model returning too many inputs." In 4.3.5 the sync path raises IndexError (5.5).
"The simulator knows when the task is done." Only if the golden has an expected_outcome, and then a simulator model, uncalibrated, decides. Otherwise the cap decides (7.4).
"A persona guarantees the simulated user behaves like that persona." A persona is prompt text; adherence is unmeasured (7.3, Part 8).
"A high simulated pass rate means users will succeed." It is a rate under one simulator version until calibrated against real outcomes (8.2).
"DeepEval's MMLU number can be compared with the published MMLU number." Different prompt, parsing, shots and scoring method (9.4).
"HumanEval in DeepEval runs code in a sandbox." It uses an in-process exec with an allow-list. Isolate the whole job yourself (9.6).
"EquityMedQA scores are safe to report." In 4.3.5 the scoring is inverted by a stale flip (9.7).
"DeepEval's HumanEval runs the unit tests." It defines the test function and never calls it, and its overall score counts any passing sample out of n (9.6).
"batch_size only changes speed." For TruthfulQA MC2 it changes the scale and meaning of the score (9.5).
"Same overall benchmark score means no regression." A micro-average can hide a collapsed small task; read the per-task table and the paired comparison (9.10).
"DROP uses a lenient containment scorer." It is a normalized exact match against any accepted answer, with no partial credit (9.5).

Key takeaways#

  • A golden is the reusable stimulus and reference; the test case is a measurement of one app version. Keep actual_output out of durable goldens and generate it at eval time, so the same dataset evaluates every version.
  • Golden needs only input; ConversationalGolden needs scenario, and carries a hidden expected_outcome and a Persona. Single-turn and multi-turn goldens never share a dataset. Keep persona (who the user is) apart from scenario and outcome (what they want).
  • EvaluationDataset reads and writes JSON, JSONL and CSV (CSV needs pandas), has no Hugging Face loader, and its push, pull, queue and version methods are Confident AI cloud features that fail closed without a key. Version datasets as immutable JSONL files with a card, in git.
  • The Synthesizer is a proposal generator with provenance, not a dataset factory. It has four generation paths and conversational twins, five config objects and a CLI. The contexts pipeline is generate, critique, rewrite, evolve, style, then write a reference; 21 calls for two contexts and two goldens each in the probe.
  • Filtration never drops an input: after the retry budget the last rewrite is kept, and the recorded score predates it. Write the acceptance filter yourself: quality threshold, faithfulness of the reference to the context, dedup, diversity, human review of a random sample.
  • Seven evolutions (reasoning, multi-context, concretizing, constrained, comparative, hypothetical, in-breadth) descend from Evol-Instruct and WizardLM. They add difficulty and variety, and they distort realism (a 15-word cap, multi-hop phrasing). Weights are sampling weights with no seed parameter.
  • Scratch and no-context generation produce no references and no critic pass. Seed expansion copies the seeds' blind spots. Document generation adds chunking in tokens, an embedder, a context-quality score and Chroma neighbour expansion, which together give coherence-by-similarity and no coverage guarantee.
  • Document synthesis has two sharp edges in 4.3.5: tiktoken's first-use download from a public Azure host (fails on locked-down runners), and an IndexError when the model returns more inputs than requested.
  • ConversationSimulator plays the user with a model, calls your callback, and stops by cap, controller, node visits or terminal node. The expected outcome is hidden from the simulated user; without one, conversations run to the cap. The default outcome check is an uncalibrated judge; a custom controller (end, proceed) is cheaper and reproducible.
  • Simulation graphs script the user and use one EdgeChoice call per branch point. They are the right tool for regression on known dialogue shapes; the free simulator is for discovery. There is no tracing and no cost report for custom models, so version the instrument and count the calls.
  • DeepEval ships no simulator validation. Run termination mix, null-app and leakage checks every time, and the realism, calibration and predictive-validity checks of 10A.12, Part 7 before you trust a simulated pass rate.
  • The 17 benchmark classes run a raw model through a Hugging Face dataset with fixed shots and a DeepEval template; scoring is mostly exact match, micro-averaged. A chatty model scored 0.0 where a schema model scored 0.5 on the same facts: the harness is part of the number.
  • HumanEval runs generated code in-process with no timeout (not a sandbox), never calls the tests, and reports the share of problems with any passing sample; TruthfulQA MC2 is a recall percentage whose scale changes with batch_size; SQuAD and EquityMedQA need a judge; EquityMedQA's scoring is inverted. All of these hold in 4.3.5 and 4.3.6. Run an oracle and a null through any benchmark before you trust it.
  • Defend a benchmark comparison with micro and macro averages, Wilson intervals, a paired test on the same items and the per-task table. Use public benchmarks for model-layer regressions against your own history, never as an application release gate; for policy and knowledge regressions, an in-house multiple-choice set built from goldens with a tested parser is usually the better instrument.

Terms introduced in this lesson#

Term One-line definition
Golden DeepEval's durable dataset row: an input plus optional references (expected output, context, expected tools), with no application output
ConversationalGolden A scenario to be simulated: scenario, hidden expected outcome, persona and context, with no turns until a simulation or import fills them
Persona A description of the simulated user (name, characteristics, speaks-first flag) separate from the scenario; its voice fields are ignored by text simulations
EvaluationDataset A collection of goldens (single-turn or multi-turn, never both) with JSON, JSONL and CSV loaders and savers
Generate at eval time Running the current app on each golden and building fresh test cases, so one dataset serves every app version
Synthesizer DeepEval's generator of synthetic goldens from contexts, documents, existing goldens or a style description
Evolution A weighted rewrite step that makes a generated input harder or broader; seven types descended from Evol-Instruct and WizardLM
Filtration (DeepEval) A critic and rewrite loop that scores a candidate input and rewrites weak ones, but keeps the last rewrite when retries run out
Silver label A reference answer produced by a model rather than verified by a person; useful, cheap and not ground truth
Context construction The documents-path front end: token chunking, embedding, context-quality scoring and nearest-neighbour grouping into contexts
ContextScore The critic's four 0-to-1 scores for a chunk (clarity, depth, structure, relevance), whose mean is the context quality
ConversationSimulator DeepEval's class that plays a user with a model, calls your callback and returns ConversationalTestCase objects
Model callback Your function that wraps the application for simulation, returning an assistant Turn; arguments are filled by name
Stopping controller A function (or the default expected-outcome check) that returns end(reason=...) or proceed() before each user turn
Simulation graph A set of SimulationNode objects with scripted user actions and natural-language edges, routed by one EdgeChoice model call per step
Simulator validity Evidence that a simulated user's scores track real-user outcomes; DeepEval provides the instrument, not that evidence
Benchmark class One of the 17 deepeval.benchmarks classes that runs a raw model through a public dataset with a fixed template and scorer
Micro-average Overall accuracy computed as total correct over total questions, so larger tasks weigh more
pass@k The probability that at least one of k sampled programs passes the tests, estimated unbiasedly from n samples
Confinement instruction A sentence DeepEval appends to a benchmark prompt, when schema= is unsupported, to force a bare answer
Macro-average The mean of per-task scores, so every task counts equally regardless of its size
Wilson interval A confidence interval for a pass rate that stays within 0 to 1 and behaves well for small samples and extreme rates
Discordant pair A question that exactly one of two compared models answered correctly; the only items a paired test such as McNemar's uses
Hybrid simulation graph A simulation graph that mixes scripted user nodes with default_simulation_node() branches the simulator model improvises
Normalized exact match Exact match after lower-casing and removing punctuation, articles and extra whitespace; DeepEval's DROP scorer

Exercises#

All exercises use the files from this lesson's ran/ folder and run keyless unless stated.

  1. Dataset round trip (1.4). Add a second golden with retrieval_context and tools_called-style data to dataset_roundtrip.py, save as CSV, and reload. Which fields survive, and what delimiter splits each list?
  2. Mixing rule (1.6). Split a mixed list of goldens into two datasets by type and save them under names that follow the versioning pattern of 1.8. Write the card fields for each.
  3. Read a prompt (3.1). Run synthesizer_contexts.py, open the RewrittenInput prompt in ran/prompts_synth, and find the instruction that tells the model what to do with the critic feedback.
  4. Add the missing gate (6.2). Extend filter_synthetic_goldens.py with a third gate that rejects any golden whose expected_output is shorter than three words. Which of the three goldens survive?
  5. Beat the lexical dedup (6.3). Add two more paraphrases to dedup_and_mix_check.py that the difflib check misses, then replace the similarity function with word-set Jaccard similarity. Does it catch them? What threshold do you need, and what does that threshold do to genuinely different inputs?
  6. Trigger and contain the crash (5.5). Wrap the call in synthesizer_overgeneration.py so that on IndexError it retries one context at a time. Record how many model calls the failed attempt consumed.
  7. Stopping reasons (7.5). Write a stopping controller that ends the conversation with a reason when the assistant repeats the same reply twice, and another reason on the cap. Run it with a stuck callback and print the reasons.
  8. Graph a hostile user (7.6). Build a four-node graph for a user who asks, pushes back twice after refusals, then leaves. Use a callback that always refuses, predict the number of model calls, then run it.
  9. Validity controls (8.3 and 8.4). In simulator_validity_checks.py, add a third app that claims "Refund issued. Confirmation number R-00." to every message without checking. What does the scripted outcome checker do with it, and what does that say about trusting a stop check?
  10. Format sensitivity (9.4). Add a SloppyModel to benchmark_mmlu.py that answers "b" in lower case and one that answers "B." with a full stop. Predict each overall score, then run them.
  11. Null and oracle for a benchmark (9.9). With the patched loader, write a wrapper that returns the gold letter (look up the answer by question text) and one that always returns "A". Check that they score 1.0 and the base rate of the patched rows.
  12. Fix TruthfulQA MC2 (9.5). From the benchmark.predictions of benchmark_truthfulqa_mc2.py, compute per-question precision and recall of the picked options and their averages. Which picker wins now, and which single number would you report?
  13. Two personas, one app (7.3 and 8.2). Run conversation_simulator.py's Run A golden under two personas (the brief, polite Sam and a new impatient, vague persona) with a scripted simulated user for each, and score both conversations with ConversationCompletenessMetric and the fake judge. Then explain, using 10A.12, 7.12, why a score difference between the personas tells you nothing yet about how real impatient users will fare.
  14. Your own benchmark (9.11). Add five questions about a domain you know to inhouse_benchmark.py, write a SloppyApp that answers "b)" or "Option B" styles, and write four unit tests for parse_letter. Which reply styles does the parser miss? Fix it, and say why the raw reply stored in metadata lets you re-score without re-running the app.
  15. HumanEval, repaired (9.6). In humaneval_patched.py, add a fifth sample that loops forever behind an if that the tests would trigger. Predict what DeepEval reports (do not run it with the real loop: replace the loop with raise TimeoutError to stand in for the timeout you would add), then write the five lines that compute c and pass@1 the reference way.
  16. Provider run (not keyless). With a real key and n_problems_per_task=20, run MMLU on one task for two models. Compute a Wilson interval for each accuracy with the helper from 10B.2, 6.6 or your own, and say whether the difference is distinguishable from noise.
Answers
  1. CSV keeps input, expected_output, context, retrieval_context and tools_called, with additional_metadata as JSON text in a cell. By default context and retrieval_context are split on |, and tools_called and expected_tools on ;. Pass the *_col_delimiter arguments if your text contains those characters.
  2. Two files, for example refunds.v1.jsonl and refund_chats.v1.jsonl, each with a card: source, corpus or log version, generator (if synthetic) and its settings, DeepEval version, filters applied, reviewer, date, row count and a content hash. The point is that the single-turn and multi-turn contracts are separate artefacts.
  3. The prompt begins "I want you to act as a query rewriter. Based on the provided context, original query, and feedback, generate a rewritten query that improves its clarity and answerability based on the feedback provided." It carries two worked examples, forbids prior knowledge, and ends with the context, the query and the critic's feedback.
  4. Add a third list comprehension keeping goldens with len((golden.expected_output or "").split()) >= 3. The one golden that survived both earlier gates ("How long does a refund take?") has a six-word reference, so the third gate keeps it; run the gate on all three goldens and the two earlier rejects stay rejected for their own reasons. The gate earns its keep on real batches, where one-word references appear.
  5. A lexical Jaccard on word sets catches a paraphrase only if it keeps most of the words. Lowering the threshold enough to catch loose paraphrases starts merging genuinely different questions that share function words. That trade-off is why real dedup uses embeddings and a threshold tuned by reading borderline pairs.
  6. The failed attempt consumed the candidate-generation call and some critique and rewrite calls before the IndexError (four calls in the probe: SyntheticDataList, two InputFeedback, one Response). Retrying one context at a time bounds the loss to that context, though a model that over-generates will do so again; also lower max_goldens_per_context or add the count to the prompt styling.
  7. A controller that takes turns and last_assistant_turn, compares the last two assistant contents, and returns end(reason="repeated reply"), with the cap handled by DeepEval itself. The cap shows up as a conversation whose user-turn count equals max_user_simulations and which was never ended by a reason, so record that in your own results because DeepEval does not label it.
  8. Chain ask, push1, push2 and a terminal leave, each linked to the next with when="The assistant refused". The router runs after each assistant reply at a node that has outgoing edges, so you should see three EdgeChoice calls (after the replies to ask, push1 and push2) and none at leave, which has no edges. The conversation then has four user turns and four assistant replies. Script the router answers with index 1 each time.
  9. The scripted checker answers "complete" because the confirmation phrase appears, so the always-claims app stops by outcome after a single user turn. The checker (and an LLM that only reads the transcript) cannot tell a real refund from a claimed one. The fix is a controller or metric that checks the state (a refund tool call or database row), not the words.
  10. "b" fails exact match ("b" != "B") so its score is 0.0 even though it is the right letter; "B." also fails. Both would be fixed by a wrapper that normalizes to the capital letter, or by honouring schema=, which constrains the answer to a literal. The lesson: exact match is case- and punctuation-sensitive.
  11. The oracle scores 1.0 and the always-"A" wrapper scores the fraction of rows whose gold letter is A (0 for the two patched rows, since the answers are B and C). If either differs, your wrapper or parser is broken, which is the point of the controls.
  12. With every pick scored on precision and recall, the precise picker has precision 1.0 and recall 1.0; "everything" has recall 1.0 but precision 0.5; "half" has precision 1.0 and recall 0.5; "wrong" scores 0 on both. Report a single F1 (or both numbers) rather than DeepEval's recall-only percentage, and say plainly that it is not the original log-probability MC2.
  13. Whatever the scores, both conversations come from one simulator model playing two prompts. A difference shows that the app behaves differently against those two scripted or generated users, not that real impatient users succeed less often: predictive validity requires comparing simulated scores with real outcomes for the same app versions (10A.12, 7.12). The persona may also not be played faithfully (sycophancy, 7.3), which is a fidelity question to check first.
  14. Typical misses: lower-case letters without a word boundary, "Option B" if the regex is anchored, and replies that mention several letters ("not A but B"), where taking the last letter is a policy choice you should test. Storing the raw reply means a parser fix is a re-score of saved text, so it is cheap, reproducible and does not depend on the app answering the same way twice.
  15. The stand-in raises inside exec, so DeepEval counts it as a failed sample, while a real infinite loop would hang the run because secure_exec has no timeout. The reference count runs prompt_imports + sample + test + "\ncheck(entry_point)" for each sample in an isolated process with a time limit, increments c on success, and calls Scorer().pass_at_k(n, c, 1); report the mean of per-problem pass@1, not the share of problems with any pass.
  16. With 20 problems per task, a Wilson 95 percent interval is wide: for example 14 of 20 correct gives roughly 0.48 to 0.85. Two models whose accuracies differ by a few points will have heavily overlapping intervals, so the difference is not distinguishable from noise at this sample size. You need hundreds of items per comparison.

Check yourself#

  1. What is the difference between a Golden and an LLMTestCase, and why does DeepEval keep them separate?
  2. Two models score 0.79 overall on a two-task benchmark. Why might one of them still be a regression, and which two numbers would show it?
  3. Name two EvaluationDataset methods that need Confident AI and say how they fail without a key.
  4. Name two reasons DeepEval's HumanEval overall score can be 1.0 for a model that writes wrong code.
  5. What does "filtration" do to a synthetic input that never reaches the quality threshold?
  6. Why is synthetic_input_quality not a validated quality score for the final golden?
  7. Which entry points produce no expected_output, and why?
  8. Why can generate_goldens_from_docs fail on a machine with no internet even though you pass a fake embedder and a fake judge?
  9. In the simulator, who decides when a conversation ends if the golden has no expected_outcome?
  10. Why is the expected outcome not shown to the simulated user, and what in the prompts could still leak information?
  11. What does a simulation graph's EdgeChoice call do, and what happens when no edge matches?
  12. Name three checks from 10A.12, Part 7 that DeepEval does not provide and one you can do from the simulator's own output.
  13. A ChattyModel answers "The answer is B" and scores 0.0 on a question whose answer is B. Why, and what does it teach?
  14. Why is DeepEval's HumanEval execution not a sandbox, and what should you do instead?
  15. What is wrong with EquityMedQA scoring in DeepEval 4.3.5, and how would you have detected it?

Further resources#

Papers and reference implementations:

  • Xu et al., "WizardLM: Empowering large pre-trained language models to follow complex instructions" (Evol-Instruct): arXiv 2304.12244, the lineage of the Synthesizer's evolutions
  • Wang et al., "Self-Instruct: Aligning Language Models with Self-Generated Instructions": arXiv 2212.10560
  • Hendrycks et al., "Measuring Massive Multitask Language Understanding" (MMLU): arXiv 2009.03300
  • Chen et al., "Evaluating Large Language Models Trained on Code" (HumanEval and pass@k): arXiv 2107.03374
  • Lin et al., "TruthfulQA: Measuring How Models Mimic Human Falsehoods": arXiv 2109.07958
  • Zheng et al., "Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena": arXiv 2306.05685, the biases a judge-scored benchmark or stop check inherits
  • Dua et al., "DROP: A Reading Comprehension Benchmark Requiring Discrete Reasoning Over Paragraphs": arXiv 1903.00161, for the original EM and F1 scoring
  • Zhou et al., "Instruction-Following Evaluation for Large Language Models" (IFEval): arXiv 2311.07911, for strict and loose, prompt- and instruction-level accuracy
  • OpenAI, human-eval, the reference HumanEval harness (see how it appends check(entry_point)): https://github.com/openai/human-eval
  • EleutherAI, lm-evaluation-harness, a widely used reference implementation for comparing published benchmark numbers: https://github.com/EleutherAI/lm-evaluation-harness

Within this course: 10A.2 for dataset design (Parts 1 to 8) and for the synthetic-data craft this lesson maps onto (Parts 9 to 20), 10A.12, Part 7 for simulator validity, 10A.10, Part 5 for benchmark literacy, 10B.4 and 10B.5 for the metrics that score what this lesson produces, 10B.7 for red teaming and the platform, and 10B.17 for choosing between DeepEval and Inspect.


← 10B.5: DeepEval Tracing, Component-Level Evals and Agent Evaluation | Module 10B overview | 10B.7: DeepEval in Production: Red Teaming, CI/CD, Prompt Optimization and Confident AI →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close