10B.17 DeepEval or Inspect? Choosing, Combining and Migrating (optional)
Sixteen lessons taught two packages. 10B.2 to 10B.7 opened DeepEval, and 10B.8 to 10B.16 opened Inspect AI, each against the same yardstick: evalkit, the small harness you built in 10A.1 to 10A.12. This lesson is the one a team lead actually needs. Which of the two should we use? Can we use both without ending up with two definitions of "correct"? How do we move our existing evals onto one of them, or from one to the other, without losing the numbers we have already shown people? And which of the traps from the last sixteen lessons will bite us first?
The answers are not a feature matrix. A feature matrix goes stale in a week (both packages release every few days) and misses what decides the outcome: what question each tool lets you ask cheaply, what it leaves you to build, and what it quietly does to a number on the way to your dashboard. So this lesson compares the two on every axis that matters (philosophy, data model, metrics versus scorers, judges and their prompts, agents and sandboxes, statistics, logs, CI, platform and lock-in, licence and governance, cost), and then does something a table cannot: it runs the same three evals in both (the ticket-triage eval of 10A.1, a docs_qa RAG eval and the support agent of 10A.7) and reads the results side by side. Every sample is keyless and was run for real, with DeepEval 4.3.6 and inspect-ai 0.3.292, using the scripted judge of 10B.2 and mockllm/model.
The middle of the lesson is about combining. You will write a check once and wrap it for both frameworks, call a DeepEval metric from inside an Inspect scorer, feed Inspect logs into evalkit's paired statistics, use one evalkit judge in both, score a run made in one framework with the other framework's scorers, and gate both in a single exit decision. Then comes migration (from evalkit, from DeepEval to Inspect and back, and across the version changes of the last six months, including the DeepEval 4.3.6 red-teaming move and the date deepteam is deprecated), the patterns and anti-patterns that matter when two frameworks live in one repository, and the lesson's practical centrepiece: one pitfalls checklist that collects the surprises of 10B.2 to 10B.16, with a scanner that finds the ones a regular expression can find.
What you'll learn
- A method for comparing two eval frameworks fairly: the axes that decide, the questions each tool makes cheap or expensive, and how to avoid comparing a framework's defaults with the other's best case
- The comparison on every axis, with measured facts: philosophy and unit of work, data model, metrics versus scorers, how each package's judges ask for scores and what that costs in calls, agents, tools and sandboxes, statistics, logs and analysis, CI, platform and lock-in, licence, governance and release cadence, and what a case costs in judge calls
- The same three evals in both packages, run keyless: triage,
docs_qaRAG and the support agent, with a reading of what each framework's result actually answers and where the two disagree for a good reason - Combining: one check wrapped for both frameworks, a DeepEval metric inside an Inspect scorer, Inspect logs into
evalkit's paired bootstrap, oneevalkitjudge in both frameworks, DeepEval grading an Inspect log and Inspect grading recorded DeepEval outputs, and a single fail-closed gate that also catches errored spans and skipped metrics in traced DeepEval runs - Why a reliability number (pass@k, pass^k) is not portable between the two frameworks unless the success threshold moves with it, shown on the same attempts in both
- Migration: from
evalkitto either package, between the two (dataset formats, run formats, a bug in the loader path that rejects an empty input), the parity protocol, an exit plan, and the version changes that moved numbers or names in 2026 - The patterns that keep a two-framework repository honest, the anti-patterns with symptoms, and a catalogue
- The pitfalls checklist for 10B.2 to 10B.16: 127 surprises grouped by where they strike, five families that explain them, each with its fix and the section that reproduced it, a runnable scanner for the ones a regex can find, and a pre-flight checklist
- Where promptfoo, Ragas, LangSmith with
openevalsand the hosted platforms fit, and a full decision table
What you don't need
- An API key, a Confident AI account, Docker or any service. Every sample marked
Output (real ...)ran on a laptop withuvonly. Nothing was sent to a hosted model; DeepEval telemetry was off (DEEPEVAL_TELEMETRY_OPT_OUT=1) and Inspect ran inside a throwaway git repository with a placeholder remote. - To have read all sixteen lessons before this one. Each section links to the section that owns the detail, and reads on its own. If you have time for only some of them, 10B.1 (the maps), the methodology parts of 10B.2 and 10B.8, and 10B.10 are the best preparation.
- The mechanics of either package. This lesson synthesizes 10B.1 to 10B.16 and must not contradict them; where it adds a fact (for instance the loader behaviour in 5.2), it says so. When it and an older lesson seem to differ, the lesson that owns the topic wins and the difference is a bug to report.
- A decision already made. The goal is to give you the questions, the evidence and the exit plan, not to crown a winner.
Setup
You need Python 3.11 or newer (Inspect's floor) and uv. If you have not used uv before, 01B.1 walks through it. The lesson's samples need both packages in one environment, which works (10B.1 measured the footprint of both together):
uv init eval-lab --bare --python 3.13 && cd eval-lab # first time only
uv add deepeval inspect-ai pytest pandas pyarrow
# or: pip install deepeval inspect-ai pytest pandas pyarrowThree more things come from earlier lessons rather than from PyPI. Copy fake_judge.py (the FakeJudge class of 10B.2, 3.5 and 10B.3, unchanged) next to the samples; copy the evalkit/ folder (judges.py, compare.py, cluster.py and the judge_validation.py of 10A.4, 10A.5 and 10A.8); and copy desk.py (the support-desk tools of 10B.14). The tickets are the twelve of 10B.1 and 10B.8, saved as triage_data.py. Every sample below runs from a folder that is a throwaway git repository, because Inspect records the repository in every log (10B.1, 5.6):
mkdir lab && cd lab && git init -q . && git remote add origin https://example.com/placeholder/eval-lab.git
export DEEPEVAL_TELEMETRY_OPT_OUT=1 # every DeepEval run in this lesson
uv run python -s ../versions.py # -s: do not add the user site; the script's folder is on sys.pathpython -s rather than python -I because the samples import their neighbours (10B.1 coordinator note: -I drops the script's folder from sys.path).
# versions.py: which versions did these samples run on? (lesson 10B.17)
from importlib import metadata
for name in ["deepeval", "inspect-ai", "pytest", "pydantic"]:
print(f"{name:11} {metadata.version(name)}")deepeval 4.3.6
inspect-ai 0.3.292
pytest 9.2.0
pydantic 2.14.4Versions (current at time of writing; verified 28 November 2026): deepeval 4.3.6 (25 November 2026, Apache-2.0, Python 3.10 or newer), inspect-ai 0.3.292 (23 November 2026, MIT, Python 3.11 or newer). Lessons 10B.2 to 10B.6 were checked against 4.3.5 and 10B.7 against 4.3.6; every DeepEval sample here ran on 4.3.6, so where this lesson ran something 10B.2 to 10B.6 described, it is also a re-check on the newer version.
What you must be able to do after this lesson#
- State the four ways a framework comparison goes wrong and how each is corrected
- Say what each framework's unit of work is and who runs your app in each
- Port the same eval to both frameworks and use the parity protocol to explain differences
- Call a DeepEval metric from an Inspect scorer following the five rules
- Write the check once so migration between frameworks is cheap
- Choose DeepEval, Inspect, both or neither with the decision table
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Should we use DeepEval or Inspect?" | Part 2 and Part 9 |
| "They both say 'metric'. Are they the same thing?" | 2.3 and 7.2 |
| "Why does the same eval give 0.6 here and 0.4 there?" | 3.2 and Part 10 |
| "Can we use DeepEval's faithfulness inside our Inspect task?" | 4.3 |
| "We have Inspect logs. Can we still run paired comparisons and gates?" | 4.4 and 4.7 |
| "How do we move our evals onto a framework without losing history?" | Part 5 |
| "Our traced agent eval is 100% green, but a tool crashed in that run." | 4.7 |
| "pass@k dropped after we moved the eval to Inspect, and nothing changed." | 2.5 |
| "What are the traps in these packages, all in one place?" | Part 8 |
| "This code or tutorial no longer works." | Part 11 |
Part 1: How to compare two frameworks fairly#
1.1 Four ways a comparison goes wrong#
Most "DeepEval versus Inspect" arguments are really one of four mistakes. Name them first, because every table later in the lesson is built to avoid them.
| Mistake | What it looks like | The correction |
|---|---|---|
| Comparing one framework's defaults with the other's best case | "Inspect's model_graded_fact() is too lenient" (with the model under test as grader), against "DeepEval's G-Eval is stable" (with fixed evaluation_steps and a strong judge) |
Compare like with like: the same judge model, the same definition, the defaults of both or the tuned setup of both, and say which |
| Comparing numbers, not definitions | "DeepEval says 0.6 faithfulness, Inspect says 0.4 accuracy" | Two different questions were asked of two different denominators (3.2 reproduces exactly this) |
| Comparing features, not the work around them | A matrix with 40 rows and a tick in each cell | What matters is the cost of the work you will do every week: writing a check, reading a failure, gating a pull request, comparing two runs, leaving |
| Comparing versions you did not name | A blog post from five months ago | Both packages release every few days; 4.2.0 flipped four DeepEval metrics, and Inspect's Python floor changed in October (11.2). Every statement here carries a version and a date |
1.2 What each tool makes cheap, and what it leaves to you#
Before any axis, one table. It is the whole lesson in a sentence per row: which question can you ask in an afternoon, and which one is a project?
| Question you need to answer | In DeepEval | In Inspect | Still yours |
|---|---|---|---|
| "Is this answer grounded in the retrieved chunks?" | A built-in metric (FaithfulnessMetric) |
A custom scorer or a model-graded template you write (3.2) | Validating the judge (10A.5) |
| "Did the agent look up the order before it refunded it?" | A trace or a recorded tools_called plus a custom metric |
The messages and events of a run Inspect made, plus a custom scorer | Deciding what the policy is |
| "Does the same eval hold across five models?" | Possible (you run each model and wrap the records), not what it is shaped for | One task, --model five times, or an eval set |
Pinned model versions, a budget |
| "What did the model actually see and say at step 7?" | Only if you traced it | Always: the log holds every message and model call | Reading it |
| "Fail the pull request when faithfulness drops" | assert_test() and deepeval test run |
A script that reads the log and exits non-zero (10B.12, Part 13) | The threshold, and a baseline |
| "Is v2 really better than v1?" | Per-case pass or fail; no between-run test locally | Per-run standard errors; no between-run test | evalkit's paired bootstrap (10A.8, 4.4) |
| "Run this code the model wrote, safely" | Not its job | Sandboxes, limits and approval (10B.15) | Real isolation for untrusted code |
| "Which of my judge's verdicts can I trust?" | Nothing built in | Nothing built in (a precomputed_scores() bridge helps) |
All of it (10A.5) |
| "Let a non-engineer browse failures" | Confident AI (commercial), or deepeval inspect for you |
Inspect View (web, for engineers) | A report format (10A.10, 7.1) |
The last column is the point. Neither package removes the need for judge validation or between-run statistics, which is why evalkit stays installed after you adopt either (10B.1, 4.3).
1.3 The shape of the work: who runs your app?#
The single most useful difference to hold in your head is who calls your application.
flowchart LR
subgraph de ["DeepEval: you run the app, DeepEval scores the record"]
direction LR
A1["your code runs the app"] --> A2["LLMTestCase<br/>input, actual_output, context"]
A2 --> A3["metrics: score, reason, pass"]
A3 --> A4["pass or fail per case<br/>exit code, .deepeval/ files"]
end
subgraph ins ["Inspect: Inspect runs the app (the solver), then scores"]
direction LR
B1["Sample: input, target"] --> B2["solver: model, tools, agent"]
B2 --> B3["scorers, then metrics<br/>over many samples"]
B3 --> B4["EvalLog: everything<br/>that happened"]
endEverything in Part 2 follows from this. If you already have an application and want assertions on what it did, DeepEval's shape fits what you have. If the application is the thing you are studying, or you want the same recipe over many models, or the thing under test is an agent with tools, Inspect's shape fits. Both can be bent to the other's job, and Part 4 shows how, but you bend a tool at a cost, and the cost is mostly in the places Part 8's checklist lists.
1.4 The lab: three evals, both frameworks, one set of fakes#
The comparison rests on three evals that earlier lessons built, now rebuilt in both packages from the same data and the same scripted behaviour. Each has a DeepEval side and an Inspect side, and each prints numbers you can compare.
| Eval | What it measures | Data | DeepEval file | Inspect file |
|---|---|---|---|---|
| Ticket triage (10A.1) | A JSON reply: valid format, right labels | 12 tickets, 12 scripted replies (2 wrong on purpose) | triage_deepeval_side.py |
triage_inspect_side.py |
docs_qa RAG (10A.6, 10B.11) |
Is the answer grounded, relevant, right? | 5 questions with retrieved chunks and scripted answers | docsqa_deepeval_side.py |
docsqa_inspect_side.py |
| Support agent (10A.7, 10B.14) | Outcome in the world, and process | 3 tasks on a toy order desk, two scripted agents (careful and careless) | desk_deepeval_side.py |
desk_inspect_side.py |
Two pieces of shared machinery keep the sides honest. triage_checks.py holds the two triage checks as plain functions (the "write the check once" pattern of 3.1), and desk_plans.py holds the three desk tasks and the two scripted agents as plain data, replayed by both sides. The data modules (triage_data.py, docsqa_data.py) import neither framework.
Part 2: The comparison on every axis#
Twelve axes, in the order a team meets them. Each ends with what it means for your choice. The facts come from the lessons named in each section and were re-run or re-read for this lesson; where a number is measured here, a sample shows it.
2.1 Philosophy and unit of work#
| DeepEval | Inspect AI | |
|---|---|---|
| Central idea | An evaluation is a unit test: a recorded interaction plus metric objects with thresholds (10B.2, 1.8) | An evaluation is a task: dataset plus solver plus scorer, and the log is the product (10B.8, Part 2) |
| What it runs | Your metrics, over records you made | Your solver (the model, tools, agents), then your scorers |
| What you hand it | LLMTestCases (input, actual_output, retrieval_context, tools_called, ...) |
Samples (input, target, metadata) and a solver |
| Natural fit | A product with behaviours to assert in CI | A model or agent you want to study, compare, benchmark and audit |
| Natural habitat | pytest, pull requests, notebooks | A command line, eval sets, a log viewer, a research workflow |
| Where it came from | An open-source library next to a commercial platform (Confident AI) | A government safety institute's own testing, co-developed with a non-profit |
The consequence people feel first is where the app lives. In DeepEval your application is outside the framework, so adopting DeepEval changes nothing about your architecture and it is easy to score recorded production traffic; but it also means DeepEval has no opinion about concurrency, retries, sandboxes or what the model saw. In Inspect your application, or the part of it under test, becomes a solver, so Inspect controls the loop (and can log, limit and replay it), at the price of writing the thing as a solver or an agent.
2.2 Data model#
evalkit |
DeepEval | Inspect AI | |
|---|---|---|---|
| One case | Example(id, input, reference, metadata) |
LLMTestCase (a finished record); Golden (input plus expectations, no output) |
Sample(input, target, id, metadata, choices, files, setup, sandbox) |
| Where the app's answer lives | In a Row after the run |
In the test case: actual_output |
Not in the sample: produced by the solver (state.output.completion) |
| Case identity | id |
name (an optional string); results carry an index and their order is not guaranteed |
id, assigned if you omit it; join runs on (id, epoch), never by position (10B.8, 7.3) |
| Retrieved context | in the row | retrieval_context (what retrieval returned) and context (golden facts): not the same field (10B.2, 2.4) |
metadata or the store, by your convention |
| Metadata | metadata |
metadata on a test case; additional_metadata on a Golden (and a deprecated alias on test cases: it lands in metadata and raises a DeprecationWarning that Python's default filters hide, see 2.2) |
metadata, optionally a typed Pydantic model (metadata_as()) |
| Tool calls | trajectory in agent_eval.py |
tools_called and expected_tools of ToolCalls |
In the messages and events of the run |
| Conversations | rows per turn | ConversationalTestCase of Turns |
A multi-turn solver, or an agent loop; the log holds the whole conversation |
| Multiple choice | a label | via custom metrics | First-class: choices, multiple_choice(), shuffle_choices |
| Datasets | JSONL via dataset.py |
EvaluationDataset of goldens; save_as, push (Confident AI) |
csv_dataset, json_dataset, hf_dataset, MemoryDataset, SampleSource |
Three traps in this table are worth one sentence each, because they cost people a day. DeepEval's LLMTestCase calls retrieval_context what Faithfulness reads and context what Hallucination reads. Inspect's Sample has an empty-string default target, which makes includes() pass everything (10B.9, 2.2). And Inspect's declarative loaders (a FieldSpec or the default column mapping, for CSV, JSON and Hugging Face) refuse a record whose input is an empty string, while a Sample built in code and a record_to_sample function accept it (5.2 reproduces this on the triage ticket T10).
One of those field names is checked here, because it appears in migrations constantly: the metadata name on a test case versus a golden.
# metadata_alias.py: additional_metadata on a test case, with and without Python's default warning filters (lesson 10B.17, 2.2 and 11.1)
import subprocess
import sys
import warnings
from importlib.metadata import version
from deepeval.dataset import Golden
from deepeval.test_case import LLMTestCase
print("deepeval", version("deepeval"))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always") # show everything, as pytest's warnings summary does
tc = LLMTestCase(input="q", actual_output="a", additional_metadata={"intent": "refunds"})
_ = tc.additional_metadata
print("test case metadata:", tc.metadata)
print("warnings with filter 'always':", sorted({f"{w.category.__name__}: {w.message}" for w in caught}))
# the same construction in a fresh interpreter with Python's default filters: nothing is printed
snippet = ("from deepeval.test_case import LLMTestCase\n"
"LLMTestCase(input='q', actual_output='a', additional_metadata={'intent': 'refunds'})")
run = subprocess.run([sys.executable, "-c", snippet], capture_output=True, text=True)
print("stderr with default filters:", repr(run.stderr.strip()[-80:] if "Deprecat" in run.stderr else ""))
print("Golden keeps the name:", Golden(input="q", additional_metadata={"intent": "refunds"}).additional_metadata)deepeval 4.3.6
test case metadata: {'intent': 'refunds'}
warnings with filter 'always': ["DeprecationWarning: 'additional_metadata' is deprecated. Use 'metadata' instead."]
stderr with default filters: ''
Golden keeps the name: {'intent': 'refunds'}The old spelling still works on a test case (it lands in metadata) and raises a DeprecationWarning. That is not new in 4.3.6: the same script on 4.3.5 prints the same lines (apart from the version line). You rarely see it, because Python's default filters hide a DeprecationWarning raised inside a library (the last line of the output shows an empty stderr). It appears under python -W default, with warnings.simplefilter("always") as here, or in pytest's warnings summary. So "accepted silently" is true only in the default-filter sense. A Golden keeps additional_metadata. Write metadata= on test cases and keep the other name where the class still uses it.
2.3 Metrics versus scorers: the same word, two objects#
The vocabulary collision of 10B.1, 4.2 is the first thing to settle on a team that uses both.
| DeepEval metric | Inspect scorer, then metric | |
|---|---|---|
| What it is | An object that scores one test case: measure(test_case) sets score, reason, success |
A scorer is an async function (state, target) -> Score for one sample. A metric is then a function over all the scores: accuracy(), mean(), stderr() |
| The number it produces | A float from 0 to 1, higher is better since 4.2.0; not clamped by every metric | A Score.value: "C", "I", a float, a bool, a list or a dict |
| Who decides pass | score >= threshold, a per-metric rule you set |
Nobody by default; a gate over logs is yours |
| Per-case reason | Yes: reason, often a generated sentence |
explanation and metadata, what the scorer chooses to record |
| What you get over the run | A pass rate and per-metric detail printed; slices and means are yours | Metric results per scorer, printed with standard errors; slices via grouped() |
| Deterministic checks | ExactMatchMetric, PatternMatchMetric, JsonCorrectnessMetric, ToolCorrectnessMetric (but several still build a judge at construction: pass model=, 10B.2, 3.4) |
exact(), match(), includes(), pattern(), answer(), f1(), math(), or @scorer |
| Failure policy | ErrorConfig: skip on missing fields, ignore errors, or crash (10B.2, 4.9) |
A scorer error is a sample error (fail_on_error); a scorer that returns Score.unscored(...) leaves the denominator; both are reported (10B.10, Part 4) |
| Subclassing | BaseMetric with measure, a_measure, __name__; async runs rebuild it from its attributes (10B.2, 4.5) |
@scorer(metrics=[...]) returning an async function; no copy rule, but @solver and @scorer bodies must be async def |
The difference in denominators deserves its own sentence. Inspect counts what it could not score: scored_samples, unscored_samples, and sample errors are separate, reported numbers, so "accuracy 0.9" always sits next to "scored 9 of 12" (10B.10, 4.6). DeepEval's equivalent is yours to compute: a case whose metrics were all skipped (skip_on_missing_params) or whose errors were ignored simply vanishes from the pass rate (10B.2, 4.9). Both can print a perfect score over a shrunken set of cases, and the gate of 4.7 is what stops that.
2.4 Judges and their prompts#
Most of the numbers that matter come from an LLM judge, so the prompts and the call pattern are an axis of their own.
| DeepEval | Inspect AI | |
|---|---|---|
| Default judge | An OpenAI model unless you configure one; the judge is built when the metric is built, so a missing key fails on the constructor line (10B.3, 2.2) | No default judge. Model-graded scorers use an explicit model=, a grader role, or, as a silent fallback, the model under test (10B.11, 5.2) |
| Judging style | Mostly decompose and verify (QAG): extract statements or claims, give a verdict on each, compute a score from a formula; plus G-Eval (criteria to steps to an integer 0 to 10, divided by 10) and DAG metrics (10B.3, 10B.4) | One request: a template with the question, the answer and the criterion; the grader ends with GRADE: C or GRADE: I (or P); the last GRADE: line wins (10B.11, 3.1) |
| Reasons | Per-metric reason, generated by an extra call (or built from verdicts) |
The grader's whole reply is the explanation |
| An unusable verdict | A validation error in the metric, handled by ErrorConfig |
Score.unscored(reason="grader_failed"): the sample leaves the denominator and is counted separately |
| Ensembles | Not built in (write a composite metric, 10B.3, 6.4) | A panel: model=[a, b, c], strict majority, ties become unscored (10B.11, 6.2) |
| Prompt-injection hardening | Not a feature of the built-ins | Delimiter neutralizing and a nonce in the default templates (10B.11, Part 7) |
| What a trajectory judge sees | Some agent judges grade a summary they wrote in an earlier call, not the trace (Task Completion, Plan Quality), on five-anchor scales (10B.5, 9.1) | Whatever your scorer puts in the grader's prompt from messages or events; nothing is summarized for you |
| You can read the prompt | Yes: templates are shipped in the package (deepeval/templates/), and a scripted judge prints them (10B.4, 1.7) |
Yes: in metadata["grading"] of every score |
| Calibrating the judge | Nothing built in | Nothing built in |
The call pattern is the practical difference, and it is measurable without a key. This sample counts judge calls per case for four DeepEval metrics, with scripted judges that answer correctly, and counts grader calls per sample for Inspect's model_graded_fact, once with one grader and once with a panel of three.
# cost_shape.py: how many judge calls does one case cost? Counted with scripted judges, no key (lesson 10B.17)
import contextlib, io
from deepeval import evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import AnswerRelevancyMetric, FaithfulnessMetric, GEval
from deepeval.test_case import LLMTestCase, SingleTurnParams
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import model_graded_fact
from inspect_ai.solver import generate
from fake_judge import FakeJudge
N = 4
case = lambda i: LLMTestCase(name=f"c{i}", input="Refund on Pro?", actual_output="Yes, within 30 days of purchase.",
expected_output="30 days.", retrieval_context=["Pro plans can be refunded within 30 days."])
Y, R = {"verdict": "yes", "reason": "s"}, {"reason": "scripted"}
quiet = dict(async_config=AsyncConfig(run_async=False), display_config=DisplayConfig(print_results=False, show_indicator=False))
def deepeval_calls(label, metric, judge, sync=True):
cfg = quiet if sync else dict(display_config=quiet["display_config"]) # default async copies the metric per case
with contextlib.redirect_stdout(io.StringIO()):
evaluate([case(i) for i in range(N)], [metric], **cfg)
print(f"DeepEval {label:38} {len(judge.calls) / N:4.1f} judge calls per case ({sorted(set(judge.schemas()))})")
j = FakeJudge(routes={"ReasonScore": [("", {"reason": "s", "score": 8})]})
deepeval_calls("GEval, fixed evaluation_steps", GEval(name="g", model=j, evaluation_steps=["Check the facts."],
evaluation_params=[SingleTurnParams.INPUT, SingleTurnParams.ACTUAL_OUTPUT]), j)
j = FakeJudge(routes={"ReasonScore": [("", {"reason": "s", "score": 8})], "Steps": [("", {"steps": ["Check the facts."]})]})
deepeval_calls("GEval, criteria only, run_async=False", GEval(name="g", model=j, criteria="Facts match.",
evaluation_params=[SingleTurnParams.INPUT, SingleTurnParams.ACTUAL_OUTPUT]), j)
j = FakeJudge(routes={"ReasonScore": [("", {"reason": "s", "score": 8})], "Steps": [("", {"steps": ["Check the facts."]})]})
deepeval_calls("GEval, criteria only, default async", GEval(name="g", model=j, criteria="Facts match.",
evaluation_params=[SingleTurnParams.INPUT, SingleTurnParams.ACTUAL_OUTPUT]), j, sync=False)
j = FakeJudge(routes={"Statements": [("", {"statements": ["a", "b"]})], "Verdicts": [("", {"verdicts": [Y, Y]})],
"AnswerRelevancyScoreReason": [("", R)]})
deepeval_calls("AnswerRelevancy, 2 statements", AnswerRelevancyMetric(model=j), j)
j = FakeJudge(routes={"Truths": [("", {"truths": ["t"]})], "Claims": [("", {"claims": ["a", "b"]})],
"Verdicts": [("", {"verdicts": [Y, Y]})], "FaithfulnessScoreReason": [("", R)]})
deepeval_calls("Faithfulness, 2 claims", FaithfulnessMetric(model=j), j)
# Inspect: model_graded_fact is one grader call per sample; a panel of three is three
for label, graders in [("one grader", ["a"]), ("panel of three graders", ["a", "b", "c"])]:
count = {"n": 0}
def fn(input, tools, tool_choice, config, count=count):
count["n"] += 1
return ModelOutput.from_content(model="mockllm", content="Reasoning.\nGRADE: C")
models = [get_model("mockllm/model", custom_outputs=fn, memoize=False) for _ in graders]
task = Task(dataset=[Sample(id=str(i), input="Refund on Pro?", target="30 days.") for i in range(N)],
solver=generate(), scorer=model_graded_fact(model=models if len(models) > 1 else models[0]))
eval(task, model=get_model("mockllm/model", memoize=False), log_dir="logs/cost", display="none")
print(f"Inspect model_graded_fact, {label:24} {count['n'] / N:4.1f} grader calls per sample")DeepEval GEval, fixed evaluation_steps 1.0 judge calls per case (['ReasonScore'])
DeepEval GEval, criteria only, run_async=False 1.2 judge calls per case (['ReasonScore', 'Steps'])
DeepEval GEval, criteria only, default async 2.0 judge calls per case (['ReasonScore', 'Steps'])
DeepEval AnswerRelevancy, 2 statements 3.0 judge calls per case (['AnswerRelevancyScoreReason', 'Statements', 'Verdicts'])
DeepEval Faithfulness, 2 claims 4.0 judge calls per case (['Claims', 'FaithfulnessScoreReason', 'Truths', 'Verdicts'])
Inspect model_graded_fact, one grader 1.0 grader calls per sample
Inspect model_graded_fact, panel of three graders 3.0 grader calls per sampleRead the rows. A G-Eval with fixed steps costs one call per case; with only criteria, DeepEval also generates the steps, once per copy of the metric. The default async runner copies the metric per case, so the steps are regenerated for every case (2.0 calls per case, and, as a side effect, different steps per case); with run_async=False there is no copy and the steps are generated once (1.2). That is the copy rule of 10B.2, 4.5 and 10B.3, 4.4 showing up as money. Answer relevancy costs three calls and faithfulness four for a two-claim answer, and the count grows with the number of statements or claims. Inspect's model_graded_fact is one call per sample per grader, so a panel of three is three.
2.5 Agents, tools and sandboxes#
| DeepEval | Inspect AI | |
|---|---|---|
| Who runs the agent | You | Inspect, through react(), a custom agent, or a bridge to an external one |
| What you evaluate | A record of the run: a trace of spans (@observe), or tools_called on a test case. In a traced eval only the golden's input, metadata, comments, name and expectations reach the test case; its expected_output, contexts and expected_tools must be copied in by your code (10B.5, 4.3) |
The run itself: messages, events, the store and the final state of a sandbox; the sample's target and metadata are always there for the scorer |
| A component that crashes | A caught exception leaves an ERRORED span whose metrics are skipped, and the golden passes; an uncaught one in a sync loop stops the suite (10B.5, 4.5) |
A tool error goes back to the model as a ToolError; an uncaught one is a sample error, counted separately and governed by fail_on_error (10B.12, Part 8) |
| Agent metrics | TaskCompletionMetric, ToolCorrectnessMetric (deterministic), ArgumentCorrectnessMetric, StepEfficiencyMetric, PlanAdherence/PlanQuality, goal and topic metrics, MCP metrics (10B.5). Mostly LLM-judged over a trajectory it extracts, on five-anchor ordinal scales; Task Completion and Plan Quality grade a summary the judge wrote, never the trace itself (10B.5, 9.1) |
Whatever you write as a scorer: read events for the trajectory, read the world for the outcome (10B.16, Parts 2 and 3) |
| Tools | Observed, not defined | Defined (@tool, MCP, the standard catalogue), with schemas (10B.14) |
| Controls on actions | None (what the agent may do is its own code's business) | Approval before a call (approve, modify, reject, escalate, terminate) fails closed: an unmatched call is rejected, so submit needs a rule. Tool result review after a call fails open: an unmatched result reaches the model. Approvers are code to unit-test (10B.15, Parts 8 and 9, 12.4) |
| Containment | None: your agent runs in your process | Sandboxes (Docker and others), local for trusted debugging only, network off by default in generated compose files (10B.15) |
| Budgets | Your agent's own | Message, token, time, working-time and cost limits are first-class, and a budget is an experimental condition: the submit call costs a turn, stopped samples are still scored, and rankings can flip between budgets, so report a budget curve (10B.16, 5.6, 10B.15, Part 7, 10B.16, Part 5) |
| Reliability | Repeat the run yourself and count successes; what counts as a success is the metric's threshold | epochs, pass_at(k), pass_k(k) reducers; what counts as a success is the reducer's value=, 1.0 by default (10B.16, 4.7) |
| Multi-turn simulation | ConversationSimulator (validate it first, 10B.6, Part 8) |
A solver or agent that plays the user |
| Public benchmarks | Model-level benchmarks in deepeval.benchmarks, with the format and contamination caveats of 10B.6, Part 9. Two scorers misreport in 4.3.5 and 4.3.6: HumanEval never runs the tests and counts any passing sample, and TruthfulQA MC2 rewards recall and changes scale when batched (10B.6, 9.5 and 9.6) |
200-plus tasks, including agentic ones, via Inspect Evals and Harbor (10B.16, Parts 9 and 10); each task carries an N-X version, and code runs in a sandbox |
If the thing under test is an agent that acts (writes files, runs code, issues refunds), Inspect's side of this table is not a convenience but the difference between measuring the agent and measuring a description of it. If the agent already exists in a framework you cannot change, DeepEval's tracing integrations or Inspect's bridge are the two ways in, and neither gives you the control a native Inspect agent has. 3.3 runs the same agent both ways.
The reliability row hides a decision that a port can move without anyone noticing: what counts as a success. Inspect's pass_at(k) and pass_k(k) count an epoch as a success when its score reaches the reducer's value= (1.0 by default); DeepEval has no reducer, so you repeat the run and count cases whose metric passed, which makes the metric's threshold the same decision under another name. > 🎓 Fresher note: pass@k asks "if the agent gets k tries, how likely is at least one to succeed?" and pass^k asks "how likely is it that all k tries succeed?". Both are estimated from n recorded attempts with c successes, so both need a rule for what a success is. With partial credit (0.5 for half the job) that rule is a choice, not a fact.
This sample feeds the same per-attempt credit (0, 0.5 or 1 for five tickets over four attempts, the table of 10B.16, 4.7) through both, with one pair of plain estimator functions on the DeepEval side:
# reliability_both.py: pass@k and pass^k from Inspect epochs and from repeated DeepEval runs (lesson 10B.17, 2.5)
# The same per-attempt credit (0, 0.5 or 1) for five tickets over four attempts, as in 10B.16, 4.7.
import contextlib, io
from math import comb
from inspect_ai import Epochs, Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model
from inspect_ai.scorer import Score, mean, pass_at, pass_k, scorer
from inspect_ai.solver import generate
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
CREDIT = {"T1": [1.0, 1.0, 1.0, 1.0], "T2": [1.0, 0.5, 1.0, 0.5], "T3": [0.5, 0.5, 0.5, 0.5],
"T4": [1.0, 0.0, 0.0, 0.0], "T5": [0.0, 0.0, 0.5, 0.0]}
N, K = 4, 2
# ---- the plain functions (write the check once): unbiased estimators from n attempts with c successes
def pass_at_k(n: int, c: int, k: int) -> float:
return 1.0 - comb(n - c, k) / comb(n, k)
def pass_hat_k(n: int, c: int, k: int) -> float:
return comb(c, k) / comb(n, k)
# ---- Inspect: epochs and reducers; the success threshold is the reducer's value= (default 1.0)
@scorer(metrics=[mean()])
def scripted_credit():
async def score(state, target):
return Score(value=CREDIT[state.sample_id][state.epoch - 1])
return score
def inspect_side(value: float) -> dict:
task = Task(dataset=[Sample(id=t, input=f"ticket {t}") for t in CREDIT], solver=generate(),
scorer=scripted_credit(), epochs=Epochs(N, [pass_at(K, value=value), pass_k(K, value=value)]))
log = eval(task, model=get_model("mockllm/model"), display="none", log_dir="logs/reliability")[0]
return {s.reducer: round(s.metrics["mean"].value, 3) for s in log.results.scores}
# ---- DeepEval: no reducers, so repeat the run and count; the success threshold is the metric's threshold
class Credit(BaseMetric):
def __init__(self, threshold: float):
self.threshold = threshold
def measure(self, test_case, *args, **kwargs):
self.score = test_case.metadata["credit"]
self.success, self.reason = self.score >= self.threshold, "scripted"
return self.score
async def a_measure(self, test_case, *args, **kwargs):
return self.measure(test_case)
def is_successful(self):
return self.success
@property
def __name__(self):
return "Credit"
def deepeval_side(threshold: float) -> dict:
successes = dict.fromkeys(CREDIT, 0)
for attempt in range(N): # one evaluate() per attempt, like `-r 4`
cases = [LLMTestCase(name=t, input=f"ticket {t}", actual_output="(recorded answer)",
metadata={"credit": c[attempt]}) for t, c in CREDIT.items()]
with contextlib.redirect_stdout(io.StringIO()):
res = evaluate(cases, [Credit(threshold)],
display_config=DisplayConfig(print_results=False, show_indicator=False))
for tr in res.test_results:
successes[tr.name] += int(tr.success)
mean_of = lambda f: round(sum(f(N, c, K) for c in successes.values()) / len(successes), 3)
return {"pass_at_2": mean_of(pass_at_k), "pass_k_2": mean_of(pass_hat_k)}
for threshold in (1.0, 0.5):
print(f"success threshold {threshold}:")
print(f" inspect (reducer value={threshold}) {inspect_side(threshold)}")
print(f" deepeval (metric threshold={threshold}) {deepeval_side(threshold)}")
print("mean credit, no threshold:", round(sum(map(sum, CREDIT.values())) / (N * len(CREDIT)), 3))success threshold 1.0:
inspect (reducer value=1.0) {'pass_at_2': 0.467, 'pass_k_2': 0.233}
deepeval (metric threshold=1.0) {'pass_at_2': 0.467, 'pass_k_2': 0.233}
success threshold 0.5:
inspect (reducer value=0.5) {'pass_at_2': 0.8, 'pass_k_2': 0.6}
deepeval (metric threshold=0.5) {'pass_at_2': 0.8, 'pass_k_2': 0.6}
mean credit, no threshold: 0.525The two frameworks agree exactly when the two thresholds agree, and the threshold moves pass@2 from 0.467 to 0.8 and pass^2 from 0.233 to 0.6 on the same attempts, while the mean credit (0.525) ignores it. So a reliability number is not portable on its own: a team that moves from a DeepEval metric with threshold=0.5 to Inspect's default pass_at(2) has changed its definition of success, and the number falls with no change in the agent. Write the threshold next to every pass@k or pass^k you report, in both frameworks, and keep the estimator in your own code (the two functions above are the unbiased estimators of 10B.16, 4.2) when you need it outside Inspect.
2.6 Statistics#
| DeepEval | Inspect AI | evalkit |
|
|---|---|---|---|
| Uncertainty on a run | None printed: a pass rate and per-metric means | stderr() by default; stderr(cluster=...), ci(), ci_wilson(), bootstrap_stderr() (unseeded) |
Bootstrap and Wilson intervals (10A.8) |
| Non-independent cases | Nothing | Clustered standard errors and a paired cluster bootstrap in your own code | cluster.py (10A.8, 2.7) |
| Repeats | deepeval test run -r k makes separate tests; -r silently turns -c off |
epochs with reducers, pass_at, pass_k; the epoch statistics are first-class (10B.10, Part 7) |
repeats= |
| Comparing two runs | Nothing locally (the platform has regression views) | Nothing: logs are comparable, you compute the difference | Paired bootstrap, permutation test, effect size, minimum detectable effect |
| Slices | By hand over metadata |
grouped() metrics |
slices from metadata |
| Benchmark comparisons | One overall accuracy per benchmark, a micro-average over questions; per-task (macro) scores, intervals and a paired test on discordant items are yours (10B.6, 9.10) | Per-sample scores in the log; grouped() for per-task means; the paired test is yours |
A paired test over per-case scores |
Inspect's printed standard error is the sample-to-sample sampling error of the mean over the cases you have, no more: on the 12-ticket triage fixture it printed accuracy 0.917 with stderr 0.083, and 10B.1, 7.1 showed that 10 of 12 is consistent with a true rate anywhere from about 55% to 95%. What neither package prints is the thing a release decision needs: whether v2 is better than v1 on the same cases. That is a paired statistic, and 4.4 computes it from Inspect logs in eight lines. For DeepEval, the same function takes the per-case scores of two runs (10B.2, 8.4).
2.7 Logs, records and analysis#
What each framework leaves behind after the same run is the axis people discover last and live with longest. This sample runs the triage eval in both (the code of 3.1) and inspects the artefacts.
# records_compare.py: what each framework leaves behind after the SAME triage run (lesson 10B.17)
import contextlib, io, json
from pathlib import Path
from inspect_ai.log import list_eval_logs, read_eval_log
import triage_deepeval_side as de
import triage_inspect_side as ins
with contextlib.redirect_stdout(io.StringIO()):
de.run()
ins.run()
# --- DeepEval: JSON files under .deepeval/ in the folder you ran from
latest = Path(".deepeval/.latest_test_run.json")
data = json.loads(latest.read_text())["testRunData"]
case = data["testCases"][0]
print(f"DeepEval {latest.name}: {latest.stat().st_size:,} bytes, testRunData keys {list(data)[:5]}...")
print(f" one test case holds: {sorted(case)}")
print(f" has the input and the output text: {'input' in case and 'actualOutput' in case}")
# --- Inspect: one .eval log per task run, in ./logs
info = [i for i in list_eval_logs("logs/triage")][0]
log = read_eval_log(info.name)
s = log.samples[0]
print(f"Inspect {Path(info.name).name[:28]}...: {Path(info.name.replace('file://', '')).stat().st_size:,} bytes")
print(f" one sample holds: messages={len(s.messages)}, events={len(s.events)}, scores={list(s.scores)}, store keys={list(s.store)}")
print(f" git revision recorded: {log.eval.revision.type} {log.eval.revision.origin} (a placeholder remote in this lab)")DeepEval .latest_test_run.json: 8,647 bytes, testRunData keys ['testCases', 'conversationalTestCases', 'metricsScores', 'prompts', 'testPassed']...
one test case holds: ['actualOutput', 'expectedOutput', 'flaky', 'input', 'metadata', 'metricsData', 'name', 'order', 'runDuration', 'success']
has the input and the output text: True
Inspect 2026-11-28T04-21-40-00-00_tr...: 36,796 bytes
one sample holds: messages=2, events=20, scores=['triage_format', 'triage_labels'], store keys=[]
git revision recorded: git https://example.com/placeholder/eval-lab.git (a placeholder remote in this lab)| DeepEval | Inspect AI | |
|---|---|---|
| What is written | .deepeval/ JSON (.latest_test_run.json, .latest_run_full.json), an optional SQLite store, optional results_folder files, optional upload |
One .eval log per task run, always, in ./logs (relative to where you ran it) |
| What it holds | Per case: input, output, expected output, per-metric score, reason and success, run duration | Everything: config, every message, every model call and tool call, scores, timings, usage, the git revision. 20 events for one 2-message sample in the run above |
| How you read it | Console table; JSON; deepeval inspect (a terminal viewer); Confident AI |
Inspect View (web), the VS Code extension, read_eval_log(), dataframes (samples_df(), events_df()), inspect log dump (10B.13) |
| Overwritten? | The latest files hold only the most recent run: archive them in CI |
New file per run; you manage the folder |
| Re-score without re-running | Not a feature (you still hold the records) | inspect score on a log, precomputed_scores(), 10B.13, Part 6 |
| Privacy | Inputs and outputs are written locally; uploaded only with a key; telemetry (PostHog) unless opted out | Logs include prompts, outputs and the git remote and commit (log.eval.revision): scrub before sharing (10B.13, 7.5) |
The line that matters: an Inspect log lets you answer questions you did not know you would ask (what did the model say at the fifth tool call? how many retries did that sample burn?), and a DeepEval run file lets you answer the questions the metrics asked. If you will audit failures a month from now, only the first is enough on its own. DeepEval's tracing (10B.5) narrows the gap, at the cost of instrumenting your code.
2.8 CI#
Both packages can gate a pull request, and each has a way of looking green while checking nothing.
| DeepEval | Inspect AI | |
|---|---|---|
| The gate | deepeval test run is pytest with a plugin: the exit code is the verdict; assert_test() is one pass or fail per case |
inspect eval exits 0 even when the eval's status is error; use inspect eval-set, whose exit code reflects completeness, and a script that reads the log (10B.12, Part 13) |
| What a threshold means | Per metric, per case | Yours: a script over log.results or reductions |
| Quiet ways to go green | || true in the job; exit code 5 (nothing collected) swallowed; a case that vanished from the totals; -n workers that lose cases from DeepEval's own summary; span failures that the console table hides (10B.7, Part 2); in traced runs, an ERRORED span under a caught exception and metrics skipped by skip_on_missing_params while the case still counts as passed (4.7) |
Errors tolerated with fail_on_error=False leaving the denominator; scorers that raise on every sample; an eval-set directory polluted by an old run (10B.12, Part 8); a reliability gate on pass_at(k) whose success threshold nobody chose (10B.16, 4.7) |
| A keyless gate | Deterministic metrics and FakeJudge (10B.7, 2.3) |
mockllm/model with scripted outputs (10B.12, Part 13) |
| Caching | -c caches metric results and ignores custom metric parameters: stale scores |
cache=True caches model calls; the key holds the model alias, not the snapshot (10B.12, Part 6) |
| A baseline and a diff | None local; archive run files and diff yourself | None; compare logs yourself |
| Cost control | max_concurrent, judge model choice, calls per metric |
Concurrency, batch mode, eval-set retries, early stopping, limits |
4.7 writes one gate that fails closed for both.
2.9 Platform, lock-in and what leaves the machine#
| DeepEval | Inspect AI | |
|---|---|---|
| Hosted platform | Confident AI: shared reports, datasets, annotation queues, online evals, prompt versioning. Free tier: 5 test runs per week; paid tiers from $200 a month per organization (dated 24 November 2026: re-read the pricing page before you budget) (10B.7, Part 5) | None, by design. Logs are files you own; Inspect Viz, Scout and Flow, and third-party platforms, build on them |
| What is local | All metrics, the runner, tracing with local evaluation, datasets as files, the synthesizer, the simulator, benchmarks, red teaming, deepeval inspect |
Everything |
| What needs an account | Pushing and pulling datasets and prompts, uploading runs, server-side metric collections, online evaluation, annotations, deepeval gate and deepeval view (10B.7, 5.2) |
Nothing |
| Telemetry | PostHog usage telemetry unless DEEPEVAL_TELEMETRY_OPT_OUT=1 (the legacy deepteam package had separate telemetry) |
None documented; the git origin goes into every log |
| Lock-in surface | Datasets and prompts if you push them; run history if you upload; the definitions of the built-in metrics (prompts you did not write) | The log format (open, documented, converted by inspect log convert), the registry entry points of custom components |
| Exit path | Keep datasets as JSONL and results as artefacts; custom metrics are plain classes | Keep tasks as code; logs are files; scorers are plain functions |
The honest summary of platform and lock-in is the one of 10A.10, 1.2: platforms sell visibility and collaboration, not measurement. The scores come from the same code you can run for free. What you should not do is let a platform's database become the only copy of your dataset.
2.10 Licence, governance and release cadence#
Both facts below are from 10B.1, 2.4 and 2.5 (checked 28 November 2026).
| DeepEval | Inspect AI | |
|---|---|---|
| Owner | Confident AI, a company; the library sits beside a paid platform | UK AI Security Institute (copyright holder), co-developed with Meridian Labs, a non-profit |
| Licence | Apache-2.0 (explicit patent grant) | MIT |
| Version line | 4.x, a major version that nevertheless changes scores and names in minor releases; 4.3.6 | 0.x; 0.3.292; any release can carry breaking changes |
| Cadence | About one release every five days | One every two to three days |
| Release notes | A docs changelog that can lag PyPI; PyPI is the source of truth | A CHANGELOG on the docs site |
| A change that moved numbers | 4.2.0 (24 August 2026) flipped Bias, Toxicity, Hallucination and Misuse to "higher is better" | 0.3.262 made a tied panel unscored; 0.3.288 changed the default model-graded template |
| A change that moved your install | 4.3.6 added red teaming back into the package and new dependencies | 0.3.281 raised the Python floor to 3.11; 0.3.288 removed web_browser() (the name still imports; calling it raises PrerequisiteError) |
The practical rule is the same for both: a number belongs to a version. Commit uv.lock, upgrade one package at a time, re-run a frozen suite before and after, diff the per-case verdicts (10A.8, 8.4), and record versions with every result (6.5).
2.11 Performance and cost#
Cost comes from judge calls, and the count is measurable: see 2.4. The rest is scheduling.
| DeepEval | Inspect AI | |
|---|---|---|
| Concurrency | AsyncConfig(max_concurrent=20) cases in flight by default; each LLM metric may make several judge calls, so 20 cases can mean 60 or more requests (10B.2, 4.6) |
Adaptive connections per model: start 20, floor 10, ceiling 100, backing off on rate limits; max_samples and max_tasks (10B.12, Part 4) |
| Retries | Tenacity, tuned with DEEPEVAL_RETRY_*; a provider outage becomes a metric error |
Model-layer retries (unlimited by default) plus timeout, attempt_timeout; eval-set task retries (10B.12, Part 5) |
| Cheaper tiers | Judge model choice; a deterministic metric first | batch mode for single-turn runs, flex tiers, cascade() (cheap checks before a grader), early stopping |
| Crash recovery | Rerun | eval_retry, eval sets, buffered logs (10B.12, Part 9) |
| Install weight | About 80 packages, about 110 MB (Inspect alone: about 80, about 150 MB) | Both together about 130 packages, about 240 MB (measured in fresh --isolated environments in 10B.1, 3.1) |
2.12 The scorecard, and how to read it#
One table, with the caution that a scorecard is a summary of the sections above and not a substitute for them. "Strong" means the framework makes the thing cheap and documented; "yours" means you build it; "n/a" means outside its scope.
| Axis | DeepEval | Inspect AI | evalkit (for reference) |
|---|---|---|---|
| Product-feature unit tests in pytest | Strong | Possible, heavier | Via a wrapper |
| Ready-made RAG metrics | Strong | Yours | Partial (10A.6) |
| Ready-made safety metrics and red teaming | Strong (4.3.6 deepeval.red_team) |
Yours; audits via Petri and Cyber | n/a |
| Agents with tools, sandboxes, budgets | Evaluate a record | Strong | Simulated (10A.7) |
| Controls on agent actions (approval, result review) | n/a | Strong (approval fails closed, review fails open) | n/a |
| Reliability (pass@k, pass^k) | Yours (repeat and count) | Built in (value= is the success threshold) |
Yours |
| Comparing many models on one recipe | Possible | Strong | Yours |
| Public benchmarks | Some (HumanEval and TruthfulQA MC2 misreport, 10B.6, 9.5) | Strong | n/a |
| Run records and transcripts | Per case; tracing optional | Strong, always on | JSONL rows |
| Per-run statistics | Yours | Built in | Strong |
| Between-run statistics | Yours | Yours | Strong |
| Judge calibration | Yours | Yours | Strong |
| Hosted collaboration | Confident AI (commercial) | Third parties | n/a |
| Telemetry and data flow | Opt-out telemetry; optional upload | None documented; logs hold the git origin | None |
| Stability of numbers across upgrades | Minor releases moved scores | 0.x: read the changelog | You control it |
Two readings. First, no column wins every row, which is why the answer is so often "both, with clear ownership" or "one, plus evalkit for the statistics". Second, the rows where both say "yours" are exactly the rows where evalkit's 10A.5 and 10A.8 tools earn their keep.
Part 3: The same three evals in both, side by side#
Deep-dive
A comparison table tells you what each tool offers. Running one eval through both tells you what each tool asks of you and what its output means. The three evals below share their data and their scripted behaviour between the two sides, so any difference in the output is a difference of the framework.
3.1 Ticket triage: one check, two wrappers#
10B.1, Part 7 rebuilt triage in both packages with two copies of the checking logic (a BaseMetric in one and a @scorer in the other). This lesson removes the copy. The checks are plain functions with no framework import; each framework gets a thin wrapper. If the definition of "valid format" changes, it changes in one file.
# triage_checks.py: the two triage checks as PLAIN functions, with no framework import (lesson 10B.17)
"""Write the check once. DeepEval metrics, Inspect scorers and evalkit graders are three thin
wrappers around these two functions, so a definition can only drift in one place."""
from __future__ import annotations
import json
import re
CATEGORIES = {"billing", "technical", "account", "shipping", "other"}
PRIORITIES = {"P1", "P2", "P3"}
def parse_json(text: str) -> dict | None:
"""The tolerant extractor from 10A.1: strip code fences, take the first {...}."""
text = re.sub(chr(96) * 3 + r"\s*(?:json)?", "", text, flags=re.IGNORECASE)
found = re.search(r"\{.*\}", text, re.DOTALL)
if not found:
return None
try:
obj = json.loads(found.group(0))
except json.JSONDecodeError:
return None
return obj if isinstance(obj, dict) else None
def check_format(reply: str) -> tuple[float, str]:
"""Gate 1: a JSON object with exactly the three valid fields. Returns (score, reason)."""
obj = parse_json(reply or "")
problems = []
if obj is None:
problems.append("no JSON object found")
else:
if set(obj) != {"priority", "category", "summary"}:
problems.append(f"keys={sorted(obj)}")
if obj.get("priority") not in PRIORITIES:
problems.append(f"priority={obj.get('priority')!r}")
if obj.get("category") not in CATEGORIES:
problems.append(f"category={obj.get('category')!r}")
if not isinstance(obj.get("summary"), str):
problems.append("summary not a string")
return (0.0 if problems else 1.0), ("; ".join(problems) or "ok")
def check_labels(reply: str, expected: str, allow_empty_summary: bool = False) -> tuple[float, str]:
"""Gate 2: a third of a point each for priority, category and a usable summary."""
obj = parse_json(reply or "")
if obj is None:
return 0.0, "unparseable output"
want_priority, want_category = expected.split("|")
summary = obj.get("summary", "")
checks = {
"priority": obj.get("priority") == want_priority,
"category": obj.get("category") == want_category,
"summary": ((summary == "" and allow_empty_summary)
or (isinstance(summary, str) and 0 < len(summary.split()) < 25)),
}
wrong = [name for name, ok in checks.items() if not ok]
return sum(checks.values()) / len(checks), ("ok" if not wrong else f"wrong: {', '.join(wrong)}")The DeepEval side builds finished records (the app already ran: the replies are scripted) and wraps each check as a metric. The wrapper is one small class that stores its arguments under their own names, so the copy rule of 10B.2, 4.5 holds.
# triage_deepeval_side.py: the triage eval as DeepEval sees it: finished records plus two metrics (lesson 10B.17)
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
from triage_checks import check_format, check_labels
from triage_data import RESPONSES, TICKETS
class FromCheck(BaseMetric):
"""A DeepEval metric made from a plain check. `fn(test_case) -> (score, reason)`."""
def __init__(self, label: str, fn, threshold: float = 1.0):
self.label, self.fn, self.threshold = label, fn, threshold # same names as the arguments (10B.2, 4.5)
def measure(self, test_case, *args, **kwargs) -> float:
self.score, self.reason = self.fn(test_case)
self.success = self.is_successful()
return self.score
async def a_measure(self, test_case, *args, **kwargs) -> float:
return self.measure(test_case)
@property
def __name__(self):
return self.label
def run() -> dict:
cases = [LLMTestCase(name=tid, input=text, actual_output=RESPONSES[tid], expected_output=ref, metadata=meta)
for tid, text, ref, meta in TICKETS] # the app already ran: scripted replies
metrics = [FromCheck("format", lambda tc: check_format(tc.actual_output)),
FromCheck("labels", lambda tc: check_labels(tc.actual_output, tc.expected_output,
(tc.metadata or {}).get("allow_empty_summary") == "1"))]
result = evaluate(cases, metrics, display_config=DisplayConfig(print_results=False, show_indicator=False))
out = {}
for t in sorted(result.test_results, key=lambda t: t.index):
out[t.name] = {m.name: m.score for m in t.metrics_data} | {"success": t.success}
return out
if __name__ == "__main__":
per_case = run()
failing = [k for k, v in per_case.items() if not v["success"]]
print("failing:", failing)
print(f"pass rate {1 - len(failing) / len(per_case):.1%} "
f"format mean {sum(v['format'] for v in per_case.values()) / len(per_case):.3f} "
f"labels mean {sum(v['labels'] for v in per_case.values()) / len(per_case):.3f}")The Inspect side is a task: samples, a solver that builds the prompt and calls the (scripted) model, and the same two checks as scorers. The triage_labels scorer returns the partial-credit float; triage_format returns CORRECT or INCORRECT, because it is a verdict.
# triage_inspect_side.py: the triage eval as Inspect sees it: a task that RUNS the (scripted) model (lesson 10B.17)
from inspect_ai import Task, eval
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.dataset import Sample
from inspect_ai.scorer import CORRECT, INCORRECT, Score, accuracy, mean, scorer, stderr
from inspect_ai.solver import generate, prompt_template
from triage_checks import check_format, check_labels
from triage_data import RESPONSES, TICKETS
PROMPT = ("Triage this support ticket. Reply with JSON holding priority (P1, P2, P3), "
"category and a one-sentence summary.\n\nTicket: {prompt}")
@scorer(metrics=[accuracy(), stderr()])
def triage_format():
async def score(state, target):
value, why = check_format(state.output.completion)
return Score(value=CORRECT if value == 1.0 else INCORRECT, explanation=why)
return score
@scorer(metrics=[mean(), stderr()])
def triage_labels():
async def score(state, target):
value, why = check_labels(state.output.completion, target.text,
state.metadata.get("allow_empty_summary") == "1")
return Score(value=value, explanation=why)
return score
def fake_model(input, tools, tool_choice, config) -> ModelOutput:
prompt = input[-1].text
reply = next((RESPONSES[tid] for tid, text, _, _ in TICKETS if text and text in prompt), RESPONSES["T10"])
return ModelOutput.from_content(model="mockllm", content=reply)
def triage_task() -> Task:
samples = [Sample(id=tid, input=text, target=ref, metadata=meta) for tid, text, ref, meta in TICKETS]
return Task(dataset=samples, solver=[prompt_template(PROMPT), generate()],
scorer=[triage_format(), triage_labels()], name="triage")
def run() -> dict:
log = eval(triage_task(), model=get_model("mockllm/model", custom_outputs=fake_model, memoize=False),
log_dir="logs/triage", display="none")[0]
return {"log": log}
if __name__ == "__main__":
log = run()["log"]
print("status:", log.status)
for s in log.results.scores:
print(f"{s.name:14}", {k: round(m.value, 3) for k, m in s.metrics.items()})
failing = [s.id for s in log.samples
if s.scores["triage_format"].value != CORRECT or s.scores["triage_labels"].value != 1.0]
print("failing:", failing)
print(f"pass rate {1 - len(failing) / len(log.samples):.1%}")Now the reconciliation, in the order 10B.1, 7.4 taught: cases first, aggregates second.
# triage_compare.py: reconcile the two frameworks on the SAME eval: cases first, aggregates second (lesson 10B.17)
import contextlib, io
import triage_deepeval_side as de
import triage_inspect_side as ins
from inspect_ai.scorer import CORRECT
with contextlib.redirect_stdout(io.StringIO()): # DeepEval's runner prints a panel
de_cases = de.run()
log = ins.run()["log"]
in_cases = {s.id: {"format": 1.0 if s.scores["triage_format"].value == CORRECT else 0.0,
"labels": s.scores["triage_labels"].value} for s in log.samples}
de_failing = {k for k, v in de_cases.items() if not v["success"]}
in_failing = {k for k, v in in_cases.items() if v["format"] != 1.0 or v["labels"] != 1.0}
print("failing cases DeepEval:", sorted(de_failing), " Inspect:", sorted(in_failing), " equal:", de_failing == in_failing)
same_scores = all(de_cases[k]["format"] == in_cases[k]["format"] and de_cases[k]["labels"] == in_cases[k]["labels"] for k in de_cases)
print("per-case scores identical:", same_scores)
print(f"{'what each tool prints':28} {'DeepEval':>10} {'Inspect':>10}")
print(f"{'case pass rate':28} {'printed':>10} {'computed':>10} -> {1 - len(de_failing) / 12:.1%} both")
fmt = log.results.scores[0].metrics
lab = log.results.scores[1].metrics
print(f"{'format: accuracy / stderr':28} {'computed':>10} {'printed':>10} -> {fmt['accuracy'].value:.3f} / {fmt['stderr'].value:.3f}")
print(f"{'labels: mean / stderr':28} {'computed':>10} {'printed':>10} -> {lab['mean'].value:.3f} / {lab['stderr'].value:.3f}")failing cases DeepEval: ['T02', 'T11'] Inspect: ['T02', 'T11'] equal: True
per-case scores identical: True
what each tool prints DeepEval Inspect
case pass rate printed computed -> 83.3% both
format: accuracy / stderr computed printed -> 0.917 / 0.083
labels: mean / stderr computed printed -> 0.889 / 0.075Both frameworks fail the same two tickets (T02, a login outage labelled P2|billing, and T11, prose around a JSON fragment) and agree on every per-case score. The headline numbers differ only in what each prints. DeepEval prints a per-case pass rate (83.3%), where a pass means every metric passed; Inspect prints one accuracy and one mean per scorer, each with a standard error, and no pass rate at all, so the pass rate is computed from the log. This is the same reconciliation 10B.1 made against evalkit (83.3%, 0.903), now achieved with one definition of each check instead of two.
3.2 docs_qa RAG: the same five cases, two questions#
The second eval is a RAG answer eval. Five questions with retrieved chunks and scripted answers: one grounded and correct (q01), one that contradicts its chunk (q02, SSO "included on the Team plan"), one grounded and correct with a noisy second chunk (q04), one with a subtle number error (q06: a 99.95% uptime SLA where the chunk says 99.9%), and one where retrieval missed the chunk and the app, sensibly, abstains (q05).
| Case | Retrieved chunk says | The app answers | What a careful reviewer says |
|---|---|---|---|
| q01 | Pro and Team refundable within 30 days | "Yes. Pro plans can be refunded within 30 days." | Correct and grounded |
| q02 | SSO is Enterprise only | "Yes, SSO is included on the Team plan." | Wrong, and unfaithful to its chunk |
| q04 | Team: 600 requests per minute (plus a trial chunk) | "600 requests per minute per workspace." | Correct and grounded |
| q06 | Enterprise has a 99.9% SLA | "...a 99.95% uptime SLA." | Wrong by a hair, unfaithful |
| q05 | (retrieval missed the currency chunk) | "I don't have information about billing currency..." | Honest abstention, but the retrieval failed |
DeepEval side. Faithfulness (with penalize_ambiguous_claims=True, so unsupported claims fail; see 10B.4, 2.3) and Answer Relevancy, with scripted judges that say what a good judge would say. The scripts are per schema, in order, and the runner is sequential so the order is the case order.
# docsqa_deepeval_side.py: the docs_qa eval as DeepEval sees it: RAG metrics over finished records (lesson 10B.17)
from deepeval import evaluate
from deepeval.evaluate import AsyncConfig, DisplayConfig
from deepeval.metrics import AnswerRelevancyMetric, FaithfulnessMetric
from deepeval.test_case import LLMTestCase
from docsqa_data import CASES
from fake_judge import FakeJudge
Y, N = {"verdict": "yes", "reason": "scripted"}, {"verdict": "no", "reason": "scripted"}
R = {"reason": "scripted reason"}
cases = [LLMTestCase(name=cid, input=q, actual_output=ans, expected_output=exp, retrieval_context=ctx)
for cid, q, ctx, ans, exp, _ in CASES] # order: q01 q02 q04 q06 q05
# Scripted judges: what a good judge WOULD say. Faithfulness: q02 and q06 make a claim the chunk does not support.
faith_judge = FakeJudge(script={
"Truths": [{"truths": ["scripted truths"]}] * 5,
"Claims": [{"claims": ["Pro refunds within 30 days."]}, {"claims": ["SSO is on the Team plan."]},
{"claims": ["Team allows 600 requests per minute."]},
{"claims": ["Enterprise has a 99.95% SLA."]}, {"claims": []}], # an abstention makes no claims
"Verdicts": [{"verdicts": [Y]}, {"verdicts": [N]}, {"verdicts": [Y]}, {"verdicts": [N]}],
"FaithfulnessScoreReason": [R] * 5})
rel_judge = FakeJudge(script={
"Statements": [{"statements": ["Pro refunds within 30 days."]}, {"statements": ["SSO is on Team."]},
{"statements": ["600 per minute."]}, {"statements": ["99.95% SLA."]},
{"statements": ["No information about currency."]}],
"Verdicts": [{"verdicts": [Y]}, {"verdicts": [Y]}, {"verdicts": [Y]}, {"verdicts": [Y]},
{"verdicts": [{"verdict": "borderline"}]}],
"AnswerRelevancyScoreReason": [R] * 5})
faith = FaithfulnessMetric(model=faith_judge, penalize_ambiguous_claims=True)
rel = AnswerRelevancyMetric(model=rel_judge)
import contextlib, io # the runner prints a panel; keep our output clean
with contextlib.redirect_stdout(io.StringIO()):
result = evaluate(cases, [faith, rel], async_config=AsyncConfig(run_async=False),
display_config=DisplayConfig(print_results=False, show_indicator=False))
print(f"{'case':5} {'faithfulness':>13} {'answer relevancy':>17}")
for t in sorted(result.test_results, key=lambda t: t.index):
s = {m.name: m.score for m in t.metrics_data}
print(f"{t.name:5} {s['Faithfulness']:>13.2f} {s['Answer Relevancy']:>17.2f}")
print("judge calls: faithfulness", len(faith_judge.calls), "| answer relevancy", len(rel_judge.calls),
"| for", len(cases), "cases")
print("schemas faithfulness asked for:", sorted(set(faith_judge.schemas())))case faithfulness answer relevancy
q01 1.00 1.00
q02 0.00 1.00
q04 1.00 1.00
q06 0.00 1.00
q05 1.00 1.00
judge calls: faithfulness 19 | answer relevancy 15 | for 5 cases
schemas faithfulness asked for: ['Claims', 'FaithfulnessScoreReason', 'Truths', 'Verdicts']Inspect side. Retrieval and prompt construction are a solver (here the chunks are read from the sample, standing in for a retriever), generation is generate(), and there are two scorers: the built-in model_graded_fact(), which compares the answer with the expert answer, and a hand-written grounded() scorer, which asks a grader one question: is every claim supported by the context? Inspect has no faithfulness metric, so this is what you write, in about ten lines. The grader is a scripted model bound to the grader role, so both scorers use it and neither falls back to the model under test.
# docsqa_inspect_side.py: the docs_qa eval as Inspect sees it: retrieval + generation as the solver, graders as scorers (lesson 10B.17)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import CORRECT, INCORRECT, Score, accuracy, model_graded_fact, scorer, stderr
from inspect_ai.solver import Generate, TaskState, generate, solver
from docsqa_data import CASES
ANSWERS = {q: ans for _, q, _, ans, _, _ in CASES} # the scripted app, keyed on the question
GRADER_CALLS: list[str] = [] # every prompt the scripted grader received
@solver
def retrieve_and_ask():
"""The RAG app as a solver: 'retrieve' (here: read the chunks stored on the sample), then build the prompt."""
async def solve(state: TaskState, generate: Generate) -> TaskState:
chunks = state.metadata["context"]
state.store.set("retrieved", chunks) # kept in the log, next to the answer
state.user_prompt.text = ("Answer from the context only.\n\nContext:\n" + "\n".join(chunks)
+ f"\n\nQuestion: {state.input_text}")
return state
return solve
@scorer(metrics=[accuracy(), stderr()])
def grounded():
"""What DeepEval's Faithfulness is for, written by hand: ONE grader call, a verdict, no claim extraction."""
async def score(state: TaskState, target) -> Score:
prompt = ("Context:\n" + "\n".join(state.store.get("retrieved")) + f"\n\nAnswer: {state.output.completion}\n\n"
"Is every claim in the answer supported by the context? End with GRADE: C or GRADE: I.")
reply = await get_model(role="grader", required=True).generate(prompt)
return Score(value=CORRECT if "GRADE: C" in reply.completion else INCORRECT, explanation=reply.completion)
return score
def app_model():
def fn(input, tools, tool_choice, config) -> ModelOutput:
question = input[-1].text.split("Question: ")[-1]
return ModelOutput.from_content(model="mockllm", content=ANSWERS[question])
return get_model("mockllm/model", custom_outputs=fn, memoize=False)
def grader_model():
"""Scripted grader. It 'knows' which answers are right, like a good judge would; the lesson's point is the shape."""
wrong = {"Yes, SSO is included on the Team plan.", "Yes, Enterprise includes a 99.95% uptime SLA."}
def fn(input, tools, tool_choice, config) -> ModelOutput:
prompt = input[-1].text
GRADER_CALLS.append(prompt)
bad = any(w in prompt for w in wrong)
abstains = "I don't have information" in prompt
if "supported by the context" in prompt: # the groundedness question
grade = "C" if not bad else "I"
else: # the reference-match question
grade = "I" if (bad or abstains) else "C"
return ModelOutput.from_content(model="mockllm", content=f"Scripted reasoning.\nGRADE: {grade}")
return get_model("mockllm/grader", custom_outputs=fn, memoize=False)
samples = [Sample(id=cid, input=q, target=exp, metadata={"context": ctx}) for cid, q, ctx, _, exp, _ in CASES]
task = Task(dataset=samples, solver=[retrieve_and_ask(), generate()],
scorer=[model_graded_fact(), grounded()], # both read the "grader" role bound at run time
name="docsqa")
if __name__ == "__main__":
log = eval(task, model=app_model(), model_roles={"grader": grader_model()}, log_dir="logs/docsqa", display="none")[0]
print("status:", log.status)
print(f"{'case':5} {'matches reference':>18} {'grounded':>9}")
for s in log.samples:
print(f"{s.id:5} {s.scores['model_graded_fact'].value:>18} {s.scores['grounded'].value:>9}")
for sc in log.results.scores:
print(f"{sc.name:18}", {k: round(m.value, 3) for k, m in sc.metrics.items()})
print("grader calls:", len(GRADER_CALLS), "for", len(samples), "samples and 2 scorers")status: success
case matches reference grounded
q01 C C
q02 I I
q04 C C
q05 I C
q06 I I
model_graded_fact {'accuracy': 0.4, 'stderr': 0.245}
grounded {'accuracy': 0.6, 'stderr': 0.245}
grader calls: 10 for 5 samples and 2 scorersRead the two outputs together, because they say different things that happen to rhyme.
| Case | DeepEval Faithfulness | DeepEval Answer Relevancy | Inspect grounded |
Inspect matches reference |
|---|---|---|---|---|
| q01 | 1.00 | 1.00 | C | C |
| q02 | 0.00 | 1.00 | I | I |
| q04 | 1.00 | 1.00 | C | C |
| q06 | 0.00 | 1.00 | I | I |
| q05 | 1.00 | 1.00 (a borderline verdict passes) |
C | I |
- Faithfulness and
groundedagree (0.6 and 0.6) because they ask the same question. Both say q02 and q06 are not supported by their chunks. The cost differs: DeepEval made 19 judge calls for faithfulness over five cases (extract truths, extract claims, one verdict call per answer with claims, a reason call) against Inspect's single grader call per sample. The extra calls bought a claim-level breakdown a person can read; the single call bought speed and a single point of failure. - Answer Relevancy is 1.00 for every case, including the wrong ones. It measures whether the answer addresses the question, not whether it is true. A dashboard showing "relevancy 1.00" next to "faithfulness 0.60" is working as designed.
- "Matches reference" (0.4) disagrees with
grounded(0.6) on q05, for a good reason. An abstention makes no claims, so it is vacuously faithful (DeepEval's empty-claims rule gives 1.0, 10B.4, 1.4), and the reference check marks it wrong because it does not contain the expert answer. Neither is wrong. They disagree because they measure different things, and the right response is to name which one your release gate uses. - Neither catches the retrieval failure on q05. The right tool is a retrieval metric: DeepEval's
ContextualRecallMetricagainst an expected answer, or, on the Inspect side, a deterministic check that the gold chunk id is in the retrieved set. That is 10A.6's stage-wise analysis, and it is one reason RAG evals use several metrics and not one. - The standard error of 0.245 on five cases is Inspect telling you the truth. DeepEval printed no uncertainty, and five cases would have deserved one.
3.3 The support agent: recorded versus run#
The third eval is the order-desk agent of 10A.7 and 10B.14: three tasks (refund a lost order, explain the refund policy, refuse to refund an order that does not exist), a world with three orders, and two scripted agents. The oracle agent looks things up first and refunds exactly what it should. The careless agent refunds without looking the order up, emails the customer unprompted, and on the other two tasks answers without calling a tool at all. Plans are plain data both sides replay:
# desk_plans.py: three support-desk tasks and two scripted agents, as plain data (lesson 10B.17)
"""Both frameworks replay the SAME plans: a plan is a list of (tool name, arguments)."""
TASKS = [ # (id, user message, expected refund or None)
("refund-lost", "Order ORD-1002 never arrived. Please refund it in full.",
{"order_id": "ORD-1002", "amount_cents": 8450}),
("policy", "What is your refund policy? My order is ORD-1001.", None),
("unknown-order", "Refund order ORD-9999 please.", None),
]
EXPECTED_TOOLS = {"refund-lost": ["orders_get", "refunds_issue"], "policy": ["docs_search"],
"unknown-order": ["orders_get"]}
ORACLE = {
"refund-lost": [("orders_get", {"order_id": "ORD-1002"}),
("refunds_issue", {"order_id": "ORD-1002", "amount_cents": 8450, "reason": "lost", "confirm": True}),
("submit", {"answer": "Refunded 84.50."})],
"policy": [("docs_search", {"query": "refund policy"}), ("submit", {"answer": "30 days."})],
"unknown-order": [("orders_get", {"order_id": "ORD-9999"}), ("submit", {"answer": "No such order."})],
}
CARELESS = { # right outcome on the refund, wrong process (no lookup, and it emails); then it refunds a ghost order
"refund-lost": [("refunds_issue", {"order_id": "ORD-1002", "amount_cents": 8450, "reason": "lost", "confirm": True}),
("send_email", {"to": "bo@example.com", "subject": "Refund", "body": "Done."}),
("submit", {"answer": "Refunded."})],
"policy": [("submit", {"answer": "30 days."})],
"unknown-order": [("submit", {"answer": "Refunded."})],
}DeepEval side. DeepEval scores a record, so the "agent" is a stub that executes a plan against a plain-Python DeskWorld and records the tool calls; each task becomes a test case with tools_called and the world's final state in metadata. Three metrics: an outcome metric that reads the world (not the model's words), a process metric over the tool names, and DeepEval's deterministic ToolCorrectnessMetric against expected_tools (it still needs a model= at construction, so it gets a FakeJudge that is never called).
# desk_deepeval_side.py: the support-agent eval as DeepEval sees it: a recorded run per task, scored by metrics (lesson 10B.17)
import contextlib, io
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseMetric, ToolCorrectnessMetric
from deepeval.test_case import LLMTestCase, ToolCall
from desk_plans import CARELESS, EXPECTED_TOOLS, ORACLE, TASKS
from desk_world import DeskWorld
from fake_judge import FakeJudge
def run_agent(plan) -> tuple[DeskWorld, list[ToolCall]]:
"""Stands in for your agent: executes a scripted plan against the world and records the tool calls."""
world, calls = DeskWorld(), []
for name, args in plan:
if name != "submit":
world.call(name, args)
calls.append(ToolCall(name=name, input_parameters=args))
return world, calls
class RefundOutcome(BaseMetric):
"""Reads the WORLD, not the model's words (10A.7 Part 3). The world rides along in metadata."""
def __init__(self, threshold: float = 1.0):
self.threshold = threshold
def measure(self, tc, *args, **kwargs) -> float:
want, got = tc.metadata["expect_refund"], tc.metadata["refunds"]
ok = (got == [(want["order_id"], want["amount_cents"])]) if want else (got == [])
ok = ok and not tc.metadata["emails"]
self.score, self.reason, self.success = float(ok), f"refunds={got} emails={len(tc.metadata['emails'])}", ok
return self.score
async def a_measure(self, tc, *args, **kwargs) -> float:
return self.measure(tc)
@property
def __name__(self):
return "refund_outcome"
class ToolPolicy(BaseMetric):
"""Process: look the order up before refunding, and never email."""
def __init__(self, threshold: float = 1.0):
self.threshold = threshold
def measure(self, tc, *args, **kwargs) -> float:
names = [c.name for c in tc.tools_called]
problems = (["emailed the customer"] if "send_email" in names else [])
if "refunds_issue" in names and ("orders_get" not in names or names.index("orders_get") > names.index("refunds_issue")):
problems.append("refund before lookup")
self.score, self.reason, self.success = (0.0 if problems else 1.0), "; ".join(problems) or "ok", not problems
return self.score
async def a_measure(self, tc, *args, **kwargs) -> float:
return self.measure(tc)
@property
def __name__(self):
return "tool_policy"
def cases_for(plans: dict) -> list[LLMTestCase]:
out = []
for tid, message, expect in TASKS:
world, calls = run_agent(plans[tid])
out.append(LLMTestCase(name=tid, input=message, actual_output=plans[tid][-1][1]["answer"], tools_called=calls,
expected_tools=[ToolCall(name=n) for n in EXPECTED_TOOLS[tid]],
metadata={"expect_refund": expect, "refunds": world.refunds, "emails": world.emails}))
return out
def run(label: str, plans: dict) -> dict:
metrics = [RefundOutcome(), ToolPolicy(), ToolCorrectnessMetric(model=FakeJudge(), async_mode=False)]
with contextlib.redirect_stdout(io.StringIO()):
result = evaluate(cases_for(plans), metrics, display_config=DisplayConfig(print_results=False, show_indicator=False))
return {t.name: {m.name: m.score for m in t.metrics_data} for t in sorted(result.test_results, key=lambda t: t.index)}
if __name__ == "__main__":
for label, plans in [("oracle", ORACLE), ("careless", CARELESS)]:
res = run(label, plans)
print(f"{label:9}", {k: (v["refund_outcome"], v["tool_policy"], round(v["Tool Correctness"], 2)) for k, v in res.items()})
for name in ("refund_outcome", "tool_policy", "Tool Correctness"):
print(f"{'':9} {name:17} mean {sum(v[name] for v in res.values()) / len(res):.3f}")oracle {'refund-lost': (1.0, 1.0, 1.0), 'policy': (1.0, 1.0, 1.0), 'unknown-order': (1.0, 1.0, 1.0)}
refund_outcome mean 1.000
tool_policy mean 1.000
Tool Correctness mean 1.000
careless {'refund-lost': (0.0, 0.0, 0.5), 'policy': (1.0, 1.0, 0.0), 'unknown-order': (1.0, 1.0, 0.0)}
refund_outcome mean 0.667
tool_policy mean 0.667
Tool Correctness mean 0.167Inspect side. Here react() runs the agent loop: Inspect sends the task to the scripted model, executes the tool calls it asks for against the real desk.py tools (a per-sample store is the world, as in 10B.14), feeds the results back, and ends on submit. The two scorers are the same two checks, now reading state.messages and the store.
# desk_inspect_side.py: the support-agent eval as Inspect sees it: react() RUNS the agent, scorers read the final world (lesson 10B.17)
from inspect_ai import Task, eval
from inspect_ai.agent import AgentSubmit, react
from inspect_ai.scorer import CORRECT, INCORRECT, Score, accuracy, scorer, stderr
from inspect_ai.dataset import Sample
from desk import call, desk_tools, refund_outcome, scripted # unchanged from lesson 10B.14
from desk_plans import CARELESS, ORACLE, TASKS
@scorer(metrics=[accuracy(), stderr()])
def tool_policy():
async def score(state, target):
names = [c.function for m in state.messages for c in (getattr(m, "tool_calls", None) or [])]
problems = (["emailed the customer"] if "send_email" in names else [])
if "refunds_issue" in names and ("orders_get" not in names or names.index("orders_get") > names.index("refunds_issue")):
problems.append("refund before lookup")
return Score(value=INCORRECT if problems else CORRECT, explanation="; ".join(problems) or "ok")
return score
def desk_task() -> Task:
samples = [Sample(id=tid, input=msg, target="", metadata={"expect_refund": want}) for tid, msg, want in TASKS]
return Task(dataset=samples, scorer=[refund_outcome(), tool_policy()], message_limit=30, name="desk",
solver=react(prompt="You are a support agent for an online shop.", tools=desk_tools(),
submit=AgentSubmit(answer_only=True)))
def plans_for_model(plans: dict) -> dict:
"""desk.scripted() finds the plan by a key that appears in the first user message."""
keys = {"refund-lost": "ORD-1002", "policy": "refund policy", "unknown-order": "ORD-9999"}
return {keys[tid]: [call(name, **args) for name, args in plan] for tid, plan in plans.items()}
if __name__ == "__main__":
for label, plans in [("oracle", ORACLE), ("careless", CARELESS)]:
log = eval(desk_task(), model=scripted(plans_for_model(plans)), log_dir="logs/desk", display="none")[0]
print(f"{label:9}", {s.id: (s.scores["refund_outcome"].value, s.scores["tool_policy"].value) for s in log.samples})
print(f"{'':9}", {sc.name: round(sc.metrics["accuracy"].value, 3) for sc in log.results.scores},
"| messages in the log for refund-lost:", len(next(s for s in log.samples if s.id == "refund-lost").messages))oracle {'policy': ('C', 'C'), 'refund-lost': ('C', 'C'), 'unknown-order': ('C', 'C')}
{'refund_outcome': 1.0, 'tool_policy': 1.0} | messages in the log for refund-lost: 7
careless {'policy': ('C', 'C'), 'refund-lost': ('I', 'I'), 'unknown-order': ('C', 'C')}
{'refund_outcome': 0.667, 'tool_policy': 0.667} | messages in the log for refund-lost: 7What to read:
- Both frameworks agree on the verdicts that both measure. The oracle scores 1.0 on outcome and policy in both. The careless agent gets
refund_outcome0.667 andtool_policy0.667 in both, failing the same task,refund-lost: the refund happened (the money moved correctly), but it emailed the customer and refunded before looking the order up. Right outcome, wrong process: 10A.7, Part 3 in two frameworks. - DeepEval's
ToolCorrectnessMetricadds a question the other scorers did not ask, and it scored the careless agent 0.167. Onpolicyandunknown-orderthe careless agent got the right outcome without callingdocs_searchororders_getat all, andexpected_toolssays it should have. Is that a defect or a harsh metric? It depends on whether answering the policy question from memory is acceptable. The metric asked a stricter question than the hand-written policy scorer, and the point of seeing both is to decide which question you mean, not to take the lower number. - The two sides exercised different amounts of machinery with the same plan. The DeepEval side replayed tool calls against a dictionary. The Inspect side ran a real agent loop: the message list, tool schemas and docstrings,
ToolErrorreturned to the model, the submit mechanism and a message limit. The Inspect log forrefund-lostheld 7 messages. For a scripted plan that is overhead; for a real model it is exactly the part you want recorded. - A real agent changes the DeepEval side most. To evaluate a real agent in DeepEval you would trace it (
@observeon the model call and the tools, 10B.5) and let DeepEval build the test case from the trace. The scripted stub here is the honest keyless stand-in: it proves the metrics, not the agent.
3.4 What the three side-by-sides teach#
| Eval | Same data, same fakes: what differed | Lesson |
|---|---|---|
| Triage | Nothing in the per-case verdicts; the headline numbers differ in definition (pass rate versus per-scorer accuracy with a standard error) | Reconcile cases first. One definition, two wrappers |
docs_qa |
The questions asked: groundedness, relevancy and reference match disagree by design; call counts differ by about four to one (19 versus 5 judge calls for the grounded check) | Name the question behind each number. A built-in faithfulness metric saves you writing a decomposition, not deciding what faithful means |
| Support agent | DeepEval scored a replay of the actions; Inspect ran the loop. A DeepEval-only metric (ToolCorrectness against expected tools) asked a stricter question |
A framework asks the questions it makes cheap. Choose the metrics, not the framework, by the decision the number drives |
Part 4: Combining them#
"Both, with clear ownership" is the answer to Part 2's scorecard more often than people expect. Combining does not mean running everything twice. It means choosing, for each piece of the eval, which framework owns it, and putting a small, tested seam between them. Six seams cover almost every case.
4.1 Six seams#
flowchart LR
C["plain check functions<br/>(your definitions)"]
C --> DE["DeepEval metric"]
C --> IN["Inspect scorer"]
DE -. "seam 2: metric inside a scorer" .-> IN
IN -- "seam 3: logs into evalkit statistics" --> EK["evalkit<br/>paired bootstrap, calibration"]
J["evalkit judge<br/>(one rubric, one parser)"] --> DE
J --> IN
IN -. "seam 5: DeepEval grades an Inspect log" .-> DE
DE -. "seam 5: Inspect grades recorded outputs" .-> IN
DE --> G["one gate"]
IN --> G| Seam | What it combines | Why you would | Cost and risk | Section |
|---|---|---|---|---|
| 1. Write the check once | Plain functions wrapped for each framework | One definition of correct, any number of runners | A wrapper per framework | 3.1 |
| 2. A DeepEval metric inside an Inspect scorer | DeepEval's RAG or safety metric, Inspect's runner, solver and log | Ready-made faithfulness on an Inspect task | Judge calls may bypass Inspect's model layer (unless routed) | 4.3 |
3. Inspect logs into evalkit |
Inspect's runs, evalkit's paired statistics |
The between-run test neither framework has | Join on sample id, same task version | 4.4 |
4. One evalkit judge in both |
A rubric you own, run by either framework | The same judge definition across runners, validated once | Two wrappers to keep in step | 4.5 |
| 5. Grade one framework's run with the other's scorers | DeepEval metrics on an Inspect log, Inspect scorers on recorded outputs | Add a metric to a run you already paid for | Fields may not map cleanly | 4.6 |
| 6. One gate | A single exit decision over both | One red or green for CI | Must fail closed | 4.7 |
4.2 Write the check once#
Seam 1 is 3.1, and it is worth turning into a rule because everything else gets easier when it holds. A check that you will use in two frameworks should be:
- A pure function of plain values:
check_labels(reply, expected, allow_empty_summary) -> (score, reason). No framework imports, noself, no async. - Tested without a framework: a handful of
pytesttests that call the function with strings and assert on the score and reason. It is the cheapest test you will write and the one that most often finds a bug. - Named and versioned:
triage_labels@2, so a run record can say which definition produced a number (6.5). - Wrapped thinly: one adapter per framework that converts that framework's objects to plain values and the function's result back to a
Scoreor a metric score. Anything more in the adapter is a second definition waiting to drift.
The same rule serves evalkit: the Scorer of 10A.1 is a wrapper over the same functions, and 10B.2, 8.3 and 10B.11, 9.4 show the adapters in the other direction.
4.3 A DeepEval metric inside an Inspect scorer#
The use case: you want DeepEval's faithfulness (or answer relevancy, or a safety metric) on an Inspect task, because the task is a RAG pipeline with tools, or you want logs, epochs and sandboxes with a metric you did not want to rewrite. A scorer is just an async function that returns a Score, so it can call await metric.a_measure(test_case) and translate the result.
# combo_deepeval_in_inspect.py: a DeepEval metric as an Inspect scorer, keyless: FakeJudge + mockllm (lesson 10B.17)
from deepeval.metrics import FaithfulnessMetric
from deepeval.test_case import LLMTestCase
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import Score, mean, scorer, stderr
from inspect_ai.solver import generate
from docsqa_data import CASES
from docsqa_inspect_side import app_model, retrieve_and_ask
from fake_judge import FakeJudge
Y, N = {"verdict": "yes", "reason": "scripted"}, {"verdict": "no", "reason": "scripted"}
WRONG = {"Yes, SSO is included on the Team plan.", "Yes, Enterprise includes a 99.95% uptime SLA."}
JUDGES: list[FakeJudge] = [] # kept only so the sample can count calls
def make_judge() -> FakeJudge:
"""Routes, not a queue: Inspect scores samples concurrently, so replies must not depend on call order."""
routes = {"Truths": [("", {"truths": ["scripted truths"]})],
"Claims": [(ans, {"claims": [ans]}) for _, _, _, ans, _, _ in CASES if "don't have" not in ans]
+ [("don't have", {"claims": []})],
"Verdicts": [(ans, {"verdicts": [N if ans in WRONG else Y]}) for _, _, _, ans, _, _ in CASES],
"FaithfulnessScoreReason": [("", {"reason": "scripted reason"})]}
judge = FakeJudge(routes=routes)
JUDGES.append(judge)
return judge
@scorer(metrics=[mean(), stderr()])
def deepeval_faithfulness(threshold: float = 0.5):
async def score(state, target) -> Score:
# Build the metric INSIDE the scorer: one fresh object per sample, so no state is shared between samples
# (the copy rule of 10B.2, 4.5, done by hand). The judge is passed in: no key, no default-model lookup.
metric = FaithfulnessMetric(model=make_judge(), threshold=threshold, penalize_ambiguous_claims=True,
async_mode=True)
case = LLMTestCase(input=state.input_text, actual_output=state.output.completion,
retrieval_context=state.store.get("retrieved"))
await metric.a_measure(case)
return Score(value=metric.score, answer=state.output.completion, explanation=metric.reason,
metadata={"deepeval_success": metric.success, "judge_calls": len(metric.model.calls)})
return score
samples = [Sample(id=cid, input=q, target=exp, metadata={"context": ctx}) for cid, q, ctx, _, exp, _ in CASES]
task = Task(dataset=samples, solver=[retrieve_and_ask(), generate()], scorer=deepeval_faithfulness(), name="docsqa_de")
if __name__ == "__main__":
log = eval(task, model=app_model(), log_dir="logs/combo", display="none")[0]
print("status:", log.status)
for s in log.samples:
sc = s.scores["deepeval_faithfulness"]
print(f"{s.id:4} value={sc.value:.1f} deepeval_success={sc.metadata['deepeval_success']!s:5} "
f"judge_calls={sc.metadata['judge_calls']} reason={sc.explanation[:40]!r}")
r = log.results.scores[0]
print({k: round(m.value, 3) for k, m in r.metrics.items()}, "| scored", r.scored_samples, "unscored", r.unscored_samples)
print("total judge calls:", sum(len(j.calls) for j in JUDGES), "across", len(JUDGES), "fresh judges")
status: success
q01 value=1.0 deepeval_success=True judge_calls=4 reason='scripted reason'
q02 value=0.0 deepeval_success=False judge_calls=4 reason='scripted reason'
q04 value=1.0 deepeval_success=True judge_calls=4 reason='scripted reason'
q05 value=1.0 deepeval_success=True judge_calls=3 reason='scripted reason'
q06 value=0.0 deepeval_success=False judge_calls=4 reason='scripted reason'
{'mean': 0.6, 'stderr': 0.245} | scored 5 unscored 0
total judge calls: 19 across 5 fresh judgesThe blank lines at the top are DeepEval's own output while it builds the metrics, not a paste error.
This matches the DeepEval-only run of 3.2 exactly (1, 0, 1, 1, 0 for q01, q02, q04, q05, q06 in Inspect's sort order; 19 judge calls). Five rules made it work, and each is a trap if you skip it:
- Build the metric inside the scorer, once per sample. Metrics are stateful (
score,reason,success, cached judge output live on the object). A module-level metric shared by concurrent samples races. DeepEval's own runner copies metrics for the same reason (10B.2, 4.5); here you do the copy by constructing a fresh one. - Pass the judge explicitly.
model=avoids the default-judge lookup that needs a key at construction (10B.2, 3.4); in production it is the same argument with a real wrapper. - Use
a_measure. The scorer is async and Inspect runs samples concurrently on one event loop; a synchronousmeasure()would block it. - Make a scripted judge order-independent. Inspect scores samples concurrently, so a queue of scripted replies would be popped in a different order each run. This sample's
FakeJudgeanswers by routes (the answer text decides the reply). 10B.1, 6.7 and 10B.8, 3.5 make the same point formockllm. - Translate, do not hide. The scorer returns the float as the value, the DeepEval
reasonas the explanation, and DeepEval's pass decision and call count inmetadata. Inspect'smean()andstderr()then summarize the scores, and your DeepEval threshold is still available per sample. Do not feed a threshold-based 0 or 1 intoaccuracy()unless you want pass rate, not mean score, as the headline.
One seam is leaky. DeepEval calls its judge itself. Those calls do not pass through Inspect's model layer, so Inspect's concurrency limits, retries, response cache and usage accounting do not apply to them, and the log shows the scores but not the judge's messages. A thousand-sample run can therefore overrun the judge's rate limit even though Inspect is configured conservatively. The fix is to make the judge an Inspect model:
# combo_inspect_model_as_judge.py: route DeepEval's judge calls THROUGH Inspect's model layer (lesson 10B.17)
import json
from deepeval.metrics import FaithfulnessMetric
from deepeval.models import DeepEvalBaseLLM
from deepeval.test_case import LLMTestCase
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import Score, mean, scorer, stderr
from inspect_ai.solver import generate
class InspectJudge(DeepEvalBaseLLM):
"""A DeepEval judge whose every call is made by Inspect's `grader` role model.
Inspect's concurrency limits, retries, cache and usage accounting then apply to the judge calls too."""
def __init__(self, role: str = "grader"):
self.role = role
super().__init__(model=f"inspect-role-{role}")
def load_model(self):
return self
def generate(self, prompt: str, schema=None):
raise RuntimeError("use the async path inside an Inspect task")
async def a_generate(self, prompt: str, schema=None):
reply = await get_model(role=self.role, required=True).generate(prompt) # a normal Inspect model call
return schema.model_validate_json(reply.completion) if schema else reply.completion
def get_model_name(self) -> str:
return f"inspect-role-{self.role}"
@scorer(metrics=[mean(), stderr()])
def faithfulness_via_inspect():
async def score(state, target) -> Score:
metric = FaithfulnessMetric(model=InspectJudge(), async_mode=True) # one fresh metric per sample
case = LLMTestCase(input=state.input_text, actual_output=state.output.completion,
retrieval_context=["Pro plans can be refunded within 30 days of purchase."])
await metric.a_measure(case)
return Score(value=metric.score, explanation=metric.reason)
return score
def grader(input, tools, tool_choice, config) -> ModelOutput:
"""A scripted grader that answers whatever schema DeepEval's prompt asks for."""
prompt = input[-1].text
if "truths" in prompt.lower() and "claims" not in prompt.lower():
body = {"truths": ["Pro plans can be refunded within 30 days."]}
elif "claims" in prompt.lower() and "verdict" not in prompt.lower() and "reason" not in prompt.lower():
body = {"claims": ["Pro plans can be refunded within 30 days."]}
elif "verdict" in prompt.lower():
body = {"verdicts": [{"verdict": "yes", "reason": "scripted"}]}
else:
body = {"reason": "scripted reason"}
return ModelOutput.from_content(model="mockllm", content=json.dumps(body))
task = Task(dataset=[Sample(id="q01", input="Can I get a refund on Pro?", target="30 days")],
solver=generate(), scorer=faithfulness_via_inspect())
log = eval(task, model="mockllm/model", model_roles={"grader": get_model("mockllm/grader", custom_outputs=grader, memoize=False)},
log_dir="logs/judge_via_inspect", display="none")[0]
s = log.samples[0]
print("status:", log.status, "| score:", s.scores["faithfulness_via_inspect"].value)
print("model events in the sample:", sum(e.event == "model" for e in s.events), "(the answer plus the judge's calls)")
print("grader calls in the log's usage:", {k: v.total_tokens > 0 for k, v in log.stats.model_usage.items()})status: success | score: 1.0
model events in the sample: 5 (the answer plus the judge's calls)
grader calls in the log's usage: {'mockllm/model': True, 'mockllm/grader': True}(The blank first line is DeepEval's own output.)
Now the DeepEval judge's four requests (truths, claims, verdicts, reason) were made by the grader role: they sit in the sample's events (five model events, the answer plus four judge calls), the grader's usage is in the log, and Inspect's concurrency limit, retry policy govern them, and the response cache can too if you pass cache= in InspectJudge.a_generate (the sample does not) (10B.12). Bind the role as you would for any model-graded scorer (--model-role grader=...). The scripted grader here picks its reply from keywords in DeepEval's prompt, which is a fixture; a real model needs a structured-output setting or a robust JSON parse, as every custom DeepEval judge does (10B.3, 3.5).
4.4 Inspect logs into evalkit's statistics#
Inspect prints a standard error per run and no between-run test. evalkit's paired bootstrap (10A.8, Part 2) answers the question a release decision asks: is v2 better than v1 on the same cases? The bridge is a dictionary from sample id to a per-sample number. This sample runs the triage task twice (v2 is scripted to fix T02 and T11 and break T05) and feeds the logs in.
# combo_logs_to_evalkit.py: two Inspect runs in, evalkit's paired statistics out (lesson 10B.17)
from inspect_ai import eval
from inspect_ai.log import EvalLog
from inspect_ai.model import ModelOutput, get_model
import triage_inspect_side as ins
from evalkit.cluster import paired_cluster_bootstrap_ci
from evalkit.compare import (min_detectable_effect, paired_bootstrap_ci, paired_diffs,
paired_effect_size, sign_flip_permutation_p)
from triage_data import RESPONSES, TICKETS
# "v2": a prompt change that fixes T02 and T11 and breaks T05 (scripted, so the effect is known)
V2 = dict(RESPONSES,
T02='{"priority": "P1", "category": "technical", "summary": "Login outage, 500 on every page."}',
T11='{"priority": "P2", "category": "billing", "summary": "Duplicate charge, refund requested."}',
T05='{"priority": "P2", "category": "other", "summary": "Order tracking stale two weeks."}')
def model_for(responses: dict):
def fn(input, tools, tool_choice, config) -> ModelOutput:
prompt = input[-1].text
reply = next((responses[tid] for tid, text, _, _ in TICKETS if text and text in prompt), responses["T10"])
return ModelOutput.from_content(model="mockllm", content=reply)
return get_model("mockllm/model", custom_outputs=fn, memoize=False)
def run(responses: dict, log_dir: str) -> EvalLog:
return eval(ins.triage_task(), model=model_for(responses), log_dir=log_dir, display="none")[0]
def per_sample(log: EvalLog, scorer: str) -> dict[str, float]:
"""Join key = sample id. Never join logs by position (10B.8, 7.3)."""
assert log.status == "success", f"refusing to compare a {log.status} run"
return {str(s.id): float(s.scores[scorer].value) for s in log.samples}
v1, v2 = run(RESPONSES, "logs/v1"), run(V2, "logs/v2")
assert v1.eval.task_version == v2.eval.task_version
a, b = per_sample(v1, "triage_labels"), per_sample(v2, "triage_labels")
for name, log in (("v1", v1), ("v2", v2)): # what Inspect prints: two means, two stderrs
m = log.results.scores[1].metrics["mean"], log.results.scores[1].metrics["stderr"]
print(f"{name}: labels mean {m[0].value:.3f} stderr {m[1].value:.3f}")
diffs = paired_diffs(a, b) # what the decision needs: a paired difference
mean_d, lo, hi = paired_bootstrap_ci(diffs)
print(f"paired diff v2-v1: {mean_d:+.3f} 95% CI [{lo:+.3f}, {hi:+.3f}] over {len(diffs)} tickets")
print(f"sign-flip p = {sign_flip_permutation_p(diffs):.3f} effect size d = {paired_effect_size(diffs):.2f}")
sd = (sum((d - mean_d) ** 2 for d in diffs) / (len(diffs) - 1)) ** 0.5
print(f"smallest paired effect 12 tickets could detect: {min_detectable_effect(len(diffs), sd):.3f}")
print("changed tickets:", {k: round(b[k] - a[k], 3) for k in sorted(a) if a[k] != b[k]})
groups: dict[str, list[float]] = {} # tickets of one intent share a cause: resample groups
for tid, _, _, meta in TICKETS:
groups.setdefault(meta["intent"], []).append(b[tid] - a[tid])
mc, lc, hc = paired_cluster_bootstrap_ci(groups)
print(f"clustered by intent ({len(groups)} groups): {mc:+.3f} 95% CI [{lc:+.3f}, {hc:+.3f}]")v1: labels mean 0.889 stderr 0.075
v2: labels mean 0.972 stderr 0.028
paired diff v2-v1: +0.083 95% CI [-0.056, +0.250] over 12 tickets
sign-flip p = 0.501 effect size d = 0.29
smallest paired effect 12 tickets could detect: 0.233
changed tickets: {'T02': 0.667, 'T05': -0.333, 'T11': 0.667}
clustered by intent (5 groups): +0.083 95% CI [-0.074, +0.190]Read it as the lesson on why the bridge matters. Inspect's two printed lines say v1 is at 0.889 (stderr 0.075) and v2 at 0.972 (stderr 0.028): an improvement of 0.083 that looks decisive. The paired statistics say otherwise: the mean paired difference is +0.083 with a 95% interval of -0.056 to +0.250, the sign-flip p-value is 0.50, and the effect size is 0.29. Twelve tickets cannot detect a paired effect smaller than about 0.23, so the apparent gain is well inside the noise. Grouping the tickets by intent (five groups, since tickets of one intent share causes) gives a similar picture: +0.083 with an interval of -0.074 to +0.190, still straddling zero. With only five groups the clustered interval is itself unstable, so read it as "no evidence either way", not as a more precise answer. Three things in the code are the discipline:
- Join on the sample id, not on position:
per_samplekeys a dictionary bys.id. Joining two logs by position is the most common way to get a nonsense comparison (10B.8, 7.3). - Refuse to compare unlike runs: the status must be
successand thetask_versionmust match (assert v1.eval.task_version == v2.eval.task_version). Add the epochs, reducers and the git commit to the check when they matter (10B.10, 8.3). - State the minimum detectable effect before you run, not after:
min_detectable_effect(12, sd)is the answer to "could this eval have seen the change we hoped for?"
The same function takes DeepEval's per-case scores. {t.name: m.score for t in result.test_results ...} from 3.1 is a scores_a dictionary, and paired_diffs and paired_bootstrap_ci do not care where it came from. That is what keeps statistics independent of the runner.
4.5 One evalkit judge in both frameworks#
Judges are the part of an eval you most want to define once, because validating a judge (10A.5) is the expensive step, and a validated rubric that exists in two versions is two unvalidated rubrics. evalkit's rubric_judge takes a plain call_model(prompt) -> str function and a Rubric, and returns a JudgeResult. Everything above that call is the same for both frameworks.
# combo_evalkit_judge_in_both.py: ONE evalkit judge, used as a DeepEval metric AND as an Inspect scorer (lesson 10B.17)
import contextlib, io
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import Score, mean, scorer, stderr
from inspect_ai.solver import generate
from docsqa_data import CASES
from evalkit.judges import FakeCallModel, Rubric, RubricCriterion, rubric_judge
RUBRIC = Rubric("docsqa_answer", "2",
(RubricCriterion("accuracy", "1 = contradicts the reference, 5 = every fact matches"),
RubricCriterion("completeness", "1 = misses the point, 5 = covers what the reference covers")),
scale=(1, 5), pass_at=0.75)
SCORES = {"q01": 5, "q02": 1, "q04": 5, "q05": 2, "q06": 2} # what the scripted judge says per case
ANSWER_TO_ID = {ans: cid for cid, _, _, ans, _, _ in CASES}
# evalkit's own seam: a plain `call_model(prompt) -> str`. FakeCallModel matches a needle in the prompt.
call_model = FakeCallModel(rules=[(ans, {"score": SCORES[cid], "rationale": f"scripted for {cid}"})
for ans, cid in ANSWER_TO_ID.items()])
def judge(question: str, answer: str, reference: str):
"""The ONE definition. Nothing below this line knows what a rubric is."""
r = Rubric(RUBRIC.name, RUBRIC.version, RUBRIC.criteria, RUBRIC.scale, RUBRIC.instructions, RUBRIC.pass_at,
reference=reference)
return rubric_judge(call_model, rubric=r, question=question, answer=answer)
class EvalkitRubric(BaseMetric): # ---- wrapper 1: DeepEval
def __init__(self, threshold: float = 0.75):
self.threshold = threshold
def measure(self, tc: LLMTestCase, *args, **kwargs) -> float:
res = judge(tc.input, tc.actual_output, tc.expected_output)
self.score, self.reason, self.success = res.score01, res.rationale, bool(res.passed)
return self.score
async def a_measure(self, tc, *args, **kwargs) -> float:
return self.measure(tc)
@property
def __name__(self):
return "evalkit rubric"
@scorer(metrics=[mean(), stderr()]) # ---- wrapper 2: Inspect
def evalkit_rubric():
async def score(state, target) -> Score:
res = judge(state.input_text, state.output.completion, target.text)
return Score(value=res.score01, explanation=res.rationale, metadata={"passed": res.passed})
return score
cases = [LLMTestCase(name=cid, input=q, actual_output=ans, expected_output=exp) for cid, q, _, ans, exp, _ in CASES]
with contextlib.redirect_stdout(io.StringIO()):
result = evaluate(cases, [EvalkitRubric()], display_config=DisplayConfig(print_results=False, show_indicator=False))
de = {t.name: round(t.metrics_data[0].score, 2) for t in result.test_results}
by_question = {q: ans for _, q, _, ans, _, _ in CASES}
app = get_model("mockllm/model", memoize=False, custom_outputs=lambda input, tools, tool_choice, config:
ModelOutput.from_content(model="mockllm", content=by_question[input[-1].text]))
log = eval(Task(dataset=[Sample(id=cid, input=q, target=exp) for cid, q, _, _, exp, _ in CASES],
solver=generate(), scorer=evalkit_rubric()), model=app, log_dir="logs/judge", display="none")[0]
ins = {str(s.id): round(s.scores["evalkit_rubric"].value, 2) for s in log.samples}
print("DeepEval :", de)
print("Inspect :", ins)
print("identical:", de == ins, "| mean", round(sum(ins.values()) / len(ins), 3), "| judge calls:", len(call_model.prompts))DeepEval : {'q01': 1.0, 'q02': 0.0, 'q04': 1.0, 'q06': 0.25, 'q05': 0.25}
Inspect : {'q01': 1.0, 'q02': 0.0, 'q04': 1.0, 'q05': 0.25, 'q06': 0.25}
identical: True | mean 0.5 | judge calls: 10The DeepEval metric and the Inspect scorer gave identical scores for all five cases (q05 and q06 each 0.25: a score of 2 on a 1-to-5 rubric, normalized), because each is a three-line wrapper over judge(). The judge was called ten times, five per framework. In real use the call_model function wraps a provider SDK, and the same Rubric object travels with you. Two routes bring the judge's model call into each framework's own machinery:
- Into DeepEval as a judge model. Any
call_modelbecomes aDeepEvalBaseLLM, so DeepEval's built-in metrics (G-Eval here) can use it. This is the adapter of 10B.3, 3.5 withevalkit's function behind it:
# combo_callmodel_as_judge.py: evalkit's `call_model(prompt) -> str` seam as a DeepEval judge (lesson 10B.17)
import contextlib, io
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.metrics import GEval
from deepeval.models import DeepEvalBaseLLM
from deepeval.test_case import LLMTestCase, SingleTurnParams
from evalkit.judges import FakeCallModel
class CallModelJudge(DeepEvalBaseLLM):
"""Any evalkit call_model (a function from prompt to text) becomes a DeepEval judge.
With a real provider the function would call the SDK; here it is evalkit's scripted FakeCallModel."""
def __init__(self, call_model, name: str = "evalkit-call-model"):
self.call_model, self._name = call_model, name
super().__init__(model=name)
def load_model(self):
return self
def generate(self, prompt: str, schema=None):
text = self.call_model(prompt) # the JSON text the judge "wrote"
return schema.model_validate_json(text) if schema else text
async def a_generate(self, prompt: str, schema=None):
return self.generate(prompt, schema)
def get_model_name(self) -> str:
return self._name
fake = FakeCallModel(rules=[("I don't have information", {"reason": "An abstention names no facts.", "score": 3})],
default={"reason": "Covers the reference facts.", "score": 9})
metric = GEval(name="Answer vs reference", model=CallModelJudge(fake),
evaluation_steps=["Check every fact in the answer against the expected output.",
"Penalize missing or contradicted facts."],
evaluation_params=[SingleTurnParams.INPUT, SingleTurnParams.ACTUAL_OUTPUT,
SingleTurnParams.EXPECTED_OUTPUT], async_mode=False)
cases = [LLMTestCase(name="q01", input="Refund on Pro?", actual_output="Yes, within 30 days.", expected_output="30 days."),
LLMTestCase(name="q05", input="Change currency?", actual_output="I don't have information about that.",
expected_output="Contact support.")]
with contextlib.redirect_stdout(io.StringIO()):
res = evaluate(cases, [metric], display_config=DisplayConfig(print_results=False, show_indicator=False))
for t in sorted(res.test_results, key=lambda t: t.index):
m = t.metrics_data[0]
print(f"{t.name} score={m.score} success={m.success} reason={m.reason!r}")
print("call_model received", len(fake.prompts), "prompts; first 60 chars:", repr(fake.prompts[0][:60]))q01 score=0.9 success=True reason='Covers the reference facts.'
q05 score=0.3 success=False reason='An abstention names no facts.'
call_model received 2 prompts; first 60 chars: 'You are an evaluator. Given the following evaluation steps, '- Into Inspect through the
graderrole. Inspect's own model layer makes the call (so concurrency, cache and usage apply), andevalkit's prompt builder and parser run around it: this is 10B.11, 9.4, which also showsScore.unscoredfor the judge's "uncertain" verdict.
4.6 Score one framework's run with the other's scorers#
You do not always have to re-run the model to add a metric. A run made in one framework holds the inputs and outputs the other needs, and a small converter carries them across.
# migrate_runs.py: score a run made in one framework with the other framework's scorers (lesson 10B.17)
import contextlib, io
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.test_case import LLMTestCase, ToolCall
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.log import EvalLog
from inspect_ai.scorer import CORRECT
from inspect_ai.solver import Generate, TaskState, solver
import triage_deepeval_side as de
import triage_inspect_side as ins
from triage_checks import check_format, check_labels
from triage_data import RESPONSES, TICKETS
# ---- A. Inspect log -> DeepEval test cases: DeepEval metrics grade what Inspect ran -----------------------------
def log_to_test_cases(log: EvalLog) -> list[LLMTestCase]:
assert log.status == "success", log.status
cases = []
for s in log.samples:
calls = [ToolCall(name=c.function, input_parameters=c.arguments)
for m in s.messages for c in (getattr(m, "tool_calls", None) or [])]
cases.append(LLMTestCase(name=str(s.id), input=s.input if isinstance(s.input, str) else s.messages[0].text,
actual_output=s.output.completion, expected_output=s.target if isinstance(s.target, str) else s.target[0],
tools_called=calls or None, metadata=s.metadata))
return cases
log = ins.run()["log"]
cases = log_to_test_cases(log)
metrics = [de.FromCheck("format", lambda tc: check_format(tc.actual_output)),
de.FromCheck("labels", lambda tc: check_labels(tc.actual_output, tc.expected_output,
(tc.metadata or {}).get("allow_empty_summary") == "1"))]
with contextlib.redirect_stdout(io.StringIO()):
res = evaluate(cases, metrics, display_config=DisplayConfig(print_results=False, show_indicator=False))
failing = sorted(t.name for t in res.test_results if not t.success)
print("A. DeepEval grading an Inspect log -> failing:", failing, "| cases:", len(cases))
# ---- B. DeepEval records -> Inspect: a solver that REPLAYS recorded outputs, then Inspect scorers grade them -------
@solver
def replay(outputs: dict[str, str]):
async def solve(state: TaskState, generate: Generate) -> TaskState:
state.output.completion = outputs[str(state.sample_id)] # no model call: the answer was recorded earlier
return state
return solve
recorded = {tc.name: tc.actual_output for tc in
[LLMTestCase(name=tid, input=text, actual_output=RESPONSES[tid]) for tid, text, _, _ in TICKETS]}
task = Task(dataset=[Sample(id=tid, input=text, target=ref, metadata=meta) for tid, text, ref, meta in TICKETS],
solver=replay(recorded), scorer=[ins.triage_format(), ins.triage_labels()], name="replay")
log2 = eval(task, model="mockllm/model", log_dir="logs/replay", display="none")[0]
failing2 = sorted(s.id for s in log2.samples
if s.scores["triage_format"].value != CORRECT or s.scores["triage_labels"].value != 1.0)
print("B. Inspect grading recorded outputs -> failing:", failing2, "| model calls:",
sum(u.total_tokens > 0 for u in log2.stats.model_usage.values()) if log2.stats.model_usage else 0)A. DeepEval grading an Inspect log -> failing: ['T02', 'T11'] | cases: 12
B. Inspect grading recorded outputs -> failing: ['T02', 'T11'] | model calls: 0- A. DeepEval metrics over an Inspect log.
log_to_test_casesturns eachEvalSampleinto anLLMTestCase: the output fromstate.output.completion, the expected output from the target, tool calls from the messages. DeepEval's metrics then grade what Inspect ran. Use it to add a RAG or safety metric to a run you already paid for, or to give the Inspect log a CI gate in pytest form. The same two tickets fail. Refuse to convert a log whose status is notsuccess. - B. Inspect scorers over recorded DeepEval outputs. A
replaysolver returns each recorded output for its sample and never calls a model (the script counted no model usage), so Inspect's scorers, statistics and viewer apply to answers you captured earlier, for example from production traffic.inspect scoredoes the same for an existing Inspect log (10B.13, Part 6).
Fields that do not map cleanly are the reason to inspect a converted case before you trust it: Inspect has no retrieval_context (put it in metadata or the store and map it by name), DeepEval has no per-sample message history, and a multi-turn Inspect run becomes a ConversationalTestCase only if you build the turns yourself.
4.7 One gate for two frameworks#
A pull request needs one answer. The gate below reads an Inspect log and a DeepEval result and returns the reasons a run must not pass, not just a boolean, and it fails closed: an empty scan is a failure, a vanished case is a failure, a scorer that stopped covering every sample is a failure. It encodes the lessons of 10B.7, 2.3 and 10B.12, Part 13.
# combined_gate.py: ONE exit decision over an Inspect log and a DeepEval result; fail closed (lesson 10B.17)
import contextlib, io
import math
from inspect_ai import Task, eval
from inspect_ai.log import EvalLog
from inspect_ai.model import get_model
from inspect_ai.scorer import scorer, accuracy, mean, stderr
from deepeval import evaluate
from deepeval.evaluate import DisplayConfig
from deepeval.test_case import LLMTestCase
import triage_deepeval_side as de
import triage_inspect_side as ins
from triage_checks import check_format, check_labels
from triage_data import RESPONSES, TICKETS
def gate_inspect(log: EvalLog, *, scorer_name: str, metric: str, minimum: float, expected: int) -> list[str]:
"""Why an Inspect run must NOT pass. `inspect eval` exits 0 on error status (10B.12, Part 13), so the log decides."""
problems = []
if log.status != "success":
return [f"status is {log.status}"]
if len(log.samples or []) != expected:
problems.append(f"{len(log.samples or [])} samples in the log, expected {expected}")
sc = next((s for s in log.results.scores if s.name == scorer_name), None)
if sc is None:
return problems + [f"no results for scorer {scorer_name!r}"]
if sc.scored_samples != expected:
problems.append(f"scored {sc.scored_samples} of {expected} (unscored {sc.unscored_samples})")
value = sc.metrics[metric].value
if math.isnan(value) or value < minimum:
problems.append(f"{scorer_name} {metric} {value:.3f} below {minimum}")
return problems
def gate_deepeval(test_results, *, expected: int, metrics_per_case: int) -> list[str]:
"""Why a DeepEval run must NOT pass: an empty scan, a vanished case, a case with missing metrics, a failure."""
problems = []
if not test_results:
return ["empty scan: no test results"]
if len(test_results) != expected:
problems.append(f"{len(test_results)} cases, expected {expected}")
for t in test_results:
if len(t.metrics_data or []) != metrics_per_case:
problems.append(f"{t.name}: {len(t.metrics_data or [])} metrics, expected {metrics_per_case}")
elif not t.success:
problems.append(f"{t.name}: failed")
return problems
def show(label: str, problems: list[str]) -> None:
print(f"{label:34} -> {'PASS' if not problems else 'FAIL'} {problems}")
# ---- Inspect: a healthy run, then the same run where the scorer crashes on one sample and errors are tolerated
good = ins.run()["log"]
show("inspect, healthy (labels >= 0.85)", gate_inspect(good, scorer_name="triage_labels", metric="mean", minimum=0.85, expected=12))
@scorer(metrics=[mean(), stderr()])
def flaky_labels():
inner = ins.triage_labels()
async def score(state, target):
if state.sample_id == "T05":
raise RuntimeError("scorer bug on one sample")
return await inner(state, target)
return score
task = ins.triage_task()
task.scorer = [ins.triage_format(), flaky_labels()]
bad = eval(task, model=get_model("mockllm/model", custom_outputs=ins.fake_model, memoize=False),
log_dir="logs/flaky", fail_on_error=False, display="none")[0]
print("flaky run status:", bad.status, "| printed labels mean:",
round(next(s for s in bad.results.scores if s.name == "flaky_labels").metrics["mean"].value, 3))
show("inspect, scorer crash tolerated", gate_inspect(bad, scorer_name="flaky_labels", metric="mean", minimum=0.85, expected=12))
# ---- DeepEval: a healthy run, a run where a case silently vanished, and an empty scan
metrics = [de.FromCheck("format", lambda tc: check_format(tc.actual_output)),
de.FromCheck("labels", lambda tc: check_labels(tc.actual_output, tc.expected_output,
(tc.metadata or {}).get("allow_empty_summary") == "1"))]
cases = [LLMTestCase(name=t, input=x, actual_output=RESPONSES[t], expected_output=r, metadata=m) for t, x, r, m in TICKETS]
with contextlib.redirect_stdout(io.StringIO()):
res = evaluate(cases, metrics, display_config=DisplayConfig(print_results=False, show_indicator=False))
show("deepeval, 2 real failures", gate_deepeval(res.test_results, expected=12, metrics_per_case=2))
show("deepeval, a case vanished", gate_deepeval(res.test_results[:-1], expected=12, metrics_per_case=2))
show("deepeval, empty scan", gate_deepeval([], expected=12, metrics_per_case=2))inspect, healthy (labels >= 0.85) -> PASS []
flaky run status: success | printed labels mean: 0.879
inspect, scorer crash tolerated -> FAIL ['scored 11 of 12 (unscored 0)']
deepeval, 2 real failures -> FAIL ['T02: failed', 'T11: failed']
deepeval, a case vanished -> FAIL ['11 cases, expected 12', 'T02: failed', 'T11: failed']
deepeval, empty scan -> FAIL ['empty scan: no test results']The interesting line is the third (inspect, scorer crash tolerated). A scorer that crashed on one ticket, with errors tolerated, still printed a labels mean of 0.879, above the 0.85 minimum, so a gate that read only the printed number would have passed it. The coverage check (scored 11 of 12) fails it, which is the whole case for gating on the log's structure and not on its headline. Everything else follows: the inspect, healthy line passes; the three deepeval lines show a real failure, a vanished case and an empty scan, each failing with its reason. In CI, call both gates, print every reason, and exit non-zero if either returned any. Keep the thresholds in a file in the repository so a change of threshold is a reviewed diff.
Traced DeepEval runs need two more checks. gate_deepeval reads test_results, which is enough for test cases you built yourself. A traced run (10B.5) has two more ways to pass while checking less than you think, both reproduced in 10B.5: a tool that raises and is caught by the agent leaves an ERRORED span whose metrics are skipped while the golden passes (10B.5, 4.5), and a golden's expected_output never reaches the traced test case unless your code copies it (10B.5, 4.3). (A span is one recorded step inside a trace, such as one tool call; DeepEval marks a span ERRORED when the function it wraps raised an exception, even if a caller caught it.) This sample traces a three-order support agent whose order service times out on one order, and gates the run file DeepEval writes:
# gate_traced.py: the DeepEval half of the gate, for TRACED runs: errored spans and skipped metrics (lesson 10B.17, 4.7)
import contextlib, io, json
from pathlib import Path
from deepeval.dataset import EvaluationDataset, Golden, get_current_golden
from deepeval.evaluate import AsyncConfig, DisplayConfig, ErrorConfig
from deepeval.metrics import ExactMatchMetric
from deepeval.tracing import observe, update_current_trace
ORDERS = {"A-1": "delivered", "A-2": "shipped"}
GOLDENS = [("known-1", "Where is order A-1?", "Order A-1 is delivered."),
("known-2", "Where is order A-2?", "Order A-2 is shipped."),
("flaky", "Where is order A-3?", "Sorry, I cannot find order A-3.")]
SPAN_LISTS = ("agentSpans", "llmSpans", "retrieverSpans", "toolSpans", "baseSpans")
@observe(type="tool")
def lookup(order_id: str) -> str:
if order_id not in ORDERS:
raise TimeoutError("order service timed out") # a crash, not "no such order"
return ORDERS[order_id]
@observe(type="agent")
def agent(query: str, copy_expected: bool) -> str:
order_id = query.rstrip("?").split()[-1]
try:
answer = f"Order {order_id} is {lookup(order_id)}."
except TimeoutError:
answer = f"Sorry, I cannot find order {order_id}." # the fallback hides the crash
expected = get_current_golden().expected_output if copy_expected else None # 10B.5, 4.3
update_current_trace(input=query, output=answer, expected_output=expected)
return answer
def traced_run(copy_expected: bool, error_config: ErrorConfig) -> dict:
dataset = EvaluationDataset(goldens=[Golden(name=n, input=q, expected_output=e) for n, q, e in GOLDENS])
with contextlib.redirect_stdout(io.StringIO()): # DeepEval prints a panel even with print_results=False
for golden in dataset.evals_iterator(
metrics=[ExactMatchMetric()], async_config=AsyncConfig(run_async=False), error_config=error_config,
display_config=DisplayConfig(print_results=False, show_indicator=False, inspect_after_run=False)):
agent(golden.input, copy_expected)
return json.loads(Path(".deepeval/.latest_test_run.json").read_text())["testRunData"]
def gate_traced(run: dict, *, expected: int, metrics_per_case: int) -> list[str]:
"""Why a traced DeepEval run must NOT pass. Reads the run file, because the console and the
pass rate count neither errored spans (10B.5, 4.5) nor metrics that were skipped."""
cases = run.get("testCases") or []
if not cases:
return ["empty scan: no test cases in the run file"]
problems = [] if len(cases) == expected else [f"{len(cases)} cases, expected {expected}"]
for case in cases:
scored = [m for m in case.get("metricsData") or [] if m.get("score") is not None]
if len(scored) != metrics_per_case:
problems.append(f"{case['name']}: {len(scored)} scored metrics, expected {metrics_per_case}")
elif not case["success"]:
problems.append(f"{case['name']}: failed")
trace = case.get("trace") or {}
for kind in SPAN_LISTS:
for span in trace.get(kind) or []:
if span.get("status") == "ERRORED":
problems.append(f"{case['name']}: {kind[:-5]} span {span['name']!r} ERRORED")
return problems
def show(label: str, run: dict) -> None:
cases = run.get("testCases") or []
passed = sum(bool(c["success"]) for c in cases)
problems = gate_traced(run, expected=3, metrics_per_case=1)
print(f"{label}\n DeepEval: {passed} of {len(cases)} cases passed | "
f"gate -> {'PASS' if not problems else 'FAIL'} {problems}")
show("A. tool crash caught by a fallback", traced_run(copy_expected=True, error_config=ErrorConfig()))
show("B. same, golden expected_output not copied, skip_on_missing_params=True",
traced_run(copy_expected=False, error_config=ErrorConfig(skip_on_missing_params=True)))A. tool crash caught by a fallback
DeepEval: 3 of 3 cases passed | gate -> FAIL ["flaky: tool span 'lookup' ERRORED"]
B. same, golden expected_output not copied, skip_on_missing_params=True
DeepEval: 3 of 3 cases passed | gate -> FAIL ['known-1: 0 scored metrics, expected 1', 'known-2: 0 scored metrics, expected 1', 'flaky: 0 scored metrics, expected 1', "flaky: tool span 'lookup' ERRORED"]Read the two runs against DeepEval's own verdict, which is "3 of 3 passed" both times.
- A. The fallback answer for order A-3 happens to equal the expected one, so Exact Match passes and the golden passes. The only trace of the crash is the
ERROREDstatus of thelookupspan in the run file. Nothing on the console says a component failed; the gate finds it by walking every span list. - B. The agent forgot to copy the golden's
expected_outputinto the trace. WithoutErrorConfig, Exact Match would raiseMissingTestCaseParamsErrorand stop the run, which is loud and fine. Withskip_on_missing_params=True, a setting people add to quiet exactly that error, the metric is skipped on every case,metricsDatais empty, and the run file still records 3 passed, 0 failed. A pass rate over zero scored metrics is the silent denominator in its purest form. The gate counts scored metrics per case, so it fails all three.
Add both checks to any gate over traced runs: count scored metrics per case (not metrics declared), and fail on any span whose status is ERRORED. The checks read .deepeval/.latest_test_run.json, which a CI job should archive anyway (2.7).
4.8 When combining is the wrong move#
| Situation | Why not combine | Do this instead |
|---|---|---|
| A small app with one eval author and no agent | Two frameworks double the upgrade, dependency and vocabulary load for a gap you cannot name | Pick one; keep evalkit for statistics |
| You want both because you cannot decide | Day-one installs of both tend to produce two definitions of the same behaviour | Write the decision down, name the gap each would fill, add the second only for a named gap (10B.1, 8.1) |
| The combination needs five adapters | The seams are costing more than the gap | Re-write the missing metric in your framework of choice as a small custom metric or scorer |
| Different teams own the two frameworks | Seams across a team boundary rot | Share the plain check functions and a data folder, not wrappers |
| A regulated metric you must explain line by line | Built-in prompts sit between you and the number | Custom metrics or scorers in one framework, over your own checks |
Part 5: Migrating#
Deep-dive
Migration is where the abstract choice becomes a calendar. Three journeys are common: from evalkit (or a hand-rolled script) to one of the two, from DeepEval to Inspect, and from Inspect to DeepEval. The fourth, upgrading within a package, is the one you will do most often and is covered in 11.2. One method serves all of them, so it comes first.
5.1 From evalkit to a framework: the playbook#
flowchart TD
A["1. Freeze a baseline<br/>fake model, reference numbers,<br/>failing-case set"] --> B["2. Extract the checks<br/>plain functions, tested alone"]
B --> C["3. Put the data in an open file<br/>JSONL under git"]
C --> D["4. Write the thin wrapper<br/>metric or scorer"]
D --> E["5. Parity test<br/>same failing cases, same scores"]
E --> F{"Identical?"}
F -- "no" --> G["reconcile: data, then<br/>definition, then defaults"]
G --> E
F -- "yes" --> H["6. Switch the runner in CI,<br/>keep the old one as a canary"]
H --> I["7. Keep evalkit's statistics<br/>and judge calibration"]
I --> J["8. Retire what the framework<br/>really replaced"]- Freeze a baseline. Before you touch anything, record what the current harness says on a frozen fake: the headline numbers, the set of failing cases and the per-case scores. For triage this was 83.3%, 0.903 and T02 and T11 (10B.1, 7.1). Without a baseline a port can only be judged by taste.
- Extract the checks into plain functions (4.2). Most of a port is here, and it is framework-free, so it is also the part that survives a later change of framework.
- Put the data in an open file you control (5.2).
- Write the thin wrapper: a
BaseMetricsubclass for DeepEval, a@scorerfor Inspect. Store every constructor argument under its own name for DeepEval, make every Inspect solver and scorer functionasync def. - Parity test: same data, same fakes, compare the per-case verdicts (5.5). Cases first, aggregates second.
- Switch the runner in CI only when parity holds, and keep the old harness running as a canary for a release or two. If the two diverge, one of them is wrong and you want to know which.
- Keep
evalkit's statistics and judge calibration. Neither framework replaces them (2.6), and they run on the same per-case numbers. - Retire what was really replaced: the runner, the report printer, the ad hoc cache, the home-made concurrency. Do not retire the datasets, the checks or the calibration set.
What each evalkit piece becomes:
evalkit |
DeepEval | Inspect AI | Note |
|---|---|---|---|
Example, EvalDataset |
Goldens in an EvaluationDataset, or LLMTestCases |
Samples in a MemoryDataset or a loader |
Keep the JSONL; convert at the edge |
Scorer (code check) |
A BaseMetric wrapper, or a built-in non-LLM metric |
@scorer, or a built-in text scorer |
Plain function underneath |
rubric_judge |
Wrapped as a metric (4.5), or a GEval you validate |
A @scorer over the grader role, or model_graded_qa() with a custom template |
Re-validate if you swap prompts |
run_eval(...) |
evaluate() |
eval() |
The runner |
repeats= |
-r k (separate tests) |
epochs with a reducer |
Inspect's is the closer match |
CallCache |
-c (metric-result cache: stale-score risk) |
cache=True (model-call cache) |
Different things cached |
cli.py gate |
deepeval test run exit code |
A script over the log (4.7) | The gate logic stays yours |
compare.py, cluster.py |
Keep | Keep | Same per-case numbers |
judge_validation.py |
Keep | Keep | Neither framework has it |
agent_eval.py World |
Tracing plus tools_called |
Tools over a per-sample store or a sandbox | Inspect's is the closer match |
FakeTriageModel and kin |
FakeJudge |
mockllm/model |
Keyless tests survive the port |
5.2 Moving data: the dataset bridge, and a loader bug#
Datasets are where migrations leak. The robust move is to keep one open file and convert at the edges. This sample writes the triage tickets as evalkit-style JSONL (id, input, reference, metadata), converts them to DeepEval goldens and Inspect samples, saves the goldens with EvaluationDataset.save_as, and then loads DeepEval's own file back into Inspect.
# migrate_datasets.py: one evalkit-style JSONL dataset into DeepEval goldens and Inspect samples, and back (lesson 10B.17)
import json
import os
from pathlib import Path
from deepeval.dataset import EvaluationDataset, Golden
from inspect_ai.dataset import FieldSpec, Sample, json_dataset
from triage_data import TICKETS
work = Path("migrate"); work.mkdir(exist_ok=True)
# 1. The source of truth: plain JSONL in evalkit's shape (10A.2): id, input, reference, metadata.
src = work / "triage.jsonl"
src.write_text("\n".join(json.dumps({"id": tid, "input": text, "reference": ref, "metadata": meta})
for tid, text, ref, meta in TICKETS) + "\n")
rows = [json.loads(line) for line in src.read_text().splitlines()]
# 2. evalkit rows -> DeepEval goldens (an input and what you expect; no actual_output: your app produces it later)
goldens = [Golden(name=r["id"], input=r["input"], expected_output=r["reference"], additional_metadata=r["metadata"])
for r in rows]
dataset = EvaluationDataset(goldens=goldens)
print("DeepEval goldens:", len(dataset.goldens), "| first:", dataset.goldens[0].name, dataset.goldens[0].expected_output)
# 3. evalkit rows -> Inspect samples (id, input, target, metadata): the field names differ, the content does not
samples = [Sample(id=r["id"], input=r["input"], target=r["reference"], metadata=r["metadata"]) for r in rows]
print("Inspect samples :", len(samples), "| first:", samples[0].id, samples[0].target)
# 4. DeepEval's own file -> Inspect, through a FieldSpec: DeepEval saves JSON, Inspect reads it by field name
saved = dataset.save_as(file_type="json", directory=str(work), file_name="goldens")
print("DeepEval wrote:", Path(saved).name if saved else None)
raw = json.loads(Path(saved).read_text())
print("keys in a saved golden:", sorted(raw[0]))
try:
json_dataset(str(saved), FieldSpec(input="input", target="expected_output", id="name",
metadata=["additional_metadata"]))
except ValueError as e: # the empty ticket T10 has input "": FieldSpec refuses it
print("FieldSpec load failed:", e)
def record_to_sample(rec: dict) -> Sample: # a function mapping has no such check: it may keep an empty input
return Sample(id=rec["name"], input=rec["input"], target=rec["expected_output"],
metadata=rec["additional_metadata"])
back = json_dataset(str(saved), record_to_sample)
print("record_to_sample load:", len(back), "samples | ids equal:", [s.id for s in back] == [r["id"] for r in rows],
"| metadata equal:", all(b.metadata == r["metadata"] for b, r in zip(back, rows)),
"| T10 input kept empty:", repr(next(s for s in back if s.id == "T10").input))DeepEval goldens: 12 | first: T01 P2|billing
Inspect samples : 12 | first: T01 P2|billing
Evaluation dataset saved at migrate/goldens.json!
DeepEval wrote: goldens.json
keys in a saved golden: ['actual_output', 'additional_metadata', 'comments', 'context', 'custom_column_key_values', 'expectations', 'expected_output', 'expected_tools', 'input', 'input_token_count', 'name', 'output_token_count', 'retrieval_context', 'source_file', 'token_cost', 'tools_called']
FieldSpec load failed: No input in dataset
record_to_sample load: 12 samples | ids equal: True | metadata equal: True | T10 input kept empty: ''What this shows, in order:
- The two conversions are one line each because the shapes are close:
referencebecomesexpected_outputortarget,metadatabecomesadditional_metadata(on aGolden) ormetadata. - DeepEval's saved golden is wide: sixteen keys, including
actual_output,tools_called,token_costandexpectations, most of them empty for a golden. A converter must pick the ones it needs. - A bug in the loader path, found while writing this lesson. Loading that file with
json_dataset(path, FieldSpec(...))failed withNo input in dataset, because ticket T10 has an emptyinput(the "empty ticket" case: the model should cope with an empty message). Inspect's declarative loaders refuse an empty input string: aFieldSpecand the default column mapping (json_dataset(path)with no spec, andcsv_dataset) fail the same way, because the check lives in the sharedread_input()helper (if ... not input: raise ValueError("No input in dataset")). ASample(input="")built in code is accepted, and a function mapping (record_to_sample) keeps it. The next sample runs all five paths.
# empty_input_loaders.py: which Inspect dataset paths accept an empty input string (lesson 10B.17, 5.2)
import json
import tempfile
from importlib.metadata import version
from pathlib import Path
from inspect_ai.dataset import FieldSpec, Sample, csv_dataset, json_dataset
print("inspect-ai", version("inspect-ai"))
work = Path(tempfile.mkdtemp())
rec = {"id": "T10", "input": "", "target": "P3|other"}
(work / "t.jsonl").write_text(json.dumps(rec) + "\n")
(work / "t.csv").write_text("id,input,target\nT10,,P3|other\n")
def record_to_sample(r: dict) -> Sample:
return Sample(id=r["id"], input=r["input"], target=r["target"])
def attempt(label, load):
try:
print(f"{label:<34} loaded {len(load())} sample(s)")
except ValueError as e:
print(f"{label:<34} ValueError: {e}")
attempt("Sample(input='') in code", lambda: [Sample(input="")])
attempt("json_dataset, default mapping", lambda: json_dataset(str(work / "t.jsonl")))
attempt("json_dataset, FieldSpec", lambda: json_dataset(str(work / "t.jsonl"), FieldSpec(input="input", target="target", id="id")))
attempt("csv_dataset, default mapping", lambda: csv_dataset(str(work / "t.csv")))
attempt("json_dataset, record_to_sample", lambda: json_dataset(str(work / "t.jsonl"), record_to_sample))inspect-ai 0.3.292
Sample(input='') in code loaded 1 sample(s)
json_dataset, default mapping ValueError: No input in dataset
json_dataset, FieldSpec ValueError: No input in dataset
csv_dataset, default mapping ValueError: No input in dataset
json_dataset, record_to_sample loaded 1 sample(s)So No input in dataset does not only mean a missing input column; it also means a present but empty one. The silent alternative would be worse: a loader that dropped the row. So the migration rule is count the rows on both sides (12 in, 12 out) and keep edge cases in the data on purpose. 10B.9, Part 3 covers FieldSpec and record_to_sample in full (read its notes on empty inputs together with this section: where they differ, the result printed above wins).
- The field names are the migration:
additional_metadataon aGoldenandmetadataon a test case (the older alias on test cases raises aDeprecationWarningthat default filters hide),expected_outputversustarget,nameversusid. Write them in a table in your repository, because they are exactly what a tired engineer gets wrong on a Friday.
5.3 From DeepEval to Inspect#
People make this move when the unit under test stops being a finished record: the app becomes an agent with tools, the team wants the same recipe over several models, or they want transcripts and sandboxes. The mapping:
| DeepEval | Inspect AI | What changes |
|---|---|---|
| Your app, run by your code | A solver (generate(), a custom @solver, react()) |
The app, or the part under test, becomes something Inspect can call |
LLMTestCase |
Sample plus the run's state |
actual_output is no longer an input; it is produced |
Golden, EvaluationDataset |
Samples, MemoryDataset, a loader |
Convert with 5.2 |
BaseMetric |
@scorer plus metrics=[...] |
One object per case becomes one function per sample and a separate aggregate |
Threshold and success |
Nothing by default | Write the gate over the log (4.7) |
GEval |
model_graded_qa() with a custom template, or your own judge scorer |
Different prompt, different scale (0 to 10 normalized versus GRADE: letters). Recalibrate |
| QAG metrics (Faithfulness, Answer Relevancy, Contextual Recall) | No built-in equivalent | Write a scorer, or call the DeepEval metric from a scorer (4.3) |
ToolCorrectnessMetric, agent metrics |
A scorer over state.messages, events and the final state |
Usually more precise, and more code |
evaluate() |
eval() |
The runner |
assert_test() and deepeval test run |
inspect eval-set plus a gate script |
No pytest integration; see 2.8 |
-r k repeats |
epochs=k with a reducer |
Per-sample reduction before the metric; carry the metric threshold over as value= on pass_at/pass_k, or pass@k changes meaning (2.5) |
@observe traces |
The log (always) | No instrumentation needed for what Inspect ran |
ConversationSimulator |
A solver or agent that plays the user | Rebuild, then validate (10B.6, Part 8) |
deepeval.red_team |
Keep it in DeepEval (or an audit tool such as Petri) | No built-in equivalent |
| Confident AI | Nothing | Logs plus your own dashboards or third-party platforms |
Expect the numbers to move. A DeepEval faithfulness score and an Inspect grounded check use different prompts, call patterns and scales, so a port will not reproduce the old number, and that is not a bug. What a port should reproduce is the failing-case set on a frozen fake for every deterministic check (5.5), and, for judged checks, an agreement figure against human labels. If you keep DeepEval's metrics for the parts that are genuinely better there (RAG metrics, red teaming) and move only the agent and benchmark work, you are not migrating but dividing ownership (Part 9).
5.4 From Inspect to DeepEval#
Less common, usually driven by CI. The product team wants pytest, thresholds and a RAG metric catalogue, and the evals are single-turn.
| Inspect AI | DeepEval | What changes |
|---|---|---|
| A task's solver | Your app, behind an adapter function | You run the app; DeepEval scores what it did |
Sample |
LLMTestCase or Golden |
actual_output filled by your app |
@scorer |
BaseMetric subclass |
Store constructor arguments under their own names |
accuracy(), mean(), stderr() |
A pass rate and per-metric means you compute | Uncertainty disappears unless you add it (2.6) |
epochs, pass_at(k) |
-r k or your own loop |
Reducers are yours, and the success threshold moves from the reducer's value= to the metric's threshold (2.5) |
Model roles (grader) |
The model= argument of each metric |
One judge per metric |
| Sandboxes, limits, approval | None | Not portable; keep these evals in Inspect |
The .eval log |
.deepeval/ run files, tracing |
Far less recorded unless you trace |
inspect eval-set |
deepeval test run |
Different exit semantics |
The honest warning: if the Inspect evals use tools, sandboxes or budgets, moving them to DeepEval means evaluating a description of the agent, not the agent. The case to move is the single-turn model-graded task whose only reason for being in Inspect was that it was there first.
5.5 The parity protocol#
Any port, in any direction, is judged by the same protocol. 3.1 is the worked example.
- Same data: the same rows, counted on both sides, with edge cases intact (the empty ticket!).
- Same fakes: a scripted model (and judge) that returns fixed answers, so any difference is the harness.
- Cases before aggregates: the set of failing case ids must be identical, then per-case scores, then headline numbers. Print the failing-set diff (cases that fail only in the new harness, and cases that fail only in the old one) before any aggregate: in 10B.1, 7.4 a port that built its test cases without
metadatascored 9 of 12 against 10 of 12, which looks like noise, and the diff named the one new failure, the empty ticket T10, whose expected behaviour lives in its metadata. - Classify each difference with this table, and do not average it away.
| Difference you see | Usually means | Action |
|---|---|---|
| A different set of failing cases | Data, a wrapper bug or a different check | Fix the wrapper; the checks are plain functions, so test them alone |
| Same cases, different headline | Different definitions of the headline (pass rate versus per-scorer mean) | Name each number; compute both from per-case scores |
| Same deterministic scores, different judged scores | Different judge prompts, scales or judge models | Not a bug. Validate the new judge (10A.5) and re-baseline |
| Different case counts | A loader dropped or refused rows, or a metric skipped cases | Count on both sides; read skip_on_missing_params and unscored counts; in a traced DeepEval run, count scored metrics per case, not cases (4.7) |
| One or two extra failures that share a property (the empty ticket, fenced JSON, a score exactly at the threshold) | A field lost in the port, a different parser, or >= against > |
Print one converted case from each side; work down the suspects table of 10B.1, 7.4 |
| Scores differ between two runs of the same framework | Judge noise, cache, async step regeneration, an unseeded bootstrap | Repeat; read 10B.2, 4.5, 10B.11, Part 8 |
- Keep the parity test: the frozen fake and the reference numbers become a permanent smoke test in CI (10B.1, 12.5). It catches the next upgrade's silent change too.
5.6 An exit plan you actually test#
Both packages are open source and neither will vanish from your lock file, but the cost of leaving is decided early. Five habits make it a port and not a rewrite:
- Datasets live as JSONL in git, not only in a framework's store.
- Checks are plain functions, with wrappers that are disposable.
- Prompts and rubrics are files with versions (10A.4, 3.5).
- Run records are artefacts: DeepEval run files and Inspect logs archived with their versions (6.5).
- Statistics and calibration are yours and run on per-case numbers.
Then test it. Once a quarter, port one small eval to the other framework (or to evalkit) on a frozen fake and time it. If the port takes an afternoon, the exit plan is real. If it takes a week, find out why now.
Part 6: Patterns#
Deep-dive
Everything so far gives you pieces. These are the shapes that keep them from drifting apart when a repository holds two frameworks, a dozen evals and a team that changes every year. Each is a habit that earlier lessons paid for in a failure.
6.1 The default shape: checks, adapters, runners, data#
evals/
data/ # JSONL under git, with a dataset card (the only copy of the cases)
triage.jsonl
docsqa.jsonl
checks/ # plain functions: no framework imports, tested with pytest alone
triage_checks.py # check_format, check_labels
docsqa_checks.py
rubrics.py # evalkit Rubric objects, versioned
adapters/ # thin wrappers: the only files that import a framework
deepeval_metrics.py # BaseMetric wrappers over checks/
inspect_scorers.py # @scorer wrappers over checks/
suites/
smoke/ # keyless: FakeJudge, mockllm, oracle and null controls, every pull request
judged/ # real judges, nightly or on a prompt change
studies/ # model comparisons, agents, benchmarks: Inspect, on demand
gates/
combined_gate.py # fail-closed over run files and logs
records/ # run records, archived DeepEval run files and Inspect logs (not committed)The layout is not special. It is the one that makes Part 5 cheap: replacing a framework replaces adapters/ and part of suites/, never data/ or checks/.
6.2 One owner for every question#
When two frameworks coexist, the failure is two answers to one question. Decide which framework owns what, and write it in the repository's README so that new code has an obvious home.
| Question | Owner | Why |
|---|---|---|
| Does a pull request break a product behaviour? | DeepEval (smoke tier) or Inspect scripts, one of them | The exit code of one tool is the verdict |
| Is a RAG answer grounded? | DeepEval's metrics (or your own check) | Ready-made, with readable prompts |
| Did the agent act correctly in a controlled world? | Inspect | It runs the loop and holds the world |
| Is v2 better than v1? | evalkit statistics, over either framework's per-case numbers |
Neither framework has the test |
| Can we trust the judge? | evalkit's calibration, on a held-out labelled set |
Neither framework has it |
| Which model should we use? | Inspect, with pinned model versions | One recipe, many models, logs |
| Can the app be attacked? | DeepEval's deepeval.red_team (frozen slice in the smoke tier, fresh runs on a schedule), with Module 12 owning the depth |
Purpose-built |
The test of a good division is that any engineer can answer "where would I add a check for X?" in one sentence.
6.3 Tiers: smoke, judged, studies#
| Tier | Runs | Judge or model | Gate | Cost |
|---|---|---|---|---|
| Smoke | Every pull request | Deterministic checks, FakeJudge, mockllm/model, oracle and null controls |
Hard: exit code and the combined gate | Seconds, free |
| Judged | Nightly, or when a prompt, model or rubric changes | Real judges (calibrated), real models | Soft first (a report and a paired comparison), hard only on stable metrics | Real money: count calls first |
| Studies | On demand | Several models, epochs, agents, sandboxes, benchmarks | None: a report with intervals | Real money and time |
The smoke tier is what keeps the harness honest between real runs: it proves the plumbing, the wrappers and the gate with no key, and it is what catches an upgrade that changed behaviour (10A.8, 8.4). The judged tier is where judge validation pays off. The studies tier is where Inspect earns its keep. Do not gate a pull request on a tier-two metric until you have measured its noise.
6.4 Oracle and null controls, in every suite#
Every eval gets two controls that run in the smoke tier (10B.8, 10.2, 10B.2, 10.2). An oracle (answers built from the references) must score near the maximum, and a null (an unrelated answer) near the minimum. The support agent of 3.3 ran an oracle (everything 1.0) and a careless agent (0.667 and 0.167) for exactly this reason. A null that scores well (an empty target makes includes() pass everything) tells you the eval cannot tell right from wrong before you have spent a dollar on it. Both controls are tiny and work in both frameworks.
6.5 A run record: the fingerprint of a number#
A number you cannot reproduce is an anecdote. Every result that leaves the team (a report, a release note, a dashboard) carries the small record that produced it. This sample builds one from the two frameworks' triage runs.
# run_record_both.py: the fingerprint of a number: versions, data hash, definitions, and the named headline (lesson 10B.17)
import contextlib, hashlib, io, json, platform
from importlib import metadata
import triage_deepeval_side as de
import triage_inspect_side as ins
from triage_data import TICKETS
CHECKS_VERSION = "triage_checks@1" # bump when a check's definition changes
with contextlib.redirect_stdout(io.StringIO()):
per_case = de.run()
log = ins.run()["log"]
data_hash = hashlib.sha256(json.dumps(TICKETS, sort_keys=True).encode()).hexdigest()[:12]
record = {
"python": platform.python_version(),
"packages": {n: metadata.version(n) for n in ("deepeval", "inspect-ai")},
"checks": CHECKS_VERSION,
"dataset": {"name": "triage-12", "rows": len(TICKETS), "sha256_12": data_hash},
"judge": "none (deterministic checks only)",
"numbers": {
"deepeval case pass rate": f"{sum(v['success'] for v in per_case.values())}/{len(per_case)} cases passed every metric",
"inspect triage_labels": f"mean of the 3-part label score over {log.results.scores[1].scored_samples} scored of "
f"{log.results.total_samples} samples",
},
"inspect": {"task_version": log.eval.task_version, "status": log.status,
"git_origin_recorded": bool(log.eval.revision and log.eval.revision.origin)},
}
print(json.dumps(record, indent=2)){
"python": "3.13.14",
"packages": {
"deepeval": "4.3.6",
"inspect-ai": "0.3.292"
},
"checks": "triage_checks@1",
"dataset": {
"name": "triage-12",
"rows": 12,
"sha256_12": "69e150eeb155"
},
"judge": "none (deterministic checks only)",
"numbers": {
"deepeval case pass rate": "10/12 cases passed every metric",
"inspect triage_labels": "mean of the 3-part label score over 12 scored of 12 samples"
},
"inspect": {
"task_version": 0,
"status": "success",
"git_origin_recorded": true
}
}Five things belong in every record, and this one has all five: the Python and package versions (a score belongs to a version, 2.10); the version of the checks (triage_checks@1); the dataset identity (name, row count and a hash, so a silent edit shows); the judge identity (here none, because the checks are deterministic; for a real judge, the model's dated snapshot, its settings and the rubric version); and the named number, with its denominator. The record also shows two things to fix: Inspect's task_version is 0 because the task never set one (set version= and bump it when the task changes, 10B.10, 8.3), and the log recorded a git origin (a placeholder here, so harmless; in a real repository it is a privacy decision, 10B.13, 7.5).
6.6 Validate each judge once, where it runs#
A judge is validated against human labels on a held-out calibration set (10A.5): agreement, true-positive and true-negative rates, with intervals and a number of labels you can defend. The set belongs to the rubric, not to the framework. When one evalkit rubric runs in both frameworks (4.5), one calibration covers both. When you use DeepEval's built-in metrics and Inspect's model_graded_fact() as separate judges, each needs its own calibration against the same labels, and the two will not agree with each other. Re-validate after any change that could move the judge: its model, its prompt, the framework version (10B.11, 10.7), or the metric's configuration (penalize_ambiguous_claims, strict mode, a rubric).
6.7 Bound everything#
| Thing | Bound it with | Both frameworks? |
|---|---|---|
| Spend | A budget on the key, a count of judge calls per suite from a scripted run | Yes |
| Concurrency | AsyncConfig(max_concurrent=...); max_connections, max_samples |
One each |
| Time | A job timeout; timeout and attempt_timeout in Inspect |
Yes |
| A runaway agent | Message, token, time and cost limits in Inspect; your own bound in the stub you hand DeepEval | Inspect has it built in |
| Retries | One owner: the framework's, not also yours | Yes (08F.15, 1.6 makes the same point for agents) |
| Cache lifetime | No cache in gates; versioned names when caching | Yes |
6.8 Upgrades are measured changes#
Both packages release every few days. Treat each upgrade as a change to a measuring instrument: bump one package, run the frozen smoke suite on the old and new versions, diff the per-case verdicts, read the changelog for the number-moving entries (11.2 lists the ones of 2026), re-validate judges, and only then re-baseline. A version bump that changes nothing on the frozen fakes is good news; one that changes a verdict is a finding to read.
6.9 Report the definition with the number#
"Faithfulness 0.82" is not a result. A result names its instrument. This is the paragraph template that follows from everything above, written out as an example (not run; the numbers are invented to show the shape):
Faithfulness (DeepEval 4.3.6, FaithfulnessMetric, penalize_ambiguous_claims=True,
judge: <model snapshot>, threshold 0.7) is 0.82 on 120 docs_qa cases (dataset docsqa@4, sha 3f9a...).
118 of 120 cases were scored (2 judge errors, listed). The judge agrees with 3 reviewers' labels on
60 cases: kappa 0.71 (interval 0.52 to 0.85). The paired difference from the previous release,
same cases, is +0.03 (95% interval -0.02 to +0.08): not a detectable change.Every clause answers a question a reader would ask.
6.10 A secure, private default#
Opt out of telemetry (DEEPEVAL_TELEMETRY_OPT_OUT=1, and DEEPTEAM_TELEMETRY_OPT_OUT=YES if the legacy package is installed) in .env and in CI. Keep CONFIDENT_API_KEY out of pull-request jobs. Scrub Inspect logs before sharing them (they hold the git remote). Never run deepeval view, deepeval login or deepeval gate in a keyless pipeline (10B.2, 7.5). Treat model-readable text in agent evaluations (tool output, files) as untrusted input to your grader (10B.11, Part 7).
Part 7: Anti-patterns#
Deep-dive
Each anti-pattern has a symptom you will see, a cause, and a fix. They are the ones that appeared repeatedly in the reviews of 10B.2 to 10B.16.
7.1 Two frameworks, two definitions#
Symptom. The DeepEval dashboard says the support bot is at 0.91 and the Inspect report says 0.84, and an hour of the weekly meeting goes to arguing about which is right.
Cause. The same behaviour (valid JSON, grounded, polite) is defined twice, once in each framework, and the definitions drifted.
Fix. One definition in a plain function, two wrappers (4.2). If a framework's built-in metric and your own check both measure "grounded", pick one as the gate and treat the other as a diagnostic, in writing.
7.2 Comparing numbers across frameworks#
Symptom. "Our faithfulness dropped from 0.9 (Ragas) to 0.8 (DeepEval) after the migration."
Cause. The same word means different things. The reconciliation table of 10B.1, 4.2 is the cure, and three cases recur:
| Name | One meaning | Another meaning |
|---|---|---|
| "Faithfulness" | DeepEval: fraction of claims not contradicted by the retrieved text by default (unsupported claims fail only with penalize_ambiguous_claims=True) |
Ragas: a different decomposition and prompts; never compare across libraries (10B.4, 2.10) |
| "Metric" | DeepEval: an object scoring one case | Inspect: a function aggregating many scores |
| "Accuracy" | Inspect: mean of per-sample verdicts after reducers, over scored samples | A pass rate you computed: share of cases where every check passed |
Fix. Compare numbers only within one instrument, one version and one judge. Across instruments, compare cases and definitions, never headlines (5.5).
7.3 Judging the framework by its defaults#
Symptom. "Inspect's grader passes everything." / "DeepEval's Toxicity never fails."
Cause. The default of each is a trap: Inspect's model_graded_fact() with no model= and no bound grader role silently uses the model under test as its own judge (10B.11, 5.2); DeepEval's safety metrics have a default threshold of 0.5, which passes half-bad outputs (10B.4, 4.7).
Fix. Never evaluate a framework by running its defaults once. Configure the judge, the threshold and the strictness on purpose, then compare.
7.4 Framework types in your domain#
Symptom. LLMTestCase and inspect_ai.Sample objects appear in your application's modules, in your database rows and in your API responses.
Cause. Convenient early on; costly at the first migration or the first breaking release (Inspect is 0.x, DeepEval renamed LLMTestCaseParams and additional_metadata).
Fix. Convert at the boundary (6.1). The same advice as 08F.15, 2.6 for LangChain types, for the same reason.
7.5 A green CI that checks nothing#
Symptom. A regression ships; CI had been green for weeks; the job log shows no evaluation.
Cause. The ways a gate quietly checks nothing are specific and listed: || true; exit code 5 swallowed; inspect eval exiting 0 on error status; errors tolerated so a perfect score covers a shrunken denominator; -n losing cases; a gate that scans an empty or wrong file.
Fix. A fail-closed gate that reports reasons (4.7), a count of cases and of scored cases in every report, and a deliberately broken case in the smoke tier that must turn the job red. Test your gate the way you test a smoke detector.
7.6 Averaging a hard rule#
Symptom. "Policy compliance 0.93", while one refusal rule fails in every conversation.
Cause. A rule that must always hold is averaged into a mean score, or into a threshold of 0.5.
Fix. Split the floor (a hard rule: a strict-mode metric, a deterministic check, a policy scorer, reported as a count of violations) from the quality score (a mean). Gate on the floor.
7.7 Scoring a description of the agent#
Symptom. The agent eval is green and the agent in production sends the wrong emails.
Cause. The agent was not run in a controlled world: the eval scored its final text or a recorded trace, not what happened to the world.
Fix. Read the world's final state for outcome and the events for process (10B.16, Parts 2 and 3); Inspect makes this natural, and a DeepEval version needs the state captured as in 3.3.
7.8 Adopting for the dashboard#
Symptom. The team chose a framework because of a demo of its viewer, then discovered that the number on the dashboard was not defined the way they assumed.
Cause. A platform sells visibility. The measurement is the checks, the judge and the data.
Fix. Choose on the questions in 1.2. The dashboard is a view: nice to have, and never the reason (10A.10, 1.2).
7.9 An uncalibrated judge as the gate#
Symptom. A threshold on a judged metric was chosen by eyeballing three examples, and it flaps between 0.7 and 0.9 between identical runs.
Cause. No calibration against labels, no noise measurement, a default judge.
Fix. Measure the judge (10A.5) and its noise by re-grading the same outputs (10B.11, 8.2); gate on a deterministic metric first, and promote a judged metric to a gate only when its noise is smaller than the effect you want to detect.
7.10 Copying a tutorial without dating it#
Symptom. ImportError, a TypeError on a documented argument, a threshold that now means the opposite.
Cause. Both packages move fast, and the docs trail the code (10B.3, 13.2).
Fix. Date every snippet by the version it ran on, run it on a frozen fake before trusting it, and use Part 11 as a decoder.
7.11 The catalogue#
| Anti-pattern | Symptom you see | First check |
|---|---|---|
| Two definitions | Two dashboards disagree | Diff the per-case verdicts |
| Cross-framework headlines | A "regression" after a migration | Compare cases, then definitions |
| Default-judge trust | A grader that passes everything | Which model graded? (metadata["grading"], the role) |
| Framework types in the domain | A migration touches every module | Grep for framework imports outside adapters/ |
| Green but empty CI | A regression ships under a green job | Cases collected and scored, per report |
| Averaged hard rule | Mean 0.93, one rule always broken | Violation count per rule |
| Description-scoring | Green agent eval, wrong production behaviour | What world state did the scorer read? |
| Dashboard-driven adoption | Surprise at a number's definition | The metric's prompt and formula |
| Uncalibrated gate | A threshold that flaps | Judge noise and agreement |
| Undated tutorial | ImportError, inverted thresholds |
The version the snippet ran on |
Part 8: The pitfalls checklist for 10B.2 to 10B.16#
Reference
Fifteen lessons (10B.2 to 10B.16) reproduced surprises. This part collects them in one place, grouped by where they strike, each with its fix and the section that reproduced it. Each row is a surprise that costs a team a day the first time: most fail silently and produce a plausible wrong number. Rows marked (new) were found while writing this lesson. The checklist was brought up to date on 28 November 2026 with the findings of the later quality passes on 10B.1, 10B.5, 10B.6, 10B.15 and 10B.16 (errored spans that pass, golden fields that never reach a traced test case, the HumanEval and TruthfulQA scorers, approval that fails closed while review fails open, the success threshold of pass_at, budget curves), so the rows are renumbered from earlier copies. Read the table once now and keep it open the first week you use either package; 8.9 runs a scanner for the rows a regular expression can catch.
The marks: DE is DeepEval, IN is Inspect, both applies to either. Each section reference is lesson, section.
8.1 Setup, install and environment#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 1 | DE. LLM metrics fail at construction without a key, including the deterministic ToolCorrectnessMetric and JsonCorrectnessMetric |
Pass model= (a FakeJudge in keyless runs) |
10B.2, 3.4 |
| 2 | DE. import deepeval loads .env, .env.<APP_ENV> (only when APP_ENV is set, in the shell or inside .env.local or .env) and .env.local from the current folder only (parent folders are not searched; ENV_DIR_PATH names another); later files win, the shell beats them all |
deepeval diagnose; DEEPEVAL_DISABLE_DOTENV=1 in CI; set the judge in code |
10B.2, 1.6, 10B.1, 5.3 |
| 3 | DE. set-* and login write keys in plain text to .env.local; set-ollama without --save mis-routes |
Do not run them in shared folders; --save=dotenv |
10B.2, 7.3, 10B.3, 2.6 |
| 4 | DE. A USE_* flag from an old set-* command makes a provider string select the wrong provider |
Pass wrapper instances; deepeval diagnose |
10B.3, 2.1 |
| 5 | DE. Telemetry (PostHog) is on unless DEEPEVAL_TELEMETRY_OPT_OUT=1; the legacy deepteam package has its own switch |
Set both in .env and CI |
10B.2, 1.5, 10B.7, 5.5 |
| 6 | DE. The pytest plugin loads in every pytest session in the environment | Separate environments, or -p no:deepeval |
10B.2, 5.6 |
| 7 | DE. deepeval view and deepeval gate need a Confident AI key (view opens a sign-up page) |
Never run them in a keyless pipeline | 10B.2, 7.5, 10B.7, 5.2 |
| 8 | IN. --model openai/... fails at once: the provider SDK is not installed (inspect-ai does not include it) |
uv add openai (or the provider's SDK) |
10B.8, Part 9 |
| 9 | IN. samples_df() needs pandas and pyarrow, which are not dependencies |
uv add pandas pyarrow |
10B.8, Part 9 |
| 10 | IN. An exported variable beats a new key in .env; INSPECT_EVAL_* variables configure the CLI, not Python eval() (except INSPECT_EVAL_MODEL) |
unset, or pass settings to eval() |
10B.12, 2.8, 10B.8, 5.5 |
| 11 | IN. Both GOOGLE_API_KEY and GEMINI_API_KEY set: Inspect prefers GOOGLE_API_KEY |
Keep one Google key | 10B.8, Part 9 |
| 12 | IN. ./logs is relative to where you ran; "where did my logs go?" |
INSPECT_LOG_DIR or --log-dir |
10B.8, 6.1 |
| 13 | IN. Logs record the git remote, commit and dirty flag; a shared bundle exposed a private URL | Scrub a copy and verify by search; use a placeholder remote in labs | 10B.13, 7.5 |
| 14 | IN. inspect loads task files from their own folder, so a helper that imports in Python fails from the CLI |
Install shared code as a package or set PYTHONPATH |
10B.12, 11.7 |
| 15 | both. python -I drops the script's folder from sys.path, so multi-file samples fail |
Use python -s (or add the folder to the path) |
the track note of this lesson's Setup |
| 16 | IN. Inspect 0.3.281 (15 October 2026) raised the Python floor to 3.11 | uv python pin 3.13; check CI images |
10B.1, 2.5 |
| 17 | both. uv run --no-project --with <package> run inside a project silently reuses the project's .venv when it already satisfies the request, so a "does this sample need X?" check proves only that the project has X |
uv run --isolated --no-project --with ... for any clean-room check |
10B.1, 3.1 |
| 18 | IN. An Inspect Evals task with an optional extra (swe_bench()) raises AssertionError before any model call when the extra is missing |
uv add "inspect-evals[swe_bench]"; run inspect list tasks first |
10B.16, 9.4 |
8.2 Data and test cases#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 19 | IN. An empty target (the default) makes includes() and match() pass everything |
Validate targets at load time; run the null control | 10B.9, 2.2 |
| 20 | IN. Template solvers mangle single braces and pass unknown placeholders through silently | Double the braces; test the rendered prompt | 10B.8, 9.2, 10B.9, 6.5 |
| 21 | IN. csv_dataset names the dataset after the last column header in 0.3.292 (an explicit name= is ignored) |
Name it with .filter(lambda s: True, name=...) |
10B.9, 3.2 |
| 22 | IN. limit counts samples after one-to-many conversion |
Filter by parent id | 10B.9, 3.6 |
| 23 | IN. Run-time positional ids plus a shuffle make "sample 7 regressed" a different question | Explicit ids or auto_id=True |
10B.9, 2.4 |
| 24 | IN. (new) Inspect's declarative loaders (FieldSpec or the default column mapping, for CSV, JSON and Hugging Face) refuse an empty input (No input in dataset); a Sample(input="") built in code and a record_to_sample function keep it |
Use a function mapping; count rows on both sides | 5.2 |
| 25 | both. A port that drops one field (test cases built without their metadata) still passes almost everything: only the empty ticket T10 flips, and 9 of 12 against 10 of 12 looks like noise |
Diff the failing sets (new and missing failures) before comparing any aggregate | 10B.1, 7.4 |
| 26 | IN. A SampleSource that grows while the task runs lets the run choose the denominator |
Report the designed quantity | 10B.9, 3.10 |
| 27 | IN. Joining two logs by position, or by sample_id, gives nonsense; epochs multiply rows |
Join on (id, epoch); reduce per id |
10B.8, 7.3, 10B.13, 8.3 |
| 28 | DE. retrieval_context (what retrieval returned) is not context (golden facts): Hallucination reads context |
Use the field each metric reads | 10B.2, 2.4, 10B.4, 2.7 |
| 29 | DE. tags do not come back on TestResult; test_results order is not guaranteed |
Slice by metadata; sort by index |
10B.2, 2.2, 4.3 |
| 30 | DE. EvaluationDataset(test_cases=...) is a TypeError: the constructor takes goldens; mixing single-turn and multi-turn goldens is a TypeError |
Build goldens; one kind per dataset | 10B.6, 1.5 |
| 31 | DE. "Filtration" in the synthesizer keeps rewritten inputs; a generator and judge from one model family inflate scores | Write the filter yourself; use different families | 10B.6, 3.3, 6.1 |
| 32 | DE. Synthetic inputs are short and abbreviated by design (a 15-word cap and "Use abbreviation wherever possible" in every evolution template), and conversational goldens generated from scratch never get an expected_outcome, so their simulations run to the turn cap |
Read the length distribution before use; write expected_outcome yourself |
10B.6, 3.4, 2.3 |
| 33 | DE. tiktoken downloads its data on first use, which fails offline |
Pre-fetch in the image | 10B.6, 5.4 |
| 34 | DE. When the generator model returns more inputs than asked, the sync synthesizer crashes with IndexError and the async one silently truncates |
Count generated against requested goldens | 10B.6, 5.5 |
| 35 | DE. Benchmarks: a sentence where a letter is expected scores near zero; EquityMedQA scores inverted in 4.3.5 | Read the prediction format; treat judge-scored benchmarks with care | 10B.6, 9.4, 9.7 |
| 36 | DE. HumanEval never calls the problem's check() tests (any function that compiles passes), its overall score counts a problem as solved when any of n = 200 samples passed (close to pass@200 whatever k), and secure_exec has no timeout and is not a sandbox; all still present in 4.3.6 |
Do not report its overall score; run the reference harness in an isolated container, or use inspect_evals/humaneval |
10B.6, 9.6 |
| 37 | DE. TruthfulQA MC2 scores the share of true options a prediction lists (listing every option scores 100) and adds the percentages on a 0 to 100 scale, but counts any overlap as 1 when batch_size is set; DROP is normalized exact match with no F1; GSM8K has no number extraction |
Recompute from benchmark.predictions; never compare across batch settings or with published numbers |
10B.6, 9.5 |
8.3 Judges and model-graded scoring#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 38 | IN. model_graded_fact() with no model= and no bound grader role grades with the model under test |
Bind --model-role grader=...; assert the role is set |
10B.11, 5.2, 10B.12, 2.3 |
| 39 | IN. The last GRADE: line wins; a custom pattern that takes the first match, or custom instructions that backtrack, let a wrong answer pass |
Keep default instructions, or test the pattern | 10B.11, 4.4 |
| 40 | IN. A tied panel is unscored; reducer="mode" breaks ties by list order |
Odd panels; report unscored | 10B.11, 6.2 |
| 41 | IN. A grader that never writes GRADE: (or truncates) leaves samples unscored, so accuracy rises as the grader gets worse |
Report scored and unscored | 10B.11, 3.4 |
| 42 | IN. The default templates hold a nonce, so the grader cache never hits | Accept it, or write a stable template | 10B.11, 8.3 |
| 43 | IN. Template traps: literal braces, a missing metadata key (KeyError), a list target concatenated into {criterion} |
Test every template | 10B.11, 4.5 |
| 44 | IN. inspect score with no --action / --overwrite / --output-file prompts and hangs in CI |
Always pass them | 10B.11, 11.2 |
| 45 | DE. token cost: None is normal for custom judges; only priced built-in wrappers are tracked |
Log usage inside your judge | 10B.2, 3.4 |
| 46 | DE. An invalid-JSON judge reply aborts; a TypeError inside generate(prompt, schema) silently triggers a retry that doubles the calls |
Unit-test generate(); count calls |
10B.3, 3.2, 3.3 |
| 47 | DE. G-Eval with criteria only regenerates steps per case in the default runners (2.4 measured it): scores differ between cases and runs |
Fixed evaluation_steps |
10B.3, 4.4 |
| 48 | DE. G-Eval scores are not clamped (8.0, 1.2, -0.3 occur); a rubric changes the normalization range; log-prob weighting depends on the judge | Guard the range; re-validate after any judge change | 10B.3, 4.5, 4.6, 4.9 |
| 49 | DE. Async compare() with show_indicator=False returns {}; A/B results near 50/50 can mean a position-biased judge |
Keep the indicator or run_async=False; swap-consistency check |
10B.3, 5.2 |
| 50 | DE. DAG: a judgement node reached only through another judgement gets no evidence; serialized DAGs lose their judge | Add the node under a TaskNode; print prompts |
10B.3, 7.4, 7.5 |
| 51 | DE. Expectations with unable_to_evaluate raises and aborts the run |
ErrorConfig(ignore_errors=True) and report errors |
10B.3, 8.2 |
| 52 | DE. Faithfulness by default fails only contradictions; an invented policy is borderline and passes |
penalize_ambiguous_claims=True, threshold from labels |
10B.4, 2.3 |
| 53 | DE. QAG metrics return 1.0 for an empty list (0 for Contextual Recall, Relevancy, Summarization alignment); a cheap judge that drops verdicts shrinks the denominator | Compare item and verdict counts in verbose_logs |
10B.4, 1.4 |
| 54 | DE. Since 4.2.0 (24 August 2026) Bias, Toxicity, Hallucination and Misuse score 1 for a pass; older thresholds are inverted | Invert old thresholds and assertions | 10B.4, 1.6 |
| 55 | DE. Bias judges only opinions; Toxicity's default threshold 0.5 passes half-bad outputs; PII Leakage flags the user's own email; JSON Correctness fails fenced JSON | Threshold 1 or strict mode; wrap or filter; parse first | 10B.4, 4.2, 4.7 |
| 56 | DE. Summarization reuses generated assessment questions across documents; Turn metrics use overlapping windows; ConversationCompleteness(window_size=) is unused |
Pass assessment_questions; window_size=1; ignore the unused argument |
10B.4, 3.2, 6.6 |
| 57 | DE. Task Completion's verdict and Plan Quality's score are computed from summaries the judge wrote earlier, never from the trace; the trajectory judges are five-anchor ordinal scales, and their default threshold of 0.5 accepts runs with plan deviations by design | Validate the extraction step; report the anchor distribution and use weighted kappa; thresholds from labels | 10B.5, 9.1 |
8.4 Metrics, scorers and statistics#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 58 | IN. Custom labels ("pass") convert to 0.0 through value_to_float(), so accuracy is 0 though the grades look right; a converter on the metric alone is overridden by the reducer's |
Return CORRECT/INCORRECT, or converters on reducer and metrics |
10B.10, 2.4 |
| 59 | IN. Unscored samples leave the denominator; all unscored gives nan |
Report coverage; treat nan as a failed run |
10B.10, 4.1 |
| 60 | IN. A TimeoutError escaping a solver is scored as if nothing happened |
Catch timeouts in solvers and tools | 10B.10, 4.3 |
| 61 | IN. Task(metrics=...) replaces every scorer's metrics; the viewer's headline is the first scorer's first metric |
List every metric; set headline_metric= |
10B.10, 6.1, 6.13 |
| 62 | IN. Adding a scorer renames results (match1, lower2): code that indexes by name breaks |
Look up by (name, reducer, metric) |
10B.10, 6.14 |
| 63 | IN. bootstrap_stderr() and ci(method="bootstrap") are unseeded; clustered standard error is 0 with equal cluster means; ci() runs outside [0, 1] with few samples |
Use stderr(), ci_wilson(), or seeded evalkit bootstraps |
10B.10, 6.5, 6.6, 6.7 |
| 64 | IN. pass_at_5 is refused with fewer than 5 epochs; majority shrinks the denominator on ties; a NaN in a custom "worst case" reducer improves the score |
epochs >= k; odd epochs; guard NaN |
10B.10, 7.5, 7.6, 7.7 |
| 65 | IN. pass_at(k) and pass_k(k) count an epoch as a success only at value=1.0 by default, so a ticket that always does half the job scores 0 strict and 1 at value=0.5; two thresholds in one Epochs list both report as pass_at_2 |
Choose and print value=, one threshold per run; in DeepEval the same decision is the metric's threshold (2.5) |
10B.16, 4.7 |
| 66 | IN. The standard error shrinks when reducers are disabled (epochs treated as independent); task-wide reducers apply to every scorer | Keep a reducer; report reducers only where they mean something | 10B.10, 7.8, 9.3 |
| 67 | IN. Epochs show zero variance with a deterministic model or a non-per-epoch cache | Production settings; per_epoch=True |
10B.10, 7.11, 10B.12, 6.4 |
| 68 | both. A benchmark's overall accuracy is a micro-average over questions, so a small task that regressed hides inside it; comparing two models' tallies ignores that they answered the same items | Report per-task (macro) scores and an exact McNemar test on the discordant items | 10B.6, 9.10 |
| 69 | DE. A custom metric that stores an argument under another name silently uses the default in async evaluate() and assert_test() (and so under deepeval test run) |
self.<argument> = <argument> for every argument |
10B.2, 4.5 |
| 70 | DE. Metric objects passed to evaluate() are not where results live; a shared sub-metric inside a composite leaks between cases |
Read test_results; build sub-metrics yourself |
10B.2, 4.3, 10B.3, 6.4 |
| 71 | DE. The cache (-c) ignores custom metric parameters and serves stale scores; -r silently turns -c off |
Delete .deepeval/.deepeval-cache.json; version metric names; no cache in gates |
10B.2, 6.3, 5.4 |
| 72 | DE. skip_on_missing_params can make an unscored case look like a pass and drops it from the totals; errors under ignore_errors fail the case, so a provider outage looks like quality failure |
Count cases with empty metrics_data; read error |
10B.2, 4.9 |
| 73 | DE. PatternMatchMetric is a full match; ExactMatchMetric is case-sensitive; a metric can score above 1 if the judge returns an out-of-range number |
Read the rules; assert 0 <= score <= 1 |
10B.2, 3.6 |
| 74 | DE. DisplayConfig(display=...) from the docs is a TypeError; the field is display_option |
display_option=TestRunResultDisplay.FAILING |
10B.2, 4.7 |
8.5 Running, concurrency and CI#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 75 | IN. inspect eval file.py runs every @task in the file (the bill doubles); a -T meant for one only warns for the other |
file.py@task; inspect list tasks |
10B.8, 5.1 |
| 76 | IN. A model= set on the Task beats --model; task_args are ignored for an already-built Task; a list starting with a Task drops the strings after it |
No model= on reusable tasks; pass by name; keep lists homogeneous |
10B.8, 5.2, 5.4, 5.6 |
| 77 | IN. inspect eval exits 0 on error status: CI green, eval crashed |
inspect eval-set and a log-reading gate |
10B.12, 11.5, Part 13 |
| 78 | IN. fail_on_error=5 fails a run with exactly 5 errors (the threshold is "at least" in 0.3.292; the docs say "more than"); tolerated errors leave the denominator |
Set N + 1 to tolerate N; gate on scored = total | 10B.12, 8.2 |
| 79 | IN. retry_on_error re-rolls input-correlated failures, so retried samples score suspiciously well; refusals count as wrong in one run and missing in another |
Compare retried and first-try samples; fix fail_on_refusal policy |
10B.12, 8.4, 8.6 |
| 80 | IN. eval_retry() writes to ./logs unless given log_dir; task files that run an eval on import break retry; a task built without @task cannot be found |
log_dir; if __name__ == "__main__":; @task |
10B.12, 9.1, 9.2 |
| 81 | IN. An eval set rejects a directory whose command changed or that holds a foreign log | A new directory per experiment | 10B.12, 11.4 |
| 82 | IN. temperature=0 "had no effect": models that reject sampling settings drop it with a warning; reasoning models use the max_tokens budget and return empty or truncated answers |
Read the warnings; count stop_reason="max_tokens" |
10B.12, 3.4 |
| 83 | IN. A run hangs for half an hour (unlimited retries, long backoff); hard samples fail with timeouts when attempt_timeout is below the slowest healthy call |
timeout, attempt_timeout; size from measurement |
10B.12, 5.2 |
| 84 | IN. The response cache key holds the model alias, not the snapshot: last week's answers after a model update; per_epoch=False races the cache; a Python-built model caches per instance |
Dated model ids; inspect cache clear --model; plain-JSON constructor arguments |
10B.12, 6.7, 6.4, 6.5 |
| 85 | IN. Batch mode on a multi-turn task means a 24-hour wait; early stopping skipped nothing when every sample was scheduled first | Batch only single-turn; lower max_samples |
10B.12, Part 7, 12.2 |
| 86 | IN. mockllm replies from a list are consumed in request order, which concurrency shuffles; mockllm counts characters as output tokens; a re-run from export-config cannot rebuild a scripted mock |
Key replies on the input; never quote mock usage | 10B.8, Part 9 |
| 87 | DE. The CI job is green but no evaluation ran: exit code 5 (nothing collected) swallowed, or || true in the script |
Let non-zero exits fail the job; a deliberately broken case must turn it red | 10B.2, 5.5, 10B.7, 2.3 |
| 88 | DE. -n workers lose test cases from DeepEval's summary (which case survives is random); span-level failures are missing from the console table and the assertion |
Sequential gates, pytest's exit code and --junit; parse .deepeval/.latest_test_run.json |
10B.7, 2.4, 2.5 |
| 89 | DE. Confident AI's free tier allows 5 test runs per week: the sixth CI upload fails | Upload nightly only, or keep pull-request jobs keyless | 10B.7, 5.4 |
| 90 | DE. There is no local baseline command: a regression that still passes thresholds is invisible | Archive run files and diff them (4.4) | 10B.7, 2.8 |
8.6 Logs and analysis#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 91 | IN. log.results is None on a failed run, so analysis scripts crash; "the latest log" from list_eval_logs()[0] in a shared folder is a colleague's |
Check status first; filter by header fields |
10B.13, 3.9, 5.2 |
| 92 | IN. NaN in a log breaks strict JSON consumers; .eval and .json copies of one run are counted twice |
Convert NaN to null; formats=["eval"] |
10B.13, 2.3, 2.2 |
| 93 | IN. The mean over samples_df() disagrees with the results panel (one row per epoch, raw C/I strings, NaN as 0); messages_df(filter=["assistant"]) ignores a list filter; score columns rename when a second reducer arrives |
Reduce per id; a callable filter; select by prefix |
10B.13, 8.3, 8.4, 8.2 |
| 94 | IN. EvalLogInfo.name is a file:// URI; model event inputs may be attachment://...; re-scoring needs log_samples=True |
Pass to Inspect functions; resolve_sample_attachments(); keep samples |
10B.8, 7.2, 10B.13, 4.4, 2.4 |
| 95 | IN. A number changed after "just adding a tag": logs were rewritten in place | Edit copies; audit log_updates and score history |
10B.13, 6.1 |
| 96 | IN. The viewer renders untrusted model output, including links; a tracking hook silently records nothing when enabled() is false |
ViewerConfig(trust_content=False); test hooks |
10B.13, 7.2, 10.5 |
| 97 | DE. Run files hold only the latest run; a CI run that overwrites them loses history | Archive .deepeval/ files as artifacts with if: always() |
10B.2, 1.7, 10B.7, 6.4 |
| 98 | DE. deepeval test run > run.txt captures stdout only: pytest's warnings, which print the virtual environment's absolute path, go to stderr, so the saved log is silently trimmed, and a full capture carries a home-directory path |
2>&1 into the artifact; search for and scrub home paths before a log leaves the machine |
10B.1, 7.2 |
| 99 | IN. A benchmark number differs from last quarter's because the task's comparability version (the N of N-X), its arguments or its epochs changed |
Compare task_version, task_args and epochs in both logs before the scores |
10B.16, 9.4 |
| 100 | IN. A Scout scanner's "agreement 0.5" hides its false negatives; the default eq predicate says 2 == true is false, so a count-valued scanner disagrees with yes/no labels; scan() in a script with no main guard dies with EOFError |
Report precision, recall and confusion counts; choose the predicate; if __name__ == "__main__": |
10B.16, 7.8 |
8.7 Agents, tools, sandboxes and tracing#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 101 | DE. In a traced eval the iterator wrapper is the trace root, so actual_output is missing; automatic span input is a stringified dict |
update_current_trace(...), update_current_span(input=...) |
10B.5, failure gallery |
| 102 | DE. handoff_agents (the docs' keyword) is silently ignored; the source keyword is agent_handoffs |
Use agent_handoffs; test with a known handoff |
10B.5, failure gallery |
| 103 | DE. Falsy updates (output="", retrieval_context=[]) are ignored |
A sentinel or metadata; redesign the empty-state test | 10B.5, failure gallery |
| 104 | DE. Plan Adherence passes every run when no plan is present (empty plans score 1.0); Step Efficiency ignores correctness; Tool Correctness ignores extra calls | Instrument explicit plans; pair with outcome metrics; add Tool Permission | 10B.5, Part 9, Part 10 |
| 105 | DE. Argument Correctness sees no calls without an owning llm span; multi-turn MCP units of two or fewer turns are skipped; a thread that does not inherit context (run_in_executor) drops its spans |
Instrument the decision-making call; represent turns separately; copy_context().run |
10B.5, 10.2, failure gallery |
| 106 | DE. DEEPEVAL_AUTO_TRACE instruments supported libraries automatically; masking only handles strings, so dict inputs leak |
Disable for controlled experiments; recursive masks | 10B.5, 6.3 |
| 107 | DE. A tool that raises inside a traced run and is caught by the agent leaves an ERRORED span whose metrics are skipped, and the golden passes (a 100% pass rate); an exception escaping a sync evals_iterator loop aborts the whole suite |
Fail CI on any ERRORED span read from the run file (4.7); catch at the agent boundary |
10B.5, 4.5, 4.7 |
| 108 | DE. A golden's expected_output, context, retrieval_context and expected_tools are not copied into a traced test case: a reference metric raises MissingTestCaseParamsError, or, under skip_on_missing_params=True, is skipped while the case still counts as passed |
Copy them with get_current_golden() into update_current_trace or update_current_span; gate on scored metrics per case |
10B.5, 4.3, 4.7 |
| 109 | DE. A metric staged with next_llm_span (or any next_*_span) applies to the next span only, and a typed payload replaces the base metadata wholesale |
One with block per call |
10B.5, 3.3 |
| 110 | DE. Agent Loop Detection scores an obviously looping agent 1.0 when its thoughts are under 20 meaningful words, alternate between two texts or are paraphrased, and reports a false cycle when two inputs share their first 64 characters | Planted-fault fixtures shaped like your agent's loops; budgets as the real guard | 10B.5, 10.4 |
| 111 | IN. After approval is added the agent never submits: no catch-all, so submit itself is rejected |
Approve submit deliberately |
10B.15, 8.6 |
| 112 | IN. Approval fails closed (a call no approver matches is rejected) but tool result review fails open (a result no reviewer matches reaches the model), so a typo in a review pattern, or an agent-level review= that replaced the eval-level policy, silently reviews nothing |
Probe every reviewer with a result that must trigger it; count ReviewEvents per tool |
10B.15, 9.1, 9.3 |
| 113 | IN. Approval argument matching compares JSON forms (10 is not 10.0) and needs every listed argument present; a modify decision must return every argument in full |
Unit-test the matcher at its boundaries; {**call.arguments, ...} in modify |
10B.15, 8.4, 8.1 |
| 114 | IN. An approver that checks evidence with a substring test (order_id in first_user) authorizes a refund on ORD-1002 when the customer named ORD-10021 |
Unit-test approvers directly with synthetic ToolCalls on look-alike and boundary cases |
10B.15, 12.4 |
| 115 | IN. A token limit is exceeded despite the setting: the limit-crossing generation is made and discarded; working_limit never fires on a rate-limited run; cost stops at the wrong amount without cached-token pricing |
Margin in forecasts; pair with time_limit; validate cost data on a tiny metered run |
10B.15, 7.4 |
| 116 | IN. Infrastructure timeouts are scored as wrong answers; hard tasks look worse after a timeout change | Read SandboxTimeoutError.reason (new in 0.3.292; getattr(ex, "reason", None) on older versions); exclude or retry infrastructure failure |
10B.15, 6.3, 3.3 |
| 117 | IN. The local sandbox "passes" a security review though it is not isolation; a custom compose file silently replaces the no-network default |
Docker or stronger for untrusted code; add network_mode: none or justify the network |
10B.15, 2.4, 5.2 |
| 118 | IN. A bridged external agent's transcript is its self-report; a human-steered sample counts as autonomous; side effects outside the sandbox are not transactional on resume | Instrument the sandbox; filter operator events; idempotent side effects | 10B.15, 10.4, 10B.15, 10.9 |
| 119 | IN. "Accuracy is perfect" on a probe suite that passes samples stopped before harm; one model "wins" only with more turns; scores improve when approval tightens | Report completion, budget stops, operator stops; equal budgets; separate agent behaviour from guarded-system outcome | 10B.15, 12.8, 10B.16, Part 5 |
| 120 | IN. At a turn limit the submit call needs a turn of its own, and stopped samples are still scored (as I), so lowering a budget lowers accuracy with no new wrong answers, and agent rankings flip between budgets |
Budget = steps plus scaffold turns; count s.limit stops separately; report a budget curve |
10B.16, 5.6, 10B.15, 12.5 |
| 121 | IN. pass@2 looks excellent while users complain; a keyless benchmark run scores zero (mock output, not capability); pip install petri installs the wrong package |
pass^k and per-attempt means; read the completion; use inspect-petri |
10B.16, 17.3 |
8.8 Red teaming, safety and the version ledger#
| # | Surprise | Fix | Reproduced in |
|---|---|---|---|
| 122 | DE. deepeval.red_team returned in 4.3.6 (25 November 2026); deepteam will be deprecated on 30 January 2027; deepeval.red_teaming (plural, pre-3.0) no longer exists |
Migrate imports to deepeval.red_team; no new project on deepteam |
10B.7, 1.1, 1.13 |
| 123 | DE. "100% resisted" red-team theatre: refusal short-circuits, a lenient judge, one attack per type; ignore_errors excludes errored cases from the rate |
Report counts, the auto-passed fraction and judge agreement; count error yourself |
10B.7, 6.3 |
| 124 | DE. deepeval red-team prints failures and exits 0 (it fails only on config errors); legacy deepteam telemetry surprises a security scan |
Gate the saved JSON; migrate or set the opt-out switch | 10B.7, 6.3 |
| 125 | DE. An optimizer rewrites the prompt to memorize the golden set, and an optimized prompt can break the safety slice | Held-out split; include the red-team slice in the gate | 10B.7, 4.6 |
| 126 | IN. web_browser() was deprecated in 0.3.272 and removed in 0.3.288: the name still imports, and calling it raises PrerequisiteError |
web_search() for retrieval; computer() or a browser MCP server in a sandbox |
10B.1, 10.2 |
| 127 | both. A score belongs to a version: 4.2.0 inverted four metrics, 0.3.262 changed tie handling, 0.3.288 changed the default grader template | Frozen suite before and after every upgrade (6.8) | 10B.1, 2.5 |
That is 127 rows. They look like a lot, and they are, but they fall into five families that are easier to remember than the rows:
- The silent denominator: something left the count (unscored samples, skipped cases, vanished cases, tolerated errors, a
NaN, a metric skipped on an errored span or a missing field) and the headline stayed plausible. (Rows 24, 41, 53, 59, 64, 72, 78, 88, 107, 108.) - The silent default: a default you did not choose decided the answer (the grader that is the model under test, the threshold 0.5, the default judge, the empty target, the default metric of the viewer, the success threshold of
pass_at, a review policy that lets unmatched results through). (Rows 4, 17, 19, 32, 38, 52, 55, 57, 61, 65, 112.) - The silent copy: the framework rebuilt, cached or re-ran something, or did not carry across what you assumed it carried, so state or a score was not what you set (the async metric copy,
-c, the response cache, regenerated G-Eval steps,retry_on_error, golden fields that never reach a traced test case, a port that lost a field). (Rows 25, 46, 47, 69, 71, 79, 84, 108, 109.) - The wrong layer reported as green: the exit code, the console table or the printed number is not the verdict (
inspect evalexit 0,-nsummaries, red-team CLI exit 0, span failures, a 100% pass rate over an errored span, a HumanEval overall score whose tests never ran). (Rows 36, 77, 87, 88, 107, 124.) - The moving ground: versions, renames and docs that trail the code (4.2.0, 4.3.6, the
deepteamdeprecation,display_option,handoff_agents, the unseeded bootstrap, the removedweb_browser(), a benchmark's task version). (Rows 54, 74, 99, 102, 122, 126, 127.)
When something odd shows up, ask which family it belongs to before you ask anything else.
8.9 A scanner for the ones a regex can find#
Perhaps one row in six leaves a fingerprint in source code or CI configuration: a deprecated import, a documented keyword that does not exist, a removed tool, || true in a job, an inspect eval of a whole file, a pass_at(2) with no threshold. A scanner will not find the others (a silent denominator is behaviour, not text), but it is the cheapest first pass over a repository that has been using either package for a while, and it works the way 08F.15's legacy scanner does: standard library only, severity, a reason and a pointer to the lesson. It was run on a fixture of two deliberately flawed files and a CI workflow. Nineteen rules cover the most common fingerprints; four of them (DE-bench-sc, DE-golden, IN-browser, IN-passat) were added with the checklist update.
# pitfall_scan.py: a first inventory of known DeepEval and Inspect traps in a source tree (lesson 10B.17)
# Standard library only. A regex scan is a starting list, not a proof: read what it flags.
# usage: python pitfall_scan.py <directory>
import re
import sys
from pathlib import Path
# (id, glob of files to scan, regex, severity, what is wrong, where this course explains it)
RULES = [
("DE-display", "*.py", r"DisplayConfig\([^)]*\bdisplay=", "breaks", "the field is display_option; `display=` is a TypeError", "10B.2, 4.7"),
("DE-params", "*.py", r"\bLLMTestCaseParams\b", "warns", "deprecated name; use SingleTurnParams", "10B.2, Part 11"),
("DE-redteam", "*.py", r"deepeval\.red_teaming\b", "breaks", "the pre-3.0 module no longer exists; use deepeval.red_team (4.3.6+)", "10B.7, 1.13"),
("DE-deepteam", "*.py", r"^\s*(import|from)\s+deepteam\b", "warns", "deepteam is deprecated from 30 January 2027; migrate to deepeval.red_team", "10B.7, 1.13"),
("DE-bench", "*.py", r"deepeval\.benchmarks\.task\b", "breaks", "the docs say `task`, the package says `tasks`", "10B.6, 9.2"),
("DE-handoff", "*.py", r"\bhandoff_agents\b", "warns", "the keyword is agent_handoffs; this one is silently ignored", "10B.5, failure gallery"),
("DE-keyless", "*.py", r"\bFaithfulnessMetric\(\s*threshold=\d(\.\d+)?\s*\)", "review", "no model=: needs a default judge and a key at construction time", "10B.2, 3.4"),
("DE-bench-sc", "*.py", r"\b(HumanEval|TruthfulQA)\(", "warns", "HumanEval never calls the tests and reports any-pass; TruthfulQA MC2 is recall-only and changes scale when batched", "10B.6, 9.5 and 9.6"),
("DE-golden", "*.py", r"update_current_trace\((?![^)]*expected_output)[^)]*\boutput=", "review", "a golden's expected_output is not copied into the traced test case; copy it if a metric needs it", "10B.5, 4.3"),
("DE-ci-true", "*.yml", r"deepeval test run.*\|\|\s*true", "breaks", "`|| true` makes the job green whatever the suite did", "10B.7, 2.3"),
("DE-ci-xdist", "*.yml", r"deepeval test run.*\s-n\s*\d", "warns", "parallel workers lose cases from DeepEval's summary", "10B.7, 2.5"),
("IN-empty", "*.py", r"Sample\([^)]*target=\"\"", "warns", "an empty target makes includes() and match() pass everything", "10B.9, 2.2"),
("IN-braces", "*.py", r"(system_message|prompt_template|user_message)\(\s*['\"][^'\"]*\{\"", "breaks", "single braces in a template are silently mangled; double them", "10B.8, 9.2"),
("IN-grader", "*.py", r"model_graded_(qa|fact)\(\s*\)", "review", "no model= and maybe no grader role: the model under test may grade itself", "10B.11, 5.2"),
("IN-failerr", "*.py", r"fail_on_error\s*=\s*False", "review", "errors leave the denominator; gate on scored = total", "10B.12, 8.2"),
("IN-latest", "*.py", r"list_eval_logs\([^)]*\)\[0\]", "warns", "the newest log in a shared folder may be someone else's run", "10B.13, 5.2"),
("IN-browser", "*.py", r"\bweb_browser\(", "breaks", "removed in 0.3.288: the name still imports, calling it raises PrerequisiteError", "10B.1, 10A.2"),
("IN-passat", "*.py", r"\bpass_(at|k)\(\s*\d+\s*\)", "review", "success threshold value=1.0 by default: partial credit counts as failure; print it", "10B.16, 4.7"),
("IN-ci", "*.yml", r"inspect eval\s+\S+\.py(\s|$)", "breaks", "runs every task in the file, and exits 0 on error status: use eval-set and gate the log", "10B.8, 9.1; 10B.12, Part 13"),
]
def scan(root: Path) -> list[tuple[str, str, int, str, str, str]]:
hits = []
for rule_id, pattern_glob, regex, severity, why, lesson in RULES:
rx = re.compile(regex)
for path in sorted(root.rglob(pattern_glob)):
for no, line in enumerate(path.read_text().splitlines(), 1):
if rx.search(line):
hits.append((severity, str(path.relative_to(root)), no, rule_id, why, lesson))
return sorted(hits, key=lambda h: ({"breaks": 0, "warns": 1, "review": 2}[h[0]], h[1], h[2]))
if __name__ == "__main__":
hits = scan(Path(sys.argv[1]))
for severity, file, no, rule_id, why, lesson in hits:
print(f"{severity:6} {file}:{no:<3} {rule_id:11} {why} [{lesson}]")
counts = {s: sum(h[0] == s for h in hits) for s in ("breaks", "warns", "review")}
print("\n" + ", ".join(f"{n} {s}" for s, n in counts.items()))
sys.exit(1 if counts["breaks"] else 0)breaks .github/workflows/evals.yml:7 DE-ci-true `|| true` makes the job green whatever the suite did [10B.7, 2.3]
breaks .github/workflows/evals.yml:8 IN-ci runs every task in the file, and exits 0 on error status: use eval-set and gate the log [10B.8, 9.1; 10B.12, Part 13]
breaks test_support_bad.py:8 DE-redteam the pre-3.0 module no longer exists; use deepeval.red_team (4.3.6+) [10B.7, 1.13]
breaks test_support_bad.py:9 DE-bench the docs say `task`, the package says `tasks` [10B.6, 9.2]
breaks test_support_bad.py:12 DE-display the field is display_option; `display=` is a TypeError [10B.2, 4.7]
breaks triage_bad.py:13 IN-braces single braces in a template are silently mangled; double them [10B.8, 9.2]
breaks triage_bad.py:24 IN-browser removed in 0.3.288: the name still imports, calling it raises PrerequisiteError [10B.1, 10A.2]
warns .github/workflows/evals.yml:7 DE-ci-xdist parallel workers lose cases from DeepEval's summary [10B.7, 2.5]
warns test_support_bad.py:7 DE-params deprecated name; use SingleTurnParams [10B.2, Part 11]
warns test_support_bad.py:10 DE-deepteam deepteam is deprecated from 30 January 2027; migrate to deepeval.red_team [10B.7, 1.13]
warns test_support_bad.py:14 DE-handoff the keyword is agent_handoffs; this one is silently ignored [10B.5, failure gallery]
warns test_support_bad.py:15 DE-bench-sc HumanEval never calls the tests and reports any-pass; TruthfulQA MC2 is recall-only and changes scale when batched [10B.6, 9.5 and 9.6]
warns triage_bad.py:12 IN-empty an empty target makes includes() and match() pass everything [10B.9, 2.2]
warns triage_bad.py:17 IN-latest the newest log in a shared folder may be someone else's run [10B.13, 5.2]
review test_support_bad.py:13 DE-keyless no model=: needs a default judge and a key at construction time [10B.2, 3.4]
review test_support_bad.py:21 DE-golden a golden's expected_output is not copied into the traced test case; copy it if a metric needs it [10B.5, 4.3]
review triage_bad.py:14 IN-grader no model= and maybe no grader role: the model under test may grade itself [10B.11, 5.2]
review triage_bad.py:18 IN-failerr errors leave the denominator; gate on scored = total [10B.12, 8.2]
review triage_bad.py:25 IN-passat success threshold value=1.0 by default: partial credit counts as failure; print it [10B.16, 4.7]
7 breaks, 7 warns, 5 reviewRead the output the way you read a linter. The breaks are things that fail or silently do nothing (a loader keyword that is a TypeError, a module that no longer exists, a removed tool, a job that cannot go red, an inspect eval of a whole file); the warns are things that work today and will not for long (a deprecated name, deepteam after 30 January 2027) or that produce a misleading number (a DeepEval HumanEval or TruthfulQA score); the reviews are patterns that are sometimes right and need a human: a model_graded_fact() with no model= is fine when a grader role is bound at run time, a pass_at(2) at the default threshold is right when success really means full credit, and an update_current_trace() without expected_output is fine when no metric on the trace needs a reference. The scanner's value is the inventory, as in 08F.15's: you leave knowing which files to read first. Extend the rule list with the surprises your team hits, and run it in CI with a non-zero exit on breaks only.
8.10 A pre-flight checklist#
Before you trust the first number from a new eval, and again before you quote any number outside the team, walk this list. It condenses the lesson-level checklists (10B.2, 10.6, 10B.8, 10.5, 10B.10, 10.2, 10B.11, 13.3, 10B.12, 14.6, 10B.14, 10.8, 10B.15, 12.10, 10B.16, 17.4) into twelve questions that apply to either package.
- Name the instrument. Framework and version, metric or scorer, the judge model's dated snapshot and settings, the rubric or template version, and the reducer; for a reliability number, the epochs,
kand the success threshold (value=in Inspect, the metric threshold in DeepEval). - Name the number's denominator. Cases collected, cases scored, unscored, errors, skipped (including metrics skipped on errored spans or missing fields), budget and operator stops: every count, every time.
- Run the controls. An oracle near the maximum, a null near the minimum, in the same run configuration.
- Read the reasons. Twenty of them, passes and failures, from the judge's own output.
- Validate the judge. Agreement, true-positive and true-negative rates against human labels with intervals, on a held-out set (10A.5). Re-validate after any change.
- Measure the noise. Re-grade the same outputs; repeat the run; report the spread.
- Report uncertainty. An interval, clustered when cases share a source; a paired interval for any comparison.
- Compare like with like. Same cases (joined on id), same task and check versions, same epochs and reducers, same judge.
- Check the gate fails closed. A deliberately broken case turns the job red; an empty scan fails; an errored span or a skipped metric fails (4.7); every approver and reviewer has been probed with a case that must trigger it.
- Check the data. Row counts on both sides of any conversion, empty and edge cases intact, no leakage from a generator that shares a family with the judge.
- Check what left the machine. Telemetry off, no key where text is sensitive, logs scrubbed before they travel.
- Date it. The run record (6.5) goes with the number.
Part 9: Choosing: the decision table and the other tools#
9.1 The decision table#
10B.1, 8.1 gave the short version for deciding where to start. Now that both packages are known, this is the fuller one. Read it as "what is the work you will do most, and which tool makes it cheap".
| Your situation | Choose | Why | Watch out for |
|---|---|---|---|
A product feature (support bot, docs_qa, extraction) with evals that gate pull requests |
DeepEval, smoke tier keyless | Metric objects with thresholds, assert_test(), ready-made RAG and safety metrics, a clean exit code |
Judge validation; -n, || true and cached scores in CI (8.5) |
| An agent with tools, code execution or a world to change | Inspect | The solver is the agent; tools, sandboxes, limits, approval and a transcript are built in | Budgets as conditions; sandboxes for untrusted code (10B.15) |
| The same recipe over many models or prompts | Inspect | One task, --model many times, eval sets, reproducible logs |
Pinned model versions; cache aliases |
| Public benchmarks | Inspect with Inspect Evals (and Harbor for container tasks) | 200-plus ready-made tasks | Defaults differ from papers; keyless runs prove plumbing only |
| RAG quality (faithfulness, relevancy, precision, recall) | DeepEval metrics, or your own checks | The metrics exist with prompts you can read | penalize_ambiguous_claims; empty-list scores; calibration |
| Red teaming your own app | DeepEval 4.3.6 deepeval.red_team (legacy deepteam only for migration) |
Purpose-built, with a CLI | Count errors yourself; Module 12 owns the depth |
| Studying a model's behaviour, transcripts and audits | Inspect with Scout and friends | Logs and analysis tools | Reading evidence, not just scores |
| Between-run statistics and judge calibration | evalkit (over either framework) |
Neither framework has them | Join on id; same versions |
| One small eval, one author, no CI | evalkit or a script |
A framework costs more than the 200 lines you have | Revisit when a second author or CI appears |
| A metric you must explain line by line | Custom checks in either framework | No built-in prompt between you and the number | Own the maintenance |
| You already live in a platform (LangSmith, Braintrust, Langfuse, Phoenix) | That platform's SDK, optionally with a framework inside | Datasets, evaluators and a runner already exist | Lock-in; keep the data portable |
| A config-file gate in any language | promptfoo (10A.10) | YAML plus a CLI, many providers | Python checks outgrow YAML |
| Both product assertions and agent studies | Both, with an owner each (6.2) | DeepEval for the PR gate, Inspect for studies | Shared plain checks, shared data |
flowchart TD
S["Start: what is the thing under test?"] --> A{"An agent with tools,<br/>files or a world to change?"}
A -- yes --> IN["Inspect<br/>(solver, sandbox, limits, logs)"]
A -- no --> B{"Same recipe over several<br/>models, or public benchmarks?"}
B -- yes --> IN
B -- no --> C{"Do you need pytest-style<br/>thresholds on RAG or safety metrics?"}
C -- yes --> DE["DeepEval<br/>(smoke tier keyless)"]
C -- no --> D{"One small eval you can<br/>define fully yourself?"}
D -- yes --> EK["evalkit or a script"]
D -- no --> E["Prototype both on 20 cases<br/>(the bake-off, 9.2)"]
IN --> F["Add evalkit statistics and<br/>judge calibration either way"]
DE --> F
EK --> F
E --> F9.2 The one-day bake-off#
If the table does not settle it, run a bake-off, but a disciplined one. The point is to measure the work, not to read feature lists.
- Pick one real eval you already run (20 real cases, not toy ones) and freeze a fake model for it.
- Port it to each candidate by the playbook of 5.1: plain checks, a wrapper, a parity test against the baseline.
- Measure the work, not the output: time to port, lines of wrapper, number of surprises met (use the checklist of Part 8, and write each one down), time to find the failing case from a cold start, time to gate a pull request.
- Make it fail on purpose: break two cases and one environment setting, and see what each tool shows you and how long it takes to find the cause.
- Try the exit: port the smallest piece to the other tool or back to
evalkit. If it takes more than an hour, the lock-in is higher than the table said.
Write the results in a table of your own (candidate, hours, surprises, lines, gate result, exit hours). The deciding row is usually not the one anyone expected.
9.3 Where the other tools fit#
10A.10, Part 2 lists the landscape with versions and licences, and 11A.5 covers LangSmith. Relative to the two packages of this track:
| Tool | What it is | Relation to DeepEval and Inspect | Reach for it when |
|---|---|---|---|
| promptfoo | A YAML-and-CLI eval and red-team tool | Overlaps DeepEval's CI role with less Python; also red-teams | A config-file gate in any language, fast |
| Ragas | A RAG metrics library | DeepEval wraps some of its metrics (10B.4, 2.9); the same names carry different definitions | You already use its metrics and need continuity |
LangSmith with openevals |
A platform plus an evaluator library, from the LangChain stack | Coexists with either; datasets and runs live in LangSmith | You already trace with LangSmith (11A.5) |
| Braintrust, Langfuse, Phoenix, Opik, Weave, MLflow | Platforms: UI, storage, online evaluation | Sit over logs from either package | You need a hosted UI or online scoring (Module 11A) |
| TruLens, Giskard | Python libraries near DeepEval's neighbourhood | Alternative metric and test-suite styles | You want their specific feedback functions or scanning |
| lm-evaluation-harness, HELM, Lighteval | Benchmark runners | Inspect Evals overlaps for public benchmarks | A specific leaderboard's exact protocol |
| OpenAI Evals (hosted) | A hosted eval product | Listed in 10A.10 as shutting down on 30 November 2026 | Do not build on it |
The rule of thumb for all of them is the one of 10A.10, 1.2: a platform sells visibility, a library sells measurement helpers, and neither replaces the data, the checks and the judge validation you own.
9.4 Five teams, five answers#
| Team | Situation | A sensible answer | Why |
|---|---|---|---|
| A three-person startup | A RAG support bot, one engineer owns evals, no CI yet | evalkit plus a few DeepEval RAG metrics behind a pytest gate when the first regression bites |
A framework before a second author costs more than it returns |
| A product team | A support agent with tools, a nightly run, a PR gate | Inspect for the agent eval (controlled world, limits, logs), DeepEval for the RAG and safety metrics, plain shared checks, one combined gate | Each tool does what it is best at (6.2) |
| A platform team | Supporting twelve product teams | A thin internal package of plain checks and a gate; DeepEval and Inspect as adapters; run records as a contract | The exit plan is the product |
| A regulated team | Must explain every metric line by line | Custom checks and scorers in one framework, a calibrated judge, run records and a frozen-fake canary | No built-in prompt between you and the number |
| A research group | Comparing models and agent scaffolds, publishing | Inspect, with Inspect Evals, Scout and Viz, epochs and reducers, pinned versions | It is what Inspect was built for |
Part 10: Methodology: defending a number from two frameworks#
Deep-dive
Everything before this part was about producing numbers. This one is about the moment someone asks "why should I believe that?", in a setting where two frameworks, three definitions of the same word and a judge are involved.
10.1 What is the number, in each framework?#
Before anything else, ask what the number is. The same sentence, "it scored 0.9", names different objects.
| You say | In DeepEval it is | In Inspect it is | In evalkit it is |
|---|---|---|---|
| "The score" | One metric's float for one case (higher is better) | The value of a Score for one sample: a letter, a float, a bool, a list or a dict |
A Score.value in [0, 1] |
| "The metric" | An object scoring one case | A function over all the scores (accuracy()) |
A rate or mean over rows |
| "The pass rate" | Printed: cases where every metric passed | Not printed: you compute it | pass_rate of the report |
| "Accuracy" | Computed by you | Printed: mean of per-sample verdicts after reducers, over scored samples | Computed |
| "The error bar" | Not printed | Printed stderr, clustered on request |
Bootstrap or Wilson interval |
| "The run" | One evaluate() or deepeval test run |
One eval() producing a log per task and model |
One run_eval |
A report that quotes a headline without the row of this table it came from is incomplete.
10.2 Reconcile before you report#
When two frameworks (or a framework and evalkit) are involved, reconcile in a fixed order, as 3.1 did:
- Cases. Same rows, same count, same ids. If the counts differ, stop: something dropped or refused rows (5.2).
- Per-case verdicts. Same set of failing cases, on deterministic checks, on a frozen fake.
- Per-case scores. Same values.
- Aggregates. Same arithmetic: name each headline (pass rate, mean, accuracy) and compute each from the per-case scores.
- Uncertainty. An interval for each, computed the same way.
Only then compare anything judged. A judged number that differs between frameworks is expected, since the prompts differ; what you need is each judge's agreement with human labels, not an argument about whose 0.82 is right.
10.3 Disagreement is information, so classify it#
When two numbers that should agree do not, there are three kinds of cause, and each has a different test.
| Kind | How to tell | Example from this lesson |
|---|---|---|
| Definition | The per-case verdicts differ only where the definitions differ; changing the check to match makes them agree | Pass rate versus per-scorer accuracy (3.1); "matches reference" versus "grounded" on the abstention q05 (3.2) |
| Noise | Repeating the same run on the same data moves the number; the difference is smaller than the spread | A judge that re-grades differently; epochs; an unseeded bootstrap; per-case regenerated G-Eval steps |
| A bug | The difference survives controls and does not fit a definition | A wrapper that stores an argument under another name; a loader that rejects the empty ticket (5.2); a gate that reads the wrong file |
The oracle and null controls (6.4) separate bug from definition quickly: a bug usually breaks a control, a definitional difference does not.
10.4 Make the checks earn their keep#
A metric or scorer that has never disagreed with the others has not been shown to matter. When you add one, list the cases it fails that nothing else failed, and read them. In 3.3 the ToolCorrectness metric failed two cases the outcome and policy checks passed, which is exactly the argument for keeping it (if the policy question is real) or dropping it (if it is not): the disagreement forced the team to decide what "correct" means for an answer given without a lookup.
10.5 Sensitivity checks#
Change one thing on a frozen fake, predict which numbers move and by how much, then run. Examples that take minutes: make T05's category wrong in the triage replies (the DeepEval pass rate should fall from 10 of 12 to 9 of 12, and the labels mean from 0.889 to 0.861), swap one scripted grader verdict in docs_qa, remove a tool call from the careless agent's plan. If the observed movement does not match your prediction, you have found a misunderstanding of the metric or a bug, both of which are cheaper to find on a fake than on a real run.
10.6 What not to claim#
| Do not say | Say instead |
|---|---|
| "DeepEval and Inspect agree" | "They agree on the failing cases and per-case scores for these deterministic checks, on this fixture" |
| "The judge is accurate" | "On 60 labelled cases the judge's agreement with 3 reviewers is kappa 0.71 (interval 0.52 to 0.85)" |
| "Faithfulness improved from 0.78 to 0.82" | "The paired difference over the same 120 cases is +0.04, interval -0.02 to +0.10: not detectable" |
| "The agent is 90% reliable" | "Per-attempt success is 0.9 over 40 tasks (interval ...); pass^5 is 0.62" |
| "We tested it with Inspect" | "We ran triage@2 under Inspect 0.3.292 with grader model X, 3 epochs, 118 of 120 samples scored" |
| "Our evals pass" | "The smoke tier passed (12 of 12 cases, controls intact); the judged tier last ran on 26 November" |
Each replacement states what was done and what the number covers, and none of them needs more than a sentence.
Part 11: Older code, tutorials and what moved in 2026#
Reference
11.1 A decoder for older code#
Most material online predates the current names. The tables of 10B.2, Part 11, 10B.3, Part 14, 10B.4, Part 10, 10B.8, Part 11, 10B.9, Part 12, 10B.10, Part 12, 10B.12, Part 16, 10B.7, Part 7 and 10B.16, Part 18 are the full decoders. This is the condensed version: the twenty-two names you will meet most, in one table.
| You see | Package | It is | Write instead |
|---|---|---|---|
LLMTestCaseParams, TurnParams |
DeepEval | Old enum names (renamed by 4.0.10) | SingleTurnParams, MultiTurnParams |
additional_metadata= on a test case |
DeepEval | Old field name; accepted as an alias and raises a DeprecationWarning that default filters hide, see 2.2 |
metadata= (a Golden still uses additional_metadata) |
GPTModel(...) |
DeepEval | The OpenAI judge wrapper, old name | OpenAIModel(...) |
ToxicityMetric(threshold=0.2) meaning "at most 20%" |
DeepEval | Pre-4.2.0 direction (also Bias, Hallucination, Misuse) | Higher is better: invert the threshold |
DisplayConfig(display=...) |
DeepEval | The docs' name, never worked | display_option= |
MLLMTestCase |
DeepEval | A separate multimodal case | LLMTestCase with MLLMImage |
AnswerCorrectnessMetric |
DeepEval | Does not exist | A GEval correctness metric |
deepeval.red_teaming (plural), RedTeamer from DeepEval 2.x |
DeepEval | Pre-3.0 module; raises ModuleNotFoundError |
deepeval.red_team (4.3.6 and later) |
from deepteam import ... |
DeepTeam | Works until the deprecation on 30 January 2027 | deepeval.red_team |
handoff_agents= |
DeepEval | The docs' keyword; silently ignored | agent_handoffs= |
Task(plan=...), Plan(...) |
Inspect | Pre-"solver" names; accepted silently | Task(solver=...), chain() |
Task(max_messages=...), Task(tool_environment=...), Task(epochs_reducer=...) |
Inspect | Old arguments; the last is silently ignored without epochs= |
message_limit=, sandbox=, epochs=Epochs(n, reducer) |
multiple_choice(shuffle=True) |
Inspect | Deprecated | shuffle_choices= on the loader |
basic_agent() |
Inspect | Still exported; the docs lead with react() |
react() |
web_browser() |
Inspect | Deprecated in 0.3.272, removed in 0.3.288: the name still imports, calling it raises PrerequisiteError |
web_search() for retrieval; computer() or a browser MCP server in a sandbox (10B.1, 10.2) |
.json logs as the default |
Inspect | .eval has been the default since 0.3.46 |
--log-format json only when you need it |
--max-connections 10 as "the default" |
Inspect | Adaptive concurrency starts at 20 and grows to 100 (since 0.3.217) | Leave adaptive on |
Score(value=NaN) for "could not grade" |
Inspect | A sentinel | Score.unscored(reason=...) |
ci() for accuracies |
Inspect | A t interval that can leave [0, 1] | ci_wilson() |
| A grader panel where "the earliest model wins ties" | Inspect | Changed in 0.3.262 | Strict majority, ties unscored; reducer="mode" for the old rule |
pip install petri |
Inspect ecosystem | A different package | inspect-petri |
| Python 3.10 in setup instructions | Inspect | Below the floor since 0.3.281 | Python 3.11 or newer |
11.2 What moved in 2026#
A dated list of the changes that moved numbers, names or installs. It is a ledger, not a history lesson: the point is to know which of your numbers could have moved when you upgraded.
| Date (2026) | Package | Change | Effect on you |
|---|---|---|---|
| 29 April | Inspect 0.3.214 | Score.unscored() |
Unscored is now a first-class outcome |
| May | DeepEval 4.0 | Major release: an eval harness for coding agents, one-line integrations, a terminal trace viewer | New surface; many renames settled in 4.0.x |
| 8 May | Inspect Evals | New evals live in the contributor's own repository and are registered | Contribution model changed (10B.16) |
| 20 May | Inspect 0.3.224 | pass_k reducer |
Reliability claims have a built-in reducer |
| 11 August | Inspect 0.3.258 | krippendorff_alpha() |
Grader agreement inside Inspect |
| 24 August | DeepEval 4.2.0 | Bias, Toxicity, Hallucination and Misuse flipped to "higher is better" | Old thresholds are inverted; scores of the same text changed meaning |
| 30 August | Inspect 0.3.261 | headline_metric= |
The viewer's headline can be chosen |
| 2 September | Inspect 0.3.262 | ci_wilson(), cascade(), and tied panels are unscored |
Panel results moved; intervals for binary scores |
| 16 September | Inspect 0.3.264 | Tool result review (review=), which fails open where approval fails closed |
Probe every reviewer (10B.15, 9.1) |
| 28 September | Inspect 0.3.272 | web_browser() deprecated |
Plan the move before 0.3.288 |
| 15 October | Inspect 0.3.281 | Python floor 3.11 | CI images and requires-python |
| 16 October | DeepTeam 1.0.10 | Last deepteam release noted in 10B.7 |
Legacy package |
| 6 November | Inspect 0.3.288 | Default model-graded template changed (nonce-coded markers); web_browser() removed |
Re-validate graders; code using the tool breaks |
| 17 November | Inspect 0.3.291 | suspend_cost_limit() and suspend_limits() |
Work inside the context manager is excluded from cost (or every) limit accounting, though still recorded in usage (10B.15, 7.8) |
| 23 November | Inspect 0.3.292 | exclude_samples() and zero_samples() return None; SandboxTimeoutError.reason |
Edit workflows; infrastructure timeouts can be told apart (10B.15, 3.3) |
| 24 November | DeepEval 4.3.5 | Baseline of 10B.2 to 10B.6 | |
| 25 November | DeepEval 4.3.6 | deepeval.red_team and a deepeval red-team CLI: red teaming is back inside DeepEval; trydeepteam.com redirects to the DeepEval docs |
Migrate deepteam imports before 30 January 2027, when the DeepTeam README says the package "will be deprecated" |
The DeepEval 4.3.6 change is the one to act on first, because it has a date attached. Until 4.3.5, red teaming lived in a separate package (deepteam) with its own telemetry (a public IP lookup, Sentry, OTLP and PostHog) and its own documentation. From 4.3.6 it lives in deepeval.red_team: the vulnerabilities, single- and multi-turn attacks, RedTeamer, AgenticRedTeamer, Guardrails and the deepeval red-team command, and DeepEval's own telemetry switch covers it. 10B.7, 1.13 is the migration, with the import changes line by line. A new project should not install deepteam; an old one should migrate, in steps, with the frozen red-team slice as the parity test, well before 30 January 2027. Everything else in this lesson that mentions DeepEval ran against 4.3.6. Two things 4.3.6 did not change: the HumanEval and TruthfulQA MC2 scoring problems of 10B.6, 9.5 and 9.6 are present in both 4.3.5 and 4.3.6, so a fix in a later release would move those benchmark numbers too.
11.3 Dating a tutorial in a minute#
Three questions date almost any snippet. Which names does it use? LLMTestCaseParams is a pre-4.x snippet, deepeval.red_teaming is pre-3.0, Task(plan=...) is a 2024 Inspect snippet. Which numbers does it quote? A Toxicity threshold of 0.2 means "at most 20%" before 4.2.0 and "at least 0.2" now. Which default does it rely on? A snippet that never names a judge, a grader or a model depends on a default that changed or will. Then run it on a frozen fake before you trust it (10B.2, Part 11 and 10B.8, 5.1 show how), and read the installed signature (help(GEval), inspect eval --help) before the docs.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "DeepEval is for products and Inspect is for government safety testing." | Inspect began at a safety institute and is used widely for product evals; DeepEval is used for agents too. The better question is who runs your app and what you need recorded (1.3) |
| "Pick one framework and the other becomes irrelevant." | Neither has between-run statistics or judge calibration, and each is stronger at something the other makes expensive (2.12). "One, plus evalkit" and "both, with owners" are both common answers |
| "If both frameworks score the same eval, their numbers should match." | Cases and deterministic scores should match; headline definitions and judged scores should not, because the prompts, scales and denominators differ (3.1, 3.2) |
| "A built-in metric is validated because it ships in a popular package." | Neither package validates its judges. Every judged number needs calibration against human labels (10A.5) |
"Inspect gives me statistics, so I do not need evalkit." |
Inspect prints a standard error per run. It does not compare two runs, and the apparent improvement of 4.4 was inside the noise |
| "A DeepEval metric cannot be used in Inspect (or the reverse)." | A metric is called from a scorer in a few lines, and an Inspect model can be a DeepEval judge (4.3). The cost is a leaky seam you must close |
"inspect eval failing means CI fails." |
It exits 0 on error status. Gate on the log (4.7) |
| "Migrating means my old numbers will reproduce." | Deterministic checks reproduce exactly on a frozen fake; judged numbers move, and that is expected (5.5) |
"Pinning in pyproject.toml makes results reproducible." |
The lock file pins versions, and the run record ties a number to them. Neither fixes a judge model alias (6.5) |
| "A clean scanner means a clean repository." | A scanner finds text. The silent-denominator and silent-default families are behaviours (8.9) |
| "A traced DeepEval run that reports 100% passed means every component worked." | A caught exception leaves an ERRORED span whose metrics are skipped, and with skip_on_missing_params=True a case can pass with no scored metric at all. Gate on the run file (4.7) |
| "pass@k is pass@k, whichever framework computed it." | It depends on what counts as a success: the reducer's value= in Inspect, the metric's threshold in DeepEval. The same attempts gave 0.467 or 0.8 (2.5) |
Key takeaways#
- Compare the work, not the features. The deciding questions are who runs your app, what you must record, and which of the weekly tasks (write a check, read a failure, gate a pull request, compare two runs, leave) each tool makes cheap.
- DeepEval scores records; Inspect runs recipes. Everything else follows: where agents live, what is logged, what the statistics are, what CI means (Part 2).
- The same eval in both frameworks agrees on cases and disagrees on headlines. Reconcile cases first, aggregates second, and name the question behind every number (Part 3).
- Write the check once. Plain functions, thin wrappers, one definition; the rest of the lesson is cheap if this holds (4.2).
- Seams are small and testable. A DeepEval metric inside an Inspect scorer, Inspect logs into
evalkitstatistics, one judge in both, one run graded by the other's scorers, one fail-closed gate (Part 4). Close the leak: route the judge through the model layer, or accept that its calls are invisible to Inspect. - Migrate by parity. Freeze a baseline, port, and reconcile on a frozen fake; count rows on both sides of any conversion (a loader refused the empty ticket); keep the statistics and the calibration (Part 5).
- Patterns keep the repository honest: checks, adapters, runners and data; one owner per question; smoke, judged and studies tiers; controls; run records; measured upgrades (Part 6).
- Gate on structure, not on the headline. Count scored cases and scored metrics, fail on errored spans and unscored samples, and print the success threshold beside every pass@k; each of these turned a passing number into a failing gate in this lesson (4.7, 2.5).
- Most pitfalls are five families: the silent denominator, the silent default, the silent copy, the wrong layer reported as green, and the moving ground. Ask which family a surprise belongs to first (8.8).
- A number belongs to a version, a judge, a dataset and a denominator. Put them in a record that travels with it (6.5, Part 10).
- Act on dates. DeepEval 4.3.6 brought red teaming back inside the package, and
deepteamwill be deprecated on 30 January 2027; DeepEval 4.2.0 inverted four metrics; Inspect's floor is Python 3.11 (11.2).
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Seam (eval) | A small, tested piece of code joining two tools, such as a wrapper that calls a DeepEval metric from an Inspect scorer |
| Check function | A framework-free function from plain values to (score, reason), wrapped by each framework so that one definition serves all of them |
| Adapter (eval) | The thin wrapper that converts a framework's objects to plain values and back; the only code that imports the framework |
| Judge routing | Making a framework's judge calls go through another framework's model layer (for example a DeepEval judge that is an Inspect grader role), so that concurrency, cache and usage apply |
| Replay solver | An Inspect solver that returns recorded outputs instead of calling a model, so scorers grade answers captured elsewhere |
| Fail-closed gate | A CI gate that treats an empty scan, a vanished case, missing coverage, an errored span or a case with no scored metric as failure and reports every reason |
| One owner per question | The practice of assigning each evaluation question (grounding, agent outcome, version comparison, judge trust) to exactly one tool |
| Smoke, judged and studies tiers | Keyless checks on every pull request, calibrated real-judge runs on a schedule, and on-demand model and agent studies |
| Bake-off | A time-boxed port of one real eval to each candidate framework, measuring the work, the surprises and the exit cost |
| Silent denominator | A pitfall family in which something left the count (unscored, skipped, vanished or errored cases, or metrics skipped while their case still passed) while the headline stayed plausible |
| Silent default | A pitfall family in which a default you did not choose (grader, threshold, judge, target) decided the answer |
| Pitfall family | One of five groupings of the 127 surprises: silent denominator, silent default, silent copy, wrong layer reported as green, moving ground |
| Exit plan | The set of habits (open datasets, plain checks, file-based prompts, archived run records, own statistics) that make leaving a framework a port instead of a rewrite |
Terms defined elsewhere and used here: parity test (eval), reconciliation, oracle run / null run, run record, lock file (10B.1); fake judge (DeepEval), copy rule (10B.2); G-Eval, DeepEvalBaseLLM (10B.3); Solver, Task (Inspect), mockllm (10B.8); Scorer, epochs, reducer (10B.10); panel, grader role (10B.11); errored span (DeepEval) (10B.5); success threshold (pass_at / pass_k), budget curve (10B.16); fail-closed versus fail-open (Inspect controls), approver unit test (10B.15); failing-set diff (10B.1); macro-average, discordant pair (10B.6).
Exercises#
All exercises run keyless, in the eval-lab project, from the throwaway git repository of the Setup. Samples are named by the file names the lesson gives them (each is printed in full where it first appears).
- Scan your own repository (8.9). Run
pitfall_scan.pyover a project of yours that uses either package. How many breaks, warns and reviews does it report? Pick one finding from each severity and say whether it is a real problem. - Predict, then run (10.5). In
triage_data.py, change T05's reply so only itscategoryis wrong. Predict the DeepEval pass rate and both Inspect metrics fortriage_labelsandtriage_format, then runtriage_compare.pyand check. - A third wrapper (4.2). Write an
evalkit-style wrapper (a function returning aScore(name, value, passed, detail)as in 10A.1) overcheck_labels, and show that the three wrappers agree on every ticket. - A retrieval miss (3.2). Add a case to
docsqa_data.pywhere retrieval returns an irrelevant chunk and the app invents an answer instead of abstaining. What do Faithfulness, Answer Relevancy, thegroundedscorer and "matches reference" each say? Which metric or check would flag the retrieval failure? - Close the leak (4.3). In
combo_inspect_model_as_judge.py, predict how manymodelevents one sample has when the metric isAnswerRelevancyMetric(statements, verdicts, reason) instead of Faithfulness. Script the grader for its schemas, then count. - Break the gate (4.7). Add a case to
combined_gate.pywhere the Inspect log has statussuccessbut itstask_versiondiffers from the baseline's. Make the gate return that as a problem. - The loader bug (5.2). Reproduce the
No input in datasetfailure with a one-row file whose input is empty, then fix it with arecord_to_samplefunction. Why is "count rows on both sides" the right guard? - A paired comparison on DeepEval output (4.4). Run the DeepEval triage eval twice with the v2 replies of
combo_logs_to_evalkit.py, build{case: score}dictionaries fromresult.test_results, and feed them topaired_diffsandpaired_bootstrap_ci. Does the interval agree with the Inspect-based one? - Five teams (9.4). Pick one team from the table and write the one-paragraph rationale a skeptical staff engineer would accept: the named gap, the owner of each question, the first week's plan, the exit test.
- Date a snippet (11.3). A tutorial shows
from deepeval.red_teaming import RedTeamer,DisplayConfig(display="all"),ToxicityMetric(threshold=0.2)andTask(plan=[generate()], max_messages=10). Say roughly when each line was written, what it means today, and what you would change. - Gate a traced run (4.7). In
gate_traced.py, change the agent's fallback toanswer = f"Order {order_id} is unknown."and keep only run A. Predict DeepEval's verdict and every reason the gate prints, then run it. - Move a threshold (2.5). In
reliability_both.py, change T3's credits to[0.5, 1.0, 0.5, 0.5]. Predict pass@2, pass^2 and the mean credit at both thresholds before you run it. Which numbers move, and why does one of them not?
Answers
- Open ended. On the lesson's fixture the scanner reports 7 breaks, 7 warns and 5 reviews. In real repositories the reviews are usually the most interesting, because a
model_graded_fact()with nomodel=is a real bug only when nograderrole is bound, andfail_on_error=Falseis acceptable only with a coverage gate. - DeepEval: 9 of 12 cases pass (75.0%), because T05 fails the labels metric (a score of 0.667 against a threshold of 1.0). The format mean stays 0.917. The labels mean falls from 0.889 to 0.861 (one ticket loses a third of a point, and a third divided by twelve is 0.028). Inspect:
triage_formataccuracy stays 0.917;triage_labelsmean 0.861. The failing set becomes T02, T05, T11 in both. - The wrapper takes the reply, the reference and the metadata, calls
check_labels, and returnsScore("triage_labels", value, value == 1.0, reason). All three wrappers call the same function with the same arguments, so they cannot disagree; a disagreement means a wrapper converts its inputs wrongly (the usual culprit isallow_empty_summaryread from metadata under a different key or type). - Faithfulness and
groundedboth fail the invented answer (it is not supported by the irrelevant chunk). Answer Relevancy probably passes (the answer addresses the question). "Matches reference" fails it. The failing retrieval is caught by a retrieval check: DeepEval'sContextualRecallMetricagainst the expected answer, or a deterministic test that the gold chunk id is in the retrieved set. That is why 3.2 says neither generation-side metric catches a retrieval failure. - One model event for the app's answer, plus one per judge request that DeepEval makes for the metric, so the count is 1 plus the number of judge calls. Run it and compare with the
FakeJudgecall counts of 2.4 (three for Answer Relevancy with a normal answer, plus any extra). If your count differs, a request is being retried or skipped. - Compare
log.eval.task_version(and the epochs and reducers inlog.eval.config) with the baseline's, and add a message such astask_version 2 differs from the baseline's 1to the problems list. The point is that a paired comparison across task versions is meaningless, and the gate is the cheapest place to refuse it (10B.10, 8.3). - A file with one JSON object whose
inputis""fails injson_dataset(path, FieldSpec(input="input", ...))and in the defaultjson_dataset(path)(andcsv_datasetlikewise) withNo input in dataset, and loads withrecord_to_samplereturningSample(input=rec["input"], ...). The guard works because the failure mode that matters is a loader that drops or refuses edge cases, so the dataset on one side of a conversion no longer equals the dataset on the other. Row counts, and the set of ids, catch this without knowing what went wrong. - The DeepEval per-case score for a metric is
m.score; the dictionaries are{t.name: m.score}for the labels metric. The paired difference is the same as in the Inspect run, because the labels check is the same function over the same replies: +0.083, with a 95% interval from about -0.056 to +0.250 on the lesson's seed. If your intervals differ, check that you joined on the case name and used the sameitersandseed. - Open ended. A strong answer names one gap per tool added, assigns each question an owner (6.2), starts with a frozen fake and a parity test (5.5), and schedules the exit test of 5.6.
deepeval.red_teamingis a pre-3.0 module and raisesModuleNotFoundError; usedeepeval.red_teamfrom 4.3.6 (and install nothing nameddeepteamin a new project).DisplayConfig(display=...)is the docs' name and aTypeError; the field isdisplay_option.ToxicityMetric(threshold=0.2)means "at most 20% toxic" before 4.2.0 and "at least 0.2 clean" now, a much weaker gate, so choose a high threshold calibrated on labelled examples.Task(plan=...)is a 2024 spelling accepted silently, andmax_messagesis the old name ofmessage_limit: writeTask(solver=[generate()], message_limit=10).- DeepEval: 2 of 3 cases pass, because the new fallback no longer equals the expected answer for
flaky, so Exact Match fails it. The gate prints two reasons for the same case:flaky: failedandflaky: tool span 'lookup' ERRORED. (Output of the modified sample, real:DeepEval: 2 of 3 cases passed | gate -> FAIL ['flaky: failed', "flaky: tool span 'lookup' ERRORED"].) The point is that a failing case and a crashed component are two findings: fixing the wording of the fallback would make the first reason disappear and leave the crash, which is why the gate reports both instead of stopping at the first. - At threshold 1.0, T3 now has one full success in four attempts, so its pass@2 becomes
1 - C(3,2)/C(4,2) = 0.5(was 0) and its pass^2 stays 0. The means become pass@2(1 + 5/6 + 0.5 + 0.5 + 0) / 5 = 0.567and pass^2 0.233 (unchanged), in both frameworks. At threshold 0.5 nothing moves (T3 already counted four successes): 0.8 and 0.6. The mean credit rises by 0.5 / 20 to 0.55. The modified sample printed exactly these numbers. pass^2 does not move because one success in four still gives no pair of successes, which is the "pass^k punishes inconsistency" reading of 10B.16, 4.7.
Check yourself#
- What are the four ways a framework comparison goes wrong, and what corrects each?Comparing defaults with a best case (compare like with like); comparing numbers and not definitions (name the question behind each number); comparing features and not the work around them (compare the weekly tasks); comparing versions you did not name (date and version every statement) (1.1).
- In one sentence each, what are DeepEval's and Inspect's units of work, and who runs your application in each?DeepEval: a test case (a finished record) scored by metrics; you run your app. Inspect: a task (dataset, solver, scorer) with the log as the product; Inspect runs the solver (1.3).
- Why is "metric" a dangerous word on a team that uses both frameworks?DeepEval's metric is an object that scores one case; Inspect's metric is a function over all the scores, and the thing that scores one sample is a scorer. People then describe different objects with one word (2.3).
- In the
docs_qacomparison, why did Faithfulness (0.6) and the hand-writtengroundedscorer (0.6) agree while "matches reference" (0.4) did not?Faithfulness andgroundedask the same question (is every claim supported by the retrieved text?) and agree on q02 and q06; "matches reference" asks whether the answer equals the expert's, so the faithful abstention on q05 fails it (3.2). - Why can a DeepEval metric inside an Inspect scorer overrun a judge's rate limit even though Inspect is configured conservatively, and how do you fix it?DeepEval calls its judge itself, outside Inspect's model layer, so Inspect's concurrency limits, retries, cache and usage accounting do not apply. Make the judge an Inspect model (a
DeepEvalBaseLLMthat callsget_model(role="grader")) (4.3). - Which five rules of 4.3 must a DeepEval metric called from an Inspect scorer follow?Build a fresh metric per sample inside the scorer; pass the judge explicitly; use
a_measure; make any scripted judge order-independent; translate the result (value, reason, metadata) and do not hide it (4.3). - Why does Inspect's printed improvement of 0.889 to 0.972 not justify a release decision, and which tool answers the question?The difference is within the noise: the paired 95% interval is -0.056 to +0.250 and 12 tickets cannot detect a paired effect below about 0.23.
evalkit's paired bootstrap over the per-sample scores answers the question (4.4). - What does it mean to "write the check once", and why does it make migration cheap?
- What is the parity protocol, in order, and what does each kind of difference usually mean?Same data, same fakes, cases before aggregates (failing set, then per-case scores, then headlines), then classify each difference: different failing cases (wrapper or data), same cases with different headline (definitions), different judged scores (not a bug: validate and re-baseline), different counts (a loader or skip), run-to-run variation (noise) (5.5).
- What did the dataset bridge sample find about empty inputs, and what is the general guard?Inspect's declarative loaders (
FieldSpecor the default mapping, for CSV and JSON) refuse an emptyinputstring (No input in dataset), while aSample(input="")built in code and arecord_to_samplefunction keep it. The guard is to count rows (and ids) on both sides of any conversion (5.2). - Name the five pitfall families with one example each.Silent denominator (unscored samples leave the count); silent default (the grader is the model under test); silent copy (async metric rebuild, cached scores); wrong layer reported as green (
inspect evalexits 0 on error); moving ground (the 4.2.0 flip, thedeepteamdeprecation) (8.8). - Why does the combined gate fail a run whose printed labels mean is 0.879 and above the threshold?A scorer crashed on one ticket and errors were tolerated, so the mean was over 11 samples; the gate checks coverage (11 of 12 scored), not just the printed number (4.7).
- What is the date by which a project should have migrated off
deepteam, and what replaces it?30 January 2027 (the DeepTeam README says the package will be deprecated then). It is replaced bydeepeval.red_team, available from DeepEval 4.3.6 (25 November 2026), with adeepeval red-teamCLI (11.2). - List five things a run record should carry.Python and package versions; the version of the checks; the dataset identity (name, rows, hash); the judge identity (model snapshot, settings, rubric version); the named number with its denominator (6.5).
- When is "use both" the wrong answer?
- How can a traced DeepEval run report 3 of 3 cases passed while no metric scored anything, and which two checks in a gate catch the two traps of 4.7?The golden's
expected_outputwas not copied into the trace, so Exact Match lacked a required field; underskip_on_missing_params=Trueit was skipped on every case,metricsDatawas empty, and DeepEval still counted each case as passed. Separately, a caught tool exception left anERROREDspan. The gate counts scored metrics per case (catches the first) and fails on any span whose status isERRORED(catches the second), both read from.deepeval/.latest_test_run.json(4.7). - A team ports a reliability eval from DeepEval (a metric with
threshold=0.5, four repeated runs) to Inspect'spass_at(2)with four epochs. pass@2 falls from 0.8 to 0.467 with no change to the agent. Why, and what is the fix?The definition of success changed. DeepEval counted an attempt as a success when its metric reached 0.5; Inspect'spass_at(2)counts it only atvalue=1.0by default, so every half-done attempt became a failure. Setpass_at(2, value=0.5)(andpass_k) to keep the old definition, or decide on purpose that success means full credit, and print the threshold beside the number either way (2.5).
Further resources#
- DeepEval documentation: deepeval.com/docs/getting-started, Evaluation introduction, Unit testing in CI/CD, Data privacy and the changelog (it can lag PyPI).
- Inspect documentation: inspect.aisi.org.uk, Scorers and model-graded scoring, Eval logs, Eval sets, Agents and the CHANGELOG.
- Repositories and releases: confident-ai/deepeval, UKGovernmentBEIS/inspect_ai, PyPI: deepeval and PyPI: inspect-ai. PyPI release history is the source of truth for what shipped.
- DeepTeam migration: github.com/confident-ai/deepteam (the README carries the migration table and the 30 January 2027 deprecation notice), and 10B.7, 1.13.
- Confident AI pricing (dated 24 November 2026; re-read before you budget): confident-ai.com/pricing.
- Inside this module: 10A.5 (judge calibration), 10A.8 (paired statistics and CI), 10A.10 (the tool landscape and
evalkitAppendix A), and, for the LangChain stack, 11A.5 and 08F.15, whose patterns, anti-patterns and migration playbook this lesson follows. - Next: 10B.18 maps both packages' official documentation, changelogs and repositories, with a reading plan.
← 10B.16: Evaluating Agents with Inspect, and the Inspect Ecosystem (optional) | Module 10B overview | 10B.18: Finish Learning DeepEval and Inspect from the Official Docs →