10B.8 Inspect AI Fundamentals: Task = Dataset + Solver + Scorer (optional)

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

Inspect is the open-source evaluation framework from the UK AI Security Institute (developed together with Meridian Labs): a Python library, a command line and a log viewer that together run an eval, record everything that happened, and let you read it back. Its whole design rests on one sentence: an evaluation is a Task, and a task is a dataset of samples, a solver that turns each sample into model output, and one or more scorers that judge the output. This lesson teaches that mental model properly and then makes it concrete: you install the package, run a first eval with no API key, rebuild the ticket-triage eval from 10A.1 as an Inspect task, reconcile its numbers with evalkit's to the third decimal, learn the difference between inspect eval and eval(), find out where the logs go and what is inside them, open them in Inspect View, read them back in Python, and map every piece onto the evalkit harness you already own. Every sample runs on your machine with Inspect's built-in mock model, and every output shown is what those runs printed. The six Inspect lessons after this one go deep on each component; this one gives you the whole shape in one sitting, plus the traps people hit on their first day.

What you'll learn

  • What Inspect is, who builds it, its licence, its release cadence and version policy, and what uv add inspect-ai does and does not install
  • The mental model: Task = Dataset + Solver + Scorer, logs as the product, and a task as a recipe whose ingredients (model, limits, epochs, solver) are swapped at run time
  • What happens inside one eval run, step by step: TaskState, the solver chain, generate(), scorers, epoch reduction, metrics and the log
  • How to run an eval with no API key using mockllm/model, both with its fixed default reply and with a scripted model you write
  • The triage eval from 10A.1 and 10A.10 rebuilt in Inspect, run keyless, and its numbers reconciled with evalkit's (83.3% pass rate, 0.903 mean score)
  • inspect eval file.py versus file.py@task, task parameters with -T, inspect list tasks, and the day-one flags
  • eval() in Python: what it accepts, why it returns list[EvalLog], and when to use eval_async() instead
  • Where logs go, how they are named, .eval versus .json, inspect view, the VS Code extension, and inspect view bundle for sharing
  • Reading a log back: list_eval_logs, read_eval_log (with and without header_only), results, samples, scores, reductions, single-sample reads, inspect log dump and inspect log export-config
  • The complete evalkit ↔ Inspect mapping, including the places where defaults differ, and what 10A.10's Inspect section now gets wrong
  • Methodology from the first run: oracle and null controls, reading transcripts, scored_samples, and what a 12-sample standard error does and does not tell you
  • The first-day pitfalls, each reproduced: every task in a file runs, a Task-level model beats --model, single braces in templates are silently mangled, an empty target passes everything, mock token counts are fake, inspect eval exits 0 on a failed run, and logs record your git remote

What you don't need

  • An API key. Every runnable sample uses mockllm/model, Inspect's built-in fake provider, and the outputs are real. The only illustrative samples are the ones that name a real provider, and they are labelled.
  • Docker, a server or a hosted service. Nothing in this lesson starts one: inspect view is described but not run, and inspect view bundle writes static files.
  • Depth on each component. Datasets, solvers and task configuration are 10B.9; scorers, metrics, epochs and Inspect's statistics are 10B.10; model grading is 10B.11; models, concurrency, caching, error policy and eval sets are 10B.12; logs, dataframes and extending Inspect are 10B.13; tools, agents and sandboxes are 10B.14 to 10B.16. This lesson previews each in a sentence or two and links.
  • The eval concepts themselves. Datasets, graders, judges, statistics and CI gates were taught framework-free in 10A.1 to 10A.8; here they are mapped onto Inspect, not re-taught. 10B.1 explains why you would adopt a framework at all and how Inspect compares with DeepEval.

Setup

You need Python 3.11 or newer (Inspect itself requires it) and uv. If you have not set up a uv project before, 01B.1 and 03.1, Part 4 walk through it.

bash
uv init inspect-lab --bare --python 3.13 && cd inspect-lab   # first time only
uv add inspect-ai
# or: pip install inspect-ai

That is everything the runnable samples need. For the illustrative real-provider runs in 4.9 you would also add the provider's own SDK (uv add openai or uv add anthropic; the optional Gemini needs uv add google-genai, and the optional OpenRouter goes through openai) and a key in .env; nothing else in the lesson needs either. Save each sample under the file name its first comment gives, all in one folder, and run Python files with uv run python file.py and CLI commands with uv run inspect ... from that folder.

Versions (current at time of writing, read from PyPI on 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT licence, Python ≥ 3.11). Inspect is still on 0.x and ships a patch release every few days, and those releases can carry breaking changes, so treat the version as a snapshot and see 1.2 for how to upgrade on purpose. Every sample marked as run was executed on 24 November 2026 with Python 3.13.14 and inspect-ai 0.3.292, using uv run --no-project --with inspect-ai (plus python for scripts and inspect for the CLI), and the output blocks are what those runs printed, trimmed only where marked. The official documentation and the installed package source were checked the same day.


What you must be able to do after this lesson#

  • Explain Task = Dataset + Solver + Scorer and what is deliberately not part of a Task
  • Install Inspect and make a first keyless run with mockllm/model
  • Rebuild the triage eval as an Inspect task
  • Run it with inspect eval and with eval(), and run only one task from a file
  • Find the log file and read it back with read_eval_log(path, header_only=True)
  • Decide which of the printed accuracies is the one you report

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Inspect is the AISI framework. Is it for safety research or for products?" 1.1 and 1.4
"Pin it: Inspect breaks things in patch releases." 1.2
"A task is just dataset plus solver plus scorer." Part 2
"Run it with mockllm first, before you spend money." 3.3
"Port the triage eval to Inspect and check the numbers match." Part 4
"Why did inspect eval run three tasks when I wanted one?" 5.1
"I passed --model but it used the other model." 5.6
"Where did the logs go?" 6.1
"Just open it in Inspect View." 6.3
"Share the results with the team, but not our repo URL." 6.4
"Pull the scores out of the log for the report." Part 7
"How does this map to evalkit?" Part 8
"The CI job was green, but the eval had crashed." 9.6
"Can we trust a 0.917 from twelve samples?" Part 10

Part 1: What Inspect is#

1.1 A framework, a command line and a log viewer#

"Inspect" names three things that ship together in one package:

Piece What it is What you do with it
The Python framework (inspect_ai) Classes and decorators for defining evals: Task, Sample, solvers, scorers, metrics, plus the engine that runs them and the API that reads logs Write @task functions in ordinary .py files; run them from Python with eval(); read results with read_eval_log()
The command line (inspect) A CLI installed with the package: inspect eval, inspect view, inspect log, inspect list, inspect score, inspect eval-set, inspect eval-retry, inspect cache and more Run tasks against any model, list tasks, inspect and convert logs, re-score old runs
Inspect View A web viewer for log files, started with inspect view (local only, by default) or built into the VS Code extension Browse results, filter samples by score, read every message and event of every sample

Around this core sits an ecosystem that later lessons cover: Inspect Evals, a separate package of 200-plus ready-made benchmark tasks (10B.16); a sandboxing system for running model-written code safely (10B.15); built-in tools, agents and MCP support (10B.14); and companion packages from Meridian Labs (Inspect Viz for plots, Inspect Scout for transcript analysis, Inspect Flow for large sweeps) that 10B.16 surveys.

The docs' own one-line summary is the one to remember: an Inspect evaluation is a Task that brings together a Dataset of labelled samples, a Solver that produces an answer for each sample ("as simple as a single generate() call to the model, or as sophisticated as a full agent that uses tools over many turns"), and a Scorer that evaluates the output "using text comparisons, model grading, or other custom schemes".

1.2 Who builds it, the licence and the release cadence#

These facts are volatile; each is dated and each has a place to re-check it.

Fact (as of 24 November 2026) Value Where to check
Maintainer Created by the UK AI Security Institute (UK AISI), which holds the copyright and is the PyPI author. The docs home page says Inspect is "developed by the UK AI Security Institute and Meridian Labs"; Meridian Labs publishes the companion packages (Viz, Scout, Flow) and recent changelog entries reference its repository inspect.aisi.org.uk, GitHub
Licence MIT ("Copyright (c) 2024 UK AI Security Institute") the LICENSE file on GitHub
Package inspect-ai on PyPI; import name inspect_ai; CLI command inspect pypi.org/project/inspect-ai
Current version 0.3.292, released 23 November 2026 PyPI, or uv run inspect --version
Cadence A patch release every few days: 0.3.288 (7 November), .289 (10th), .290 (14th), .291 (17th), .292 (23rd); 25 releases between 22 September and 23 November 2026 the CHANGELOG
Version policy Still 0.x. Releases that look like patches can contain a Breaking Changes section (0.3.292 itself changed what two log-editing functions return) the CHANGELOG, release by release
Python 3.11 or newer, since 0.3.281 (15 October 2026), which also started testing on 3.14 PyPI requires_python
First release 0.0.1 on PyPI, 3 April 2024 PyPI release history
Log format version EvalLog.version == 2 any log you read back

Three habits follow from that table. Pin the version you validated. In a uv project the lock file (uv.lock) already pins it; commit it. The course rule is that install commands carry no version pins, so pinning is the lock file's job, not the install command's. Upgrade on purpose, one step at a time, after reading the Breaking Changes sections of every release in between, and re-run a known eval to compare numbers (10A.8, 8.4 is the playbook). Date every Inspect fact you write down, including the ones in this lesson.

1.3 What uv add inspect-ai installs, and what it does not#

The core install is deliberately broad. Among its dependencies (as of 0.3.292): pydantic (every log and config type is a Pydantic model), anyio and httpx (the async engine and HTTP), fsspec, s3fs and universal-pathlib (logs and datasets can live on S3 and other filesystems), textual and rich (the terminal display), fastapi and uvicorn (the inspect view server), tiktoken (token counting), python-dotenv (.env loading), zstandard (log compression) and numpy (metrics).

What it does not install surprises people:

Not included Why it matters What to add
Provider SDKs --model openai/... fails until the SDK is present: Inspect drives each provider through that provider's own Python package openai (also used for the optional OpenRouter and many OpenAI-compatible services), anthropic, the optional google-genai, and so on per providers
pandas and pyarrow The dataframe functions in inspect_ai.analysis (evals_df(), samples_df()) check for them at call time and fail without them uv add pandas pyarrow (10B.13)
The math() scorer's parser math() raises a PrerequisiteError without its optional dependencies uv add "inspect-ai[math]" (10B.10)
datasets (Hugging Face) hf_dataset() needs it uv add datasets (10B.9)
Docker or other sandboxes Only agent tasks that run model-written code need one 10B.15

The only optional extra a user installs is math (the package also defines dev, doc and dist extras, which are for Inspect's own developers).

The VS Code extension is separate: search the marketplace for "Inspect AI". It adds a Logs pane that opens logs in the viewer, Run Task and Debug Task buttons (Cmd+Shift+U and Cmd+Shift+T on macOS), a Tasks panel listing every @task in the workspace, and a Configuration panel that edits the workspace .env. Debug Task adds --limit 1 automatically (a setting named "inspect debug" turns that off). The extension uses the workspace's Python interpreter, so inspect-ai must be installed in that environment. It is recommended by the docs but not required by anything in this track; this lesson uses the terminal throughout.

1.4 What Inspect is for, and what that means for a product team#

Inspect was built by a government lab to test frontier models for dangerous capabilities and to measure agentic behaviour, and its feature set shows it: sandboxes for untrusted code, agents and tools as first-class citizens, 200-plus benchmark implementations (with categories such as cybersecurity, scheming and safeguards), transcripts of every model call, and a written scoring policy that separates failures of the model from failures of the grader. None of that stops a product team from using it, and most of it helps.

Inspect is strong at Inspect is weaker at (or leaves to you)
Agentic and multi-turn evals, tool use, sandboxed code execution A pytest-style "assert this metric ≥ threshold" workflow (DeepEval's home ground, 10B.2)
Reproducible runs: the log records the task, solver chain, scorer, model, config, git commit and package version Paired comparisons between two runs, multiple-comparison corrections, power analysis (do these on the log data with 10A.8's tools; 10B.10 shows how)
Reading what happened: the transcript viewer is the best in the open-source field for long, tool-heavy runs Ready-made RAG metrics (faithfulness and friends): you write the scorers or reuse 10A.6's
Running the same task across many models and configurations, with retries and resumable eval sets A hosted UI for non-engineers, annotation queues, online evaluation of production traffic (10A.9, 10A.10)
Benchmarks: 200-plus implementations you can run as-is Human-label calibration of judges (that is 10A.5's job; 10B.11 connects the two)
Being free, MIT-licensed and local: logs are files you own Stability: 0.x with frequent releases means you must pin and upgrade deliberately

What this means for you as an engineer: Inspect is the natural choice when your evals are research-shaped (agents, tools, long transcripts, many models, reproducibility) and a reasonable choice for any single-turn product eval, because the triage-style task you will build in Part 4 is a few dozen lines. It is a harness, not a platform: you still own the dataset design, the scorer definitions and the statistics, exactly as in 10A.1 to 10A.8. 10B.17 compares it with DeepEval on every axis.

1.5 The design ideas you will meet everywhere#

Four ideas run through the docs and the API. Recognizing them makes every later page easier to read.

  1. A task is a recipe, not a run. A @task function returns a Task object that describes what to evaluate. The model, the number of epochs, the sample limit, the error policy and much else are chosen when you run it. The docs phrase it as: "A task definition provides defaults for everything an evaluation needs". The same task file runs against ten models without edits.
  2. Logs are the product. Every run writes a log file that records the configuration and every sample's messages, model calls, scores and timings. The terminal summary is a convenience; the log is the artefact you analyse, share, re-score and compare (Part 6, Part 7).
  3. Tasks should be solver-agnostic. In the docs' words, "it is often desirable to design tasks that can work with any solver so that you can experiment with different strategies". The dataset and scorer define the measurement; the solver is the thing being measured, so you can swap it from the command line.
  4. Measurement honesty is explicit. The scoring-policy page treats a model-graded scorer as part of "the measurement instrument", so an unparseable answer from the model counts against the model while an unparseable verdict from the grader is left out of the denominator and reported separately. The models page warns that "temperature is not random assignment". You will meet this attitude again in 10B.10 and 10B.11.

Part 2: The mental model: Task = Dataset + Solver + Scorer#

2.1 The three ingredients#

Think of a task as a recipe. The dataset is the list of dishes to cook (each with a photo of what it should look like), the solver is the cooking method, the model is the cook you hire on the day, and the scorer is the taster who compares each plate with the photo. You write the recipe once; you can hire a different cook, or try a different method, without rewriting it.

flowchart LR
    subgraph task ["Task: the recipe you write once"]
        DS["Dataset<br/>list of Sample<br/>input, target, id, metadata"]
        SV["Solver chain<br/>prompt_template, system_message,<br/>generate, agents..."]
        SC["Scorer(s)<br/>Score per sample<br/>plus their metrics"]
    end
    M["Model<br/>chosen at run time<br/>--model provider/name"]
    DS -->|"each Sample becomes a TaskState"| SV
    M -.->|"generate() calls it"| SV
    SV -->|"final TaskState"| SC
    SC --> AGG["Reduce epochs, then metrics<br/>accuracy, mean, stderr"]
    AGG --> LOG[("EvalLog<br/>.eval file in ./logs")]
    SV -.->|"messages, events, usage"| LOG
    LOG --> VIEW["inspect view, Python log API,<br/>dataframes, your CI gate"]

Each ingredient has one core type:

  • Dataset: a list of Sample. A Sample (from inspect_ai.dataset) holds an input (a string, or a list of chat messages), a target (the ideal answer, a list of acceptable answers, or grading guidance for a model grader; it defaults to the empty string), an optional id, optional metadata (a dict your solvers and scorers can read), and for multiple-choice tasks choices. A task accepts a plain Python list of samples, a MemoryDataset, or a dataset loaded from CSV, JSON, JSON Lines or Hugging Face (10B.9).
  • Solver: a function that transforms a TaskState. For each sample, Inspect builds a TaskState: the conversation so far (state.messages, which starts as the sample's input), the latest model reply (state.output), the sample's metadata, a per-sample key-value store, and more. A solver is an async function solve(state, generate) -> state. Some solvers only reshape the conversation (system_message() adds a system prompt, prompt_template() rewrites the user prompt); generate() calls the model and appends its reply. A list of solvers runs in order as a chain. An agent is just a solver that loops (10B.14). If you give no solver at all, the default is generate(): send each sample to the model once.
  • Scorer: a function from the final state and the target to a Score. A scorer is an async function score(state, target) -> Score. The Score carries a value (by convention "C" for correct and "I" for incorrect, or a number, or a dict), the answer it extracted from the output, an explanation, an optional machine-readable reason, and metadata. Each scorer also declares the metrics computed over all its scores, such as accuracy() and stderr(). Inspect ships text scorers (includes(), match(), exact(), pattern(), answer(), f1(), choice(), math()) and model-graded scorers (model_graded_qa(), model_graded_fact()), and you write your own for anything else (10B.10, 10B.11).

The model is deliberately not one of the three. It is chosen at run time with --model provider/name (or eval(model=...)), and generate() calls whichever model is active. That single design choice is what lets one task file compare models.

2.2 Decorators and the registry#

Every ingredient is written as a factory: an ordinary function, wrapped in a decorator, that returns the thing Inspect runs.

python
# anatomy.py: the shape of each ingredient (lesson 10B.8)
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Scorer, Target, accuracy, scorer, stderr
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver


@solver
def add_policy(policy: str) -> Solver:          # a factory: plain def, takes options
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state.user_prompt.text = f"{policy}\n\n{state.user_prompt.text}"
        return state                            # a solver always returns the state
    return solve                                # ...and the factory returns the async function


@scorer(metrics=[accuracy(), stderr()])         # metrics are declared on the scorer
def says_refund() -> Scorer:
    async def score(state: TaskState, target: Target) -> Score:
        answer = state.output.completion
        ok = target.text.lower() in answer.lower()
        return Score(value=CORRECT if ok else INCORRECT, answer=answer)
    return score


@task                                           # registers the recipe by its function name
def refunds() -> Task:
    return Task(
        dataset=[Sample(id="r1", input="I was charged twice.", target="refund")],
        solver=[add_policy("Refunds are allowed within 30 days."), generate()],
        scorer=says_refund(),
    )

Why factories? Because the outer function's arguments are options (policy, a template, a threshold) that Inspect records in the log, and that you can override from the command line (--solver add_policy -S policy=..., 10B.9). The inner async def is what runs per sample. The decorators register each factory by name, so the log says "solver add_policy with policy='Refunds are allowed within 30 days.'" rather than "some function". Two rules from this shape cause most first-day errors:

  • The inner function must be async def; a plain def is rejected with TypeError: '...' is not declared as an async callable. (9.4).
  • The outer factory must be a plain def. An async def factory returns a coroutine instead of a scorer, a mistake 10A.10's failure gallery already recorded.

2.3 What happens in one run#

When you run inspect eval triage.py --model mockllm/model, this is what Inspect does (from the docs and the behaviour you will see in the logs):

flowchart TB
    START(["inspect eval triage.py --model mockllm/model"]) --> RESOLVE["Resolve task, model, config<br/>Task defaults, then .env/env vars (CLI),<br/>then CLI flags or eval() args"]
    RESOLVE --> PER["For each Sample x epoch<br/>run concurrently"]
    PER --> INIT["TaskState from Sample<br/>messages = input as a user message"]
    INIT --> SETUP["setup solvers, if any"]
    SETUP --> CHAIN["solver chain in order<br/>each gets state and generate"]
    CHAIN --> GEN["generate: call the model,<br/>append reply, set state.output"]
    GEN --> DONE{"more solvers and<br/>not completed?"}
    DONE -->|"yes"| CHAIN
    DONE -->|"no"| SCORE["every scorer: score(state, target)"]
    SCORE --> CLEAN["cleanup, if any"]
    CLEAN --> WRITE["sample written to the log<br/>incrementally"]
    WRITE --> ALL{"all samples done?"}
    ALL -->|"no"| PER
    ALL -->|"yes"| REDUCE["reduce epochs per sample<br/>default reducer: mean"]
    REDUCE --> METRICS["metrics per scorer x reducer"]
    METRICS --> FINAL[("EvalLog finalized<br/>status success or error")]

In words, for each sample and each epoch (a repeat of the whole sample; one by default):

  1. A TaskState is created from the Sample. A string input becomes one user message.
  2. Any setup solvers run (they run even if you swap the main solver from the command line).
  3. The solver chain runs in order. Each solver receives the state and a generate function. When a solver calls generate(state), Inspect sends state.messages to the active model, appends the reply and sets state.output. If a solver sets state.completed = True, or a sample limit is reached, the remaining solvers are skipped.
  4. Every scorer runs on (state, target) and returns a Score (or None, or an "unscored" result, or raises: the scoring policy in 10B.10 says what each means).
  5. Any cleanup function runs, even after an exception.
  6. The sample, with its messages, events, scores and timings, is written to the log as the run goes (in batches; a crash loses little).

After every sample has finished, each sample's epoch scores are reduced to one value (the default reducer is the mean), and each scorer's metrics are computed over those reduced values. The log is then finalized with a status of success or error.

Samples run concurrently. Inspect is built on asyncio (through anyio), and while one sample waits for the model, others proceed. By default it starts at 20 in-flight requests per model, grows towards 100 while the provider keeps up, and backs off (to as few as 10) on rate-limit retries (10B.12); the progress line's mockllm: 0/20 shows that limit.

2.4 Logs are the product#

Every inspect eval and every eval() writes one log file per task and model, by default under ./logs in the current directory. The log is not a text dump: it is a structured EvalLog holding the task's identity and version, the solver chain with arguments, the scorers and metrics, the model and generation settings, the run configuration (limits, epochs, error policy, sample ids), the git commit of your working directory, the Inspect version, and, for every sample, every message sent and received, the raw model call, token usage, timings, errors, the store, and every score with its explanation. Part 6 and Part 7 open one.

What this means for you as an engineer: treat the log directory the way you treat a database of test results. Results you quote should come from a log (with its file name), comparisons should be between logs, and a CI gate should read the log rather than the terminal output (9.6). That is the same discipline evalkit's JSONL rows taught in 10A.1, with far more detail per row.

2.5 A recipe with swappable ingredients: the override layers#

Almost every setting can be given in four places. From lowest to highest precedence, as the tasks page lists them:

Layer How you set it Typical use
1. The Task definition Task(epochs=3, message_limit=20, config=GenerateConfig(...)) Defaults the task author thinks are right
2. task_with() task_with(my_task(), solver=..., scorer=...) Building a variant of someone else's task in Python (note: it edits the task in place)
3. Environment (CLI) .env or shell INSPECT_EVAL_* variables; read by the inspect command, while eval() reads only INSPECT_EVAL_MODEL and a few INSPECT_* settings such as INSPECT_LOG_DIR Per-machine or per-project defaults
4. eval() or the CLI eval(task, epochs=5), inspect eval task.py --epochs 5 Per-run choices: model, limits, sample selection

Three exceptions are worth knowing before they bite. The dataset, scorer and metrics can only be set on the Task or with task_with(): there is no command-line flag that swaps the scorer, because the scorer is the definition of the measurement. Some run-time choices exist only on eval() or the CLI (limit, sample_id, retry_on_error, score). And, as you will see for real in 5.6, a model set on the Task is used even when you pass --model, which is not what the precedence table suggests. 10B.9 covers every row of the docs' override reference and the run-config file that captures a whole configuration.

2.6 Async under the hood#

Solvers and scorers are async def because Inspect interleaves many samples on one event loop. You do not need deep async knowledge to write them, but you need two rules (the "why" is 01B.3):

  • await every model call (await generate(state), await get_model().generate(...)). The docs give the reason: awaiting is how "the solver participates correctly in the scheduling".
  • Never block the loop with long synchronous work (a time.sleep, a blocking HTTP client, a heavy CPU loop) inside a solver or scorer: every other sample waits while it runs.

2.7 The 10A.1 anatomy, in Inspect's words#

10A.1, 2.1 stripped every eval framework to five components. Here is where each lives in Inspect:

10A.1 component Inspect Note
Dataset Task(dataset=...): a list of Sample Same idea; target is 10A.1's reference
Task (the system under test) The solver chain plus the model chosen at run time Inspect's word "Task" means the whole recipe, not the system under test; see the fresher note in 2.1
Scorer(s) Task(scorer=...): one or a list of @scorer factories Each scorer has its own metrics
Aggregation Epoch reducers, then metrics (accuracy(), mean(), stderr()...) Reported per scorer, not combined across scorers
Report The EvalLog (plus the terminal panel and Inspect View) Far richer than EvalReport: full transcripts and config

Part 3: Install and a first keyless run#

3.1 Install and check#

After uv add inspect-ai (Setup), check what you got:

bash
uv run inspect --version
uv run inspect --help
Output · real, --help trimmed to the command list16 lines
0.3.292
Commands:
  acp         Connect to a running Inspect eval over the Agent Client...
  cache       Manage the inspect model output cache.
  ctl         Read and direct running evals and manage kept-alive processes.
  download    Inspect-managed binary downloads.
  eval        Evaluate tasks.
  eval-retry  Retry failed evaluation(s).
  eval-set    Evaluate a set of tasks with retries.
  info        Read configuration and log info.
  list        List tasks on the filesystem.
  log         Query, read, and convert logs.
  sandbox     Manage Sandbox Environments.
  score       Score a previous evaluation run.
  trace       List and read execution traces.
  view        Inspect log viewer.

This lesson uses eval, list, log and view. eval-retry, eval-set, cache and ctl belong to 10B.12, score to 10B.11, and sandbox to 10B.15. inspect <command> --help is the authoritative list of flags for the version you have installed; the docs describe the latest release, which may be ahead of yours.

3.2 Hello, Inspect#

The smallest task worth running has two samples, a two-step solver and a built-in scorer:

python
# hello.py: the smallest useful Inspect task (lesson 10B.8)
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import generate, system_message


@task
def hello(greeting: str = "Hello") -> Task:
    return Task(
        dataset=[
            Sample(id="h1", input=f"{greeting}! Reply with the words 'default output'.",
                   target="default output"),
            Sample(id="h2", input="Reply with the single word: banana", target="banana"),
        ],
        solver=[system_message("You are terse."), generate()],
        scorer=includes(),
    )

Line by line: @task registers hello as a task; the greeting argument is a task parameter you can set from the command line. The dataset is a plain list of two Samples with explicit ids. The solver chain adds a system message and then calls the model once. includes() scores a sample correct ("C") when the target text appears anywhere in the model's reply, ignoring case, and comes with the metrics accuracy() and stderr().

Run it against the mock model:

bash
uv run inspect eval hello.py --model mockllm/model --display plain
Output · real19 lines
Running 1 tasks...
---------------------------------------------------------
hello (2 samples): mockllm/model
dataset: (samples)
---------------------------------------------------------

generate     | Steps:   2/2 100% | Samples:   2/  2 | accuracy:  n/a | mockllm:  0/20 | HTTP retries: 0

---------------------------------------------------------
hello (2 samples): mockllm/model
dataset: (samples)

total time:              0:00:00
mockllm/model            93 tokens [I: 27, O: 66]
includes
accuracy  0.500
stderr    0.500
Log: logs/2026-11-24T16-28-40-00-00_hello_dZuaRfShj6rDge9vSDgUWf.eval
---------------------------------------------------------

(The first line printed was Monitor from another shell: inspect ctl task list (inspect ctl --help), a hint about the control channel that every run prints; it is left out of the outputs in this lesson.)

--display plain prints plain progress lines, which is what you want in a terminal log or CI. Without it you get the default interactive full-screen display; --display none prints nothing, and conversation prints each sample's messages as they happen, which is handy when debugging a single sample.

3.3 mockllm/model: the fake provider that makes keyless runs possible#

Why 0.500? Because mockllm/model is a built-in fake model provider that, unless told otherwise, answers every request with the same text: Default output from mockllm/model. Sample h1's target, default output, appears in that reply (case is ignored), so it scores C; banana does not, so h2 scores I. One of two is 0.5.

The mock is the backbone of keyless work in Inspect, so know its behaviour precisely (read from the installed source of 0.3.292; the docs mention it only in CLI help examples):

Behaviour Detail
Model string mockllm/model. The provider is mockllm; the name after the slash is free text (mockllm/other behaves the same)
Default reply Every call returns Default output from mockllm/model with stop reason stop
Scripted replies Pass custom_outputs as a model argument: get_model("mockllm/model", custom_outputs=...)
custom_outputs forms A list (or other iterable) of ModelOutput objects, consumed in order, raising ValueError("custom_outputs ran out of values") when exhausted; a generator; or a function (input, tools, tool_choice, config) -> ModelOutput, sync or async
Usage numbers Synthesized: input tokens from Inspect's token counter, output tokens = the number of characters of the reply (9.5)
Transcript It records the request like a real provider, so the log and the viewer look the same as for a real run
Concurrency Same default as real providers (the 0/20 in the progress line)

Its sibling, --model none (or eval(model=None)), selects a provider that raises an error on any generate() call. Use it for tasks that only call role models, or to prove that a task makes no default-model calls.

What this means for you as an engineer: the mock answers every call, including calls from model-graded scorers and agents. That makes it the tool for testing the plumbing of a task (does the dataset load, does the solver chain run, does the scorer parse, where do logs go) before you spend a cent. What it cannot test is anything about a real model's behaviour; for that you need a real provider (4.9).

3.4 Reading the results panel#

The panel at the end of a run is a summary of the log, line by line:

Line Meaning
hello (2 samples): mockllm/model Task name, how many samples ran, which model
dataset: (samples) The dataset's name; a plain list of samples has none, a file-loaded dataset shows its name. Task parameters appear here too when set (greeting: Hi, dataset: (samples))
total time Wall-clock time of the task
93 tokens [I: 27, O: 66] Usage per model: input and output tokens. With the mock these are not real tokens (9.5)
includes The scorer's name; its metrics are listed under it
accuracy 0.500 The mean of the per-sample values after converting C to 1 and I to 0
stderr 0.500 The standard error of that mean: the sample standard deviation divided by the square root of the number of samples. With values 1 and 0 the standard deviation is 0.707 and √2 is 1.414, so 0.5. It is the size of the uncertainty, not a confidence interval (Part 10 of this lesson)
Log: logs/...eval Where the full record went (6.1)

Try a task parameter. -T sets an argument of the @task function, and the @hello suffix selects that task from the file:

bash
uv run inspect eval hello.py@hello --model mockllm/model -T greeting=Hi --display plain
Output · real, trimmed to the lines that changed4 lines
hello (2 samples): mockllm/model
greeting: Hi, dataset: (samples)
accuracy  0.500
Log: logs/2026-11-24T16-32-06-00-00_hello_S8HRxH7hMTsYZ3na5VCx4K.eval

The parameter is recorded in the log (task_args), so a later reader can see that this run said "Hi" instead of "Hello".

3.5 Scripting the mock#

A mock that always says the same thing is enough for plumbing, but to see a scorer pass and fail on realistic answers you script it. The function form is the one to use:

text
def my_model(input: list[ChatMessage], tools, tool_choice, config: GenerateConfig) -> ModelOutput

input is the list of messages Inspect would send to a real provider (system, user, assistant and tool messages), so input[-1].text is the latest user message after your solvers have shaped it. Return ModelOutput.from_content(model="mockllm", content="...") for a text reply (ModelOutput.for_tool_call(...) exists for agent tests, 10B.14). Then bind it:

text
model = get_model("mockllm/model", custom_outputs=my_model, memoize=False)
eval(my_task(), model=model)

memoize=False asks get_model() for a fresh Model object instead of a cached one with the same arguments. In inspect-ai 0.3.292 mockllm models are never memoized anyway, so for the mocks in this track the flag is harmless but unneeded; it matters for real providers, where 10B.12, 2.4 explains the cache.


Part 4: The triage eval, rebuilt in Inspect#

4.1 The fixture and the plan#

The best way to learn a framework is to port an eval whose numbers you already know. 10A.1, Part 6 built triage_eval.py: twelve support tickets for "Acme Cloud", a prompt that asks for a JSON object with a priority (P1/P2/P3), a category and a one-sentence summary, two scorers (format, the contract, and labels, correctness with partial credit), and a deliberately imperfect fake model that gets T02 wrong and wraps T11's answer in prose. Its real output was pass rate 83.3%, mean score 0.903, failing examples T02 and T11.

This part ports it piece by piece, keeping the data, the prompt, the scoring rules and the fake model's answers identical, so that any difference in the numbers is a difference in how the framework counts, not in what was measured. 10A.10, 4.4 sketched a smaller Inspect version with one exact-match scorer; this one is complete, and it runs.

The plan, file by file:

File Contents evalkit counterpart
triage.py The dataset, the prompt, the two scorers and the @task EXAMPLES, PROMPT_TEMPLATE, triage_task, format_scorer, label_scorer in triage_eval.py
fake_triage.py The scripted mock model FakeTriageModel
run_triage.py Runs the task from Python and prints the results main() with run_eval() and summary()
triage_scripted.py A variant that makes the task runnable keyless from the CLI (none)

triage.py only defines things; it never runs an eval when imported. Keep task files that way: the CLI imports them, inspect eval-retry re-imports them, and a task file that runs an eval at import time breaks both (10B.12 shows the error).

4.2 The dataset#

Here is the first part of triage.py. The twelve tickets are exactly 10A.1's, as tuples of id, text, reference and metadata, converted to Samples:

python
# triage.py: the ticket-triage eval of lesson 10A.1, rebuilt as an Inspect task (lesson 10B.8)
"""Same twelve tickets, same prompt, same two scorers as evalkit's triage_eval.py.

Import-safe on purpose: this module only *defines* the task. Running it is
the job of the `inspect eval` CLI or of run_triage.py.
"""
from __future__ import annotations

import json
import re

from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (CORRECT, INCORRECT, Score, Scorer, Target,
                               accuracy, mean, scorer, stderr)
from inspect_ai.solver import TaskState, generate, prompt_template

# ---------------------------------------------------------------------------
# Dataset: (id, ticket text, reference "<priority>|<category>", metadata)
# ---------------------------------------------------------------------------
TICKETS: list[tuple[str, str, str, dict[str, str]]] = [
    ("T01", "Hi, I was charged twice for my pro plan this month and nobody has "
            "responded to my emails for days. This is really frustrating and I "
            "want my money back. Also is there any discount if I stay?",
     "P2|billing", {"intent": "billing", "edge": "multi-intent"}),
    ("T02", "Our whole team can't log in since this morning. Dashboard shows "
            "a 500 error on every page. We're losing sales every hour.",
     "P1|technical", {"intent": "technical", "edge": "outage"}),
    ("T03", "How do I add a second admin to our Team plan? The docs mention "
            "it but I can't find the button.",
     "P3|account", {"intent": "account", "edge": "how-to"}),
    ("T04", "I think someone hacked my account. I got a password-reset email "
            "I didn't request and now I see charges I don't recognise.",
     "P1|account", {"intent": "account", "edge": "security"}),
    ("T05", "When will my order ship? I ordered the standing desks two weeks "
            "ago and tracking hasn't updated.",
     "P2|shipping", {"intent": "shipping", "edge": "stale-tracking"}),
    ("T06", "Your mobile app crashes every time I open the reports tab on "
            "Android 15. I've reinstalled twice.",
     "P2|technical", {"intent": "technical", "edge": "bug-report"}),
    ("T07", "Thanks for the quick fix last week — everything works now. "
            "Just wanted to say the support was great.",
     "P3|other", {"intent": "other", "edge": "no-request"}),
    ("T08", "I want to downgrade from Team to Pro at the end of this billing "
            "cycle. Will I lose my historical data?",
     "P3|billing", {"intent": "billing", "edge": "downgrade"}),
    ("T09", "URGENT: all our API calls are returning 403 since your deploy "
            "last night. This is blocking our production launch tomorrow.",
     "P1|technical", {"intent": "technical", "edge": "outage"}),
    ("T10", "", "P3|other",
     {"intent": "other", "edge": "empty", "allow_empty_summary": "1"}),
    ("T11", "pls refnd my dupolicate charge on the pro plan, its the second "
            "time this month and support hasnt replied",
     "P2|billing", {"intent": "billing", "edge": "typos"}),
    ("T12", "Bonjour, je voudrais savoir si je peux exporter mes données "
            "avant de résilier mon abonnement Team. Merci!",
     "P3|account", {"intent": "account", "edge": "non-english"}),
]


def triage_samples() -> list[Sample]:
    """One Sample per ticket. Explicit ids keep runs comparable and retryable."""
    return [Sample(id=tid, input=text, target=ref, metadata=meta)
            for tid, text, ref, meta in TICKETS]

Three choices to notice:

  • target keeps 10A.1's "P2|billing" format. Inspect does not care what the target string looks like; only your scorer interprets it. A built-in text scorer such as includes() would compare the whole string against the output, which is why this task needs custom scorers.
  • Explicit ids. Without them, Inspect numbers samples 1, 2, 3 when the eval runs. Explicit, stable ids are what make results comparable between runs, let you select samples with --sample-id T02, and let retries reuse completed samples (10B.9).
  • metadata carries the slice axes (intent, edge) and the empty-ticket rule (allow_empty_summary). Solvers can render metadata into prompts, scorers read it through state.metadata, and the dataframes in 10B.13 turn it into columns you can group by. (Inspect's built-in way to report a metric per slice is the grouped() metric, 10B.10.)

The empty ticket T10 is a legal Sample: its input is an empty string, which the solver below wraps in the prompt template, so the model still receives a full prompt.

4.3 The solver: the same prompt, and the brace rule#

10A.1's triage_task() rendered a template with str.format(ticket=...). Inspect's equivalent is the built-in solver prompt_template(), which replaces the user message with a template in which {prompt} stands for the current prompt text (here, the ticket):

python
# ---------------------------------------------------------------------------
# Solver: the same prompt as 10A.1. prompt_template() replaces the user message
# with this text; {prompt} is the sample input (the ticket). Literal JSON braces
# are doubled, exactly as with str.format().
# ---------------------------------------------------------------------------
PROMPT_TEMPLATE = """\
# Task
Triage a customer support ticket for Acme Cloud. Assign a priority, a
category, and a one-sentence summary for the on-call engineer.

# Rules
- priority: "P1" only for outages, data loss, security incidents or legal
  threats; "P2" for anything needing action this week; "P3" for questions
  and low-impact issues. When in doubt between P2 and P3, choose P2.
- category: exactly one of "billing", "technical", "account", "shipping",
  "other".
- summary: one sentence, under 25 words, naming the concrete issue.
- If the ticket is empty, return {{"priority": "P3", "category": "other",
  "summary": ""}}.

# Output format
Reply with ONLY a JSON object, no prose, no markdown fences:
{{"priority": "P1"|"P2"|"P3", "category": "billing"|"technical"|"account"|"shipping"|"other", "summary": "<one sentence>"}}

# Ticket
<ticket>
{prompt}
</ticket>
"""

The template is 10A.1's, with one change: {ticket} became {prompt}, the variable prompt_template() provides. Every other placeholder that Inspect's template solvers fill comes from the sample's metadata, the per-sample store, or keyword arguments you pass to the solver: prompt_template(PROMPT_TEMPLATE, product="Acme Cloud") would fill a {product} placeholder.

Look at the doubled braces in the JSON examples: {{"priority": ...}}. Inspect's template solvers use Python's str.format rules, so a literal { must be written {{. 10A.1's template already had them, because it also went through str.format(), which is why it ports unchanged. If you paste a JSON example with single braces into an Inspect template, it is not an error: it is silently mangled, and your model receives a broken instruction. 9.2 reproduces it; check the prompt as sent (in the log or the viewer) every time you write a template.

4.4 The scorers#

The two scorers are 10A.1's format_scorer and label_scorer with Inspect's signature. Here is the middle part of triage.py:

python
# ---------------------------------------------------------------------------
# Scorers: evalkit's format_scorer and label_scorer, ported.
# ---------------------------------------------------------------------------
CATEGORIES = {"billing", "technical", "account", "shipping", "other"}
PRIORITIES = {"P1", "P2", "P3"}


def parse_json(text: str) -> dict | None:
    """The tolerant extractor from 10A.1: strip fences, take the first {...}."""
    fence = chr(96) * 3  # chr(96) is a backtick; three of them make a Markdown code fence
    text = re.sub(fence + 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


@scorer(metrics=[accuracy(), stderr()])
def triage_format() -> Scorer:
    """Gate 1, the contract: a JSON object with exactly the three valid fields."""

    async def score(state: TaskState, target: Target) -> Score:
        output = state.output.completion
        obj = parse_json(output)
        if obj is None:
            return Score(value=INCORRECT, answer=output,
                         explanation="no JSON object found",
                         reason="invalid_response_format")
        problems = []
        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")
        if problems:
            return Score(value=INCORRECT, answer=json.dumps(obj),
                         explanation="; ".join(problems),
                         reason="invalid_response_format")
        return Score(value=CORRECT, answer=json.dumps(obj), explanation="ok")

    return score


@scorer(metrics=[mean(), stderr()])
def triage_labels() -> Scorer:
    """Gate 2, correctness with partial credit: priority, category and summary
    are one third each. The value is a float in [0, 1], so the metric is mean()."""

    async def score(state: TaskState, target: Target) -> Score:
        obj = parse_json(state.output.completion)
        if obj is None:
            return Score(value=0.0, answer=state.output.completion,
                         explanation="unparseable output",
                         reason="invalid_response_format")
        want_priority, want_category = target.text.split("|")
        allow_empty = state.metadata.get("allow_empty_summary") == "1"
        summary = obj.get("summary", "")
        checks = {
            "priority": obj.get("priority") == want_priority,
            "category": obj.get("category") == want_category,
            "summary": ((summary == "" and allow_empty)
                        or (isinstance(summary, str)
                            and 0 < len(summary.split()) < 25)),
        }
        wrong = [name for name, ok in checks.items() if not ok]
        return Score(
            value=sum(checks.values()) / len(checks),
            answer=f"{obj.get('priority')}|{obj.get('category')}",
            explanation="ok" if not wrong else f"wrong: {', '.join(wrong)}",
            metadata={"checks": checks},
        )

    return score

What changed in the port, and why:

evalkit (10A.1) Inspect port Why
def format_scorer(example, output) -> Score async def score(state, target) -> Score inside an @scorer factory Inspect's scorer protocol; the factory carries the metrics
output (a string) state.output.completion The scorer sees the whole TaskState: messages, metadata, store, output
example.reference target.text Target can hold a list of acceptable answers; .text joins them, which is fine for one
example.metadata state.metadata The sample's metadata travels with the state
Score("format", 1.0, True, "ok") Score(value=CORRECT, answer=..., explanation="ok") Inspect's Score has no name (the scorer's registered name is used) and no separate passed flag: the value is the verdict
passed=False with a detail string value=INCORRECT, explanation=..., reason="invalid_response_format" reason is a machine-readable label from Inspect's scoring-policy vocabulary; it shows up in the viewer and in dataframes
A float in [0, 1] for labels A float in [0, 1], with mean() as the metric accuracy() would also accept floats, but mean() names what the number is

Two habits the docs recommend and this port follows. Always return an answer: it is the extracted thing that was compared, and without it a reviewer in the viewer sees only "I" and has to dig through the transcript to learn why. Use explanation for the human reason and metadata for structured detail (here, the three checks), so that later analysis does not have to parse strings.

4.5 The task#

The last lines of triage.py put the ingredients together:

python
@task
def triage() -> Task:
    return Task(
        dataset=triage_samples(),
        solver=[prompt_template(PROMPT_TEMPLATE), generate()],
        scorer=[triage_format(), triage_labels()],
        version=1,
        metadata={"source": "lesson 10A.1 triage_eval.py"},
    )

The four code blocks of 4.2 to 4.5, in order, are the complete triage.py. scorer= takes a list, and each scorer gets its own results and metrics. version is yours to bump whenever you change the dataset, the prompt or a scorer in a way that makes old numbers incomparable; it is logged as task_version, and a comparison between runs with different versions should be refused, the same rule 10A.2, 6.3 set for datasets. metadata is free-form and logged.

Notice what is not here: no model, no epochs, no limits. Those are chosen per run.

4.6 The scripted model#

fake_triage.py is 10A.1's FakeTriageModel as a mockllm function, with the same twelve answers:

python
# fake_triage.py: 10A.1's FakeTriageModel as a mockllm/model script (lesson 10B.8)
"""A deterministic stand-in for a real model, so the eval runs with no API key.

mockllm/model accepts `custom_outputs`: here a function that receives the
messages Inspect would send to a provider and returns a ModelOutput. Keying the
reply on the ticket text (not on call order) keeps it correct when Inspect runs
samples concurrently.
"""
from inspect_ai.model import ChatMessage, GenerateConfig, Model, ModelOutput, get_model

from triage import TICKETS

RESPONSES = {
    "T01": '{"priority": "P2", "category": "billing", "summary": "Duplicate Pro charge, refund requested."}',
    "T02": '{"priority": "P2", "category": "billing", "summary": "Login outage reported."}',  # wrong on purpose
    "T03": '{"priority": "P3", "category": "account", "summary": "How to add a second admin."}',
    "T04": '{"priority": "P1", "category": "account", "summary": "Suspected account takeover."}',
    "T05": '{"priority": "P2", "category": "shipping", "summary": "Order tracking stale two weeks."}',
    "T06": '{"priority": "P2", "category": "technical", "summary": "App crashes on reports tab."}',
    "T07": '{"priority": "P3", "category": "other", "summary": "Customer thank-you, no request."}',
    "T08": '{"priority": "P3", "category": "billing", "summary": "Downgrade and data-retention question."}',
    "T09": '{"priority": "P1", "category": "technical", "summary": "API 403s blocking launch."}',
    "T10": '{"priority": "P3", "category": "other", "summary": ""}',
    # prose wrapping an incomplete JSON fragment: a format failure on purpose
    "T11": 'Sure! This looks like a billing issue, I would mark it P2. '
           'Here is the JSON you asked for: {"priority": "P2"}',
    "T12": '{"priority": "P3", "category": "account", "summary": "Data export before cancelling Team plan."}',
}


def fake_triage(input: list[ChatMessage], tools, tool_choice,
                config: GenerateConfig) -> ModelOutput:
    prompt = input[-1].text            # the last user message, as rendered by the solver
    reply = RESPONSES["T10"]           # the empty ticket matches nothing below
    for tid, text, _ref, _meta in TICKETS:
        if text and text in prompt:
            reply = RESPONSES[tid]
            break
    return ModelOutput.from_content(model="mockllm", content=reply)


def scripted_model() -> Model:
    # memoize=False: always build a fresh Model rather than reusing a cached one
    return get_model("mockllm/model", custom_outputs=fake_triage, memoize=False)

The function looks the ticket text up in the rendered prompt, the same trick 10A.1's fake used, so the answer for each sample does not depend on which order Inspect happens to call it in. T02's answer is wrong on both labels, T11's is prose around an incomplete JSON fragment, and T10 (the empty ticket) gets the empty-summary answer.

4.7 Running it from Python#

python
# run_triage.py: run the triage task keyless and read the result (lesson 10B.8)
from inspect_ai import eval
from inspect_ai.scorer import CORRECT

from fake_triage import scripted_model
from triage import triage

if __name__ == "__main__":
    logs = eval(triage(), model=scripted_model(),
                log_dir="logs-triage",          # its own folder, so later reads find it
                display="none")
    log = logs[0]                               # one EvalLog per task x model
    print("logs returned:", len(logs), "| status:", log.status)
    print("log file:", log.location.rsplit("/", 1)[-1])
    for s in log.results.scores:               # one EvalScore per scorer (x reducer)
        metrics = {name: round(m.value, 3) for name, m in s.metrics.items()}
        print(f"{s.name:14} scored={s.scored_samples}  {metrics}")

    print()
    for sample in log.samples:
        fmt, lab = sample.scores["triage_format"], sample.scores["triage_labels"]
        note = "" if lab.value == 1 else f"  labels: {lab.explanation}"
        if fmt.value != CORRECT:
            note += f"  | format: {fmt.explanation}"
        print(f"{sample.id}  format={fmt.value}  labels={lab.value:.3f}{note}")

    # evalkit's headline numbers, recomputed from the same per-sample scores
    rows = [(s.scores["triage_format"].value, s.scores["triage_labels"].value)
            for s in log.samples]
    passed = [fmt == CORRECT and lab == 1.0 for fmt, lab in rows]
    per_row = [((1.0 if fmt == CORRECT else 0.0) + lab) / 2 for fmt, lab in rows]
    print(f"\nevalkit-style pass rate: {sum(passed) / len(rows):.1%}"
          f"   mean score: {sum(per_row) / len(rows):.3f}")
bash
uv run python run_triage.py
Output · real19 lines
logs returned: 1 | status: success
log file: 2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval
triage_format  scored=12  {'accuracy': 0.917, 'stderr': 0.083}
triage_labels  scored=12  {'mean': 0.889, 'stderr': 0.075}

T01  format=C  labels=1.000
T02  format=C  labels=0.333  labels: wrong: priority, category
T03  format=C  labels=1.000
T04  format=C  labels=1.000
T05  format=C  labels=1.000
T06  format=C  labels=1.000
T07  format=C  labels=1.000
T08  format=C  labels=1.000
T09  format=C  labels=1.000
T10  format=C  labels=1.000
T11  format=I  labels=0.333  labels: wrong: category, summary  | format: keys=['priority']; category=None; summary not a string
T12  format=C  labels=1.000

evalkit-style pass rate: 83.3%   mean score: 0.903

Read it like an engineer:

  • eval() returned a list with one EvalLog. One task, one model, one log. Pass two tasks or two models and you get one log per combination (5.4).
  • status: success means the run completed. It does not mean the model did well; a run in which every sample scores zero is still a success. A run that crashed is error (9.6).
  • Two results, one per scorer. triage_format reports accuracy 0.917 (11 of 12) and triage_labels reports a mean of 0.889. Each has its own standard error.
  • The per-sample table is the report that matters. Exactly two samples are imperfect: T02 (both labels wrong, so a third of the credit, for the summary) and T11 (format failure, and only the priority right). The explanations say why without opening the transcript.
  • display="none" silenced the progress display so the script's own prints are the only output; log_dir="logs-triage" put this run's log in its own folder so that Part 7 can find it without picking up the other runs in ./logs.

4.8 Reconciling the numbers with evalkit#

10A.1 reported pass rate 83.3%, mean score 0.903. Inspect reports 0.917 and 0.889. Nothing is wrong: they are different aggregations of the same twenty-four per-sample scores.

Number How it is computed Value
Inspect triage_format accuracy Mean over samples of the format verdict (C = 1, I = 0) 11/12 = 0.917
Inspect triage_labels mean Mean over samples of the labels value (10 × 1 + 2 × 1/3) / 12 = 0.889
evalkit pass rate Share of rows where every scorer passed (format C and labels 1.0) 10/12 = 83.3%
evalkit mean score Mean over rows of the mean of the two scorers' values ((11 + 10.667) / 2) / 12 = 0.903

The last line of the output recomputes evalkit's two numbers from Inspect's per-sample scores and gets exactly 83.3% and 0.903. The ported eval measures the same thing; the frameworks summarize it differently.

The lesson to keep: Inspect has no built-in "a sample passes only if all its scorers pass" aggregate. Each scorer stands alone. If your release gate is "pass rate across all checks", either compute it from the log as run_triage.py does, or write one combined scorer that returns C only when every check passes, or use multi_scorer() with a reducer that takes the minimum (10B.10). Decide which, and write it down, before anyone compares an Inspect number with an evalkit one.

4.9 The same task against a real model#

With a key, the identical task runs against any supported provider; only the --model string and the provider SDK change. Inspect's model strings are provider/model-name, and each provider reads its key from its own environment variable (the provider pages are the authority, and they change; as of November 2026):

Provider Model string SDK to add Key variable
OpenAI openai/gpt-6-luna openai OPENAI_API_KEY
Anthropic anthropic/claude-haiku-5-5 anthropic ANTHROPIC_API_KEY
Google Gemini (optional) google/gemini-3.8-flash google-genai GOOGLE_API_KEY (the docs name only this; 0.3.292 also accepts the course's GEMINI_API_KEY through the google-genai SDK, and GOOGLE_API_KEY wins if both are set)
OpenRouter (optional) openrouter/openai/gpt-6-luna (any vendor/model from the catalogue) openai OPENROUTER_API_KEY
bash
# illustrative: needs a key in .env and the provider SDK
uv add openai
uv run inspect eval triage.py --model openai/gpt-6-luna --display plain
Example output · illustrative11 lines
---------------------------------------------------------
triage (12 samples): openai/gpt-6-luna
dataset: (samples)

total time:             0:00:09
openai/gpt-6-luna       5,210 tokens [I: 3,343, O: 1,867]
triage_format         triage_labels
accuracy       1.000  mean           0.944
stderr         0.000  stderr         0.038
Log: logs/2026-11-24T17-02-11-00-00_triage_Kx2...eval
---------------------------------------------------------

Several models in one run: --model openai/gpt-6-luna,anthropic/claude-haiku-5-5 produces one log per model. Inspect loads .env from the current directory (searching parent directories), so the same .env file that held keys in Module 03 works here, including the Google key (Inspect documents GOOGLE_API_KEY but also accepts GEMINI_API_KEY). Do not set temperature out of habit: many current models reject it and Inspect drops it with a warning (10B.12 covers generation settings and what each provider honours).

4.10 Running it from the command line, keyless#

From the CLI, a scripted mock cannot be passed as a flag (-M takes strings, not Python functions), so --model mockllm/model gives you the fixed default reply:

bash
uv run inspect eval triage.py --model mockllm/model --display plain
Output · real, results panel only11 lines
---------------------------------------------------------
triage (12 samples): mockllm/model
dataset: (samples)

total time:           0:00:01
mockllm/model         3,739 tokens [I: 3,343, O: 396]
triage_format         triage_labels
accuracy       0.000  mean           0.000
stderr         0.000  stderr         0.000
Log: logs/2026-11-24T16-29-57-00-00_triage_WPz4dL57nvhrYqGVSFPeqx.eval
---------------------------------------------------------

Zero on both scorers, as it should be: Default output from mockllm/model is not JSON. This is a useful run in its own right, the null run of Part 10: it proves the task loads, the prompt renders, the scorers execute and reject garbage.

To run the scripted mock from the CLI, make it the task's own model in a small variant file:

python
# triage_scripted.py: the triage task with the scripted model as its default (lesson 10B.8)
from inspect_ai import Task, task, task_with

from fake_triage import scripted_model
from triage import triage


@task
def triage_scripted() -> Task:
    # task_with() edits the Task it is given (in place) and returns it.
    # A model set on the Task is used even when --model is given (see 5.6).
    return task_with(triage(), model=scripted_model(), name="triage_scripted")
bash
uv run inspect eval triage_scripted.py --display plain
Output · real, results panel only11 lines
---------------------------------------------------------
triage_scripted (12 samples): mockllm/model
dataset: (samples)

total time:             0:00:00
mockllm/model           4,375 tokens [I: 3,343, O: 1,032]
triage_format         triage_labels
accuracy       0.917  mean           0.889
stderr         0.083  stderr         0.075
Log: logs/2026-11-24T16-38-36-00-00_triage-scripted_3xvogAgCu2FMsTZRADPbdk.eval
---------------------------------------------------------

No --model was needed: the task carries one. The same numbers as the Python run, as they must be. (Notice the log name: underscores in the task name become hyphens.) The comment in the file warns about a trap: a model set on the Task is used even when you pass --model, which 5.6 demonstrates. That is fine for a keyless-only variant like this one and a bug anywhere else.


Part 5: Running evals: inspect eval and eval()#

5.1 What inspect eval accepts#

The first argument of inspect eval says which tasks to run. The forms you will use:

Form What runs
inspect eval triage.py Every @task in the file
inspect eval triage.py@triage Only the task named triage in that file
inspect eval evals/ Every task found by scanning the directory recursively (files and folders starting with . or _, and folders named env, venv or tests, are skipped)
inspect eval inspect_evals/gpqa_diamond A task registered by an installed package, here the Inspect Evals benchmark package (10B.16)
inspect eval hf/OpenEvals/aime_24 A task published as a Hugging Face dataset with an eval.yaml (10B.9)
inspect eval a.py b.py@x Several of the above

The first row is a classic surprise. Here is a file with two tasks:

python
# two_tasks.py: one file, two tasks (lesson 10B.8)
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes, match


@task
def greet(greeting: str = "Hello") -> Task:
    return Task(dataset=[Sample(id="g1", input=f"{greeting}!", target="output")],
                scorer=match())          # no solver given: the default is generate()


@task
def banana() -> Task:
    return Task(dataset=[Sample(id="b1", input="Say banana", target="banana")],
                scorer=includes())
bash
uv run inspect eval two_tasks.py --model mockllm/model -T greeting=Hi --display plain
Output · real, trimmed to the lines that matter9 lines
[11/24/26 22:00:09] WARNING  param 'greeting' not used by task   registry.py:170
                             'banana'
Running 2 tasks...
greet (1 sample): mockllm/model
greeting: Hi, dataset: (samples)
banana (1 sample): mockllm/model
...
Log: logs/2026-11-24T16-30-10-00-00_greet_aGnGKBWfTWe3Anjg4oEobT.eval
Log: logs/2026-11-24T16-30-10-00-00_banana_e9NHhpXfKkAf3rUAcs57oS.eval

Both tasks ran, and the parameter meant for one of them produced only a warning for the other (the warning's timestamp is in the machine's local time). With paid models that is a doubled bill. Make it a habit to name the task: two_tasks.py@greet. To see what a file or folder contains before running it:

bash
uv run inspect list tasks
Output · real, run in the folder holding this lesson's files5 lines
hello.py@hello
triage.py@triage
triage_scripted.py@triage_scripted
two_tasks.py@banana
two_tasks.py@greet

inspect list tasks also takes paths, --json for machine-readable output, and -F key=value to filter on attributes you attach with @task(light=True) and the like (10B.12 uses this for eval sets).

5.2 Task parameters with -T#

A task parameter is any argument of the @task function. Use them for anything a caller might reasonably want to vary without editing the file: the system prompt variant, a dataset split or path, a difficulty filter, a grader model name. Four ways to set them:

Where Syntax
CLI, one at a time -T greeting=Hi -T split=test (repeatable)
CLI, from a file --task-config params.yaml (YAML or JSON with the same keys)
Python, through eval() eval("hello.py@hello", task_args={"greeting": "Hi"})
Python, directly eval(hello(greeting="Hi")): call the function yourself

The values are recorded in the log as task_args (all arguments, defaults included) and task_args_passed (only the ones you set), which is how a reader later tells two variants apart.

python
# task_args_check.py: task_args on a built Task vs by name; what the log records (lesson 10B.8)
from inspect_ai import eval

from hello import hello

if __name__ == "__main__":
    built = eval(hello(), task_args={"greeting": "Hi"}, model="mockllm/model",
                 log_dir="logs-args", display="none")[0]
    named = eval("hello.py@hello", task_args={"greeting": "Hi"}, model="mockllm/model",
                 log_dir="logs-args", display="none")[0]
    for label, log in (("built Task", built), ("by name", named)):
        print(f"{label:10} task_args={log.eval.task_args} passed={log.eval.task_args_passed}"
              f" | first input: {log.samples[0].input[:12]!r}")
bash
uv run python task_args_check.py
Output · real2 lines
built Task task_args={'greeting': 'Hello'} passed={} | first input: 'Hello! Reply'
by name    task_args={'greeting': 'Hi'} passed={'greeting': 'Hi'} | first input: 'Hi! Reply wi'

The built task ran with "Hello" and no warning appeared on the console in this run (the source contains a warning for this case, but it did not fire for eval() here). The log is honest about it, though: task_args_passed is empty. When a variant's numbers look identical to the baseline's, check that field first.

5.3 The flags you need on day one#

inspect eval --help lists well over a hundred options. These are the ones worth knowing from the first day; each later lesson adds its own.

Flag What it does More in
--model provider/name The model under test; a comma-separated list runs each 10B.12
-T key=value A task parameter 5.2
--limit 10, --limit 10-20 Run only the first 10 samples, or samples 10 to 20 10B.9
--sample-id T02,T11 Run only these samples (globs such as 'T1*' work) 10B.9
--epochs 3 Run every sample three times and reduce (default: mean) 10B.10
--log-dir DIR Where to write the log (default ./logs) Part 6
--display plain / none / conversation How much to print while running 3.2
--no-fail-on-error Keep going when a sample raises (the default stops the task at the first error) 9.6, 10B.12
--max-connections N A hard cap on concurrent model requests (turns adaptive concurrency off) 10B.12
--model-role grader=provider/name Bind a named role, such as the grader model 10B.11
--no-score Generate now, score later with inspect score 10B.11
--log-format json Write a .json log instead of .eval 6.2

5.4 eval() in Python#

eval() is the Python twin of inspect eval, with (almost) every CLI flag as a keyword argument:

python
# multi_eval.py: two tasks x two models in one eval() call (lesson 10B.8)
from inspect_ai import eval

from hello import hello
from two_tasks import banana

if __name__ == "__main__":
    logs = eval(
        [hello(), banana()],                        # keep the list homogeneous (see 9.7)
        model=["mockllm/model", "mockllm/other"],   # two "models"
        log_dir="logs-multi",
        display="none",
    )
    print("logs returned:", len(logs))
    for log in logs:
        acc = log.results.scores[0].metrics["accuracy"].value
        print(f"  {log.eval.task:7} {log.eval.model:14} accuracy={acc:.2f}  {log.status}")
bash
uv run python multi_eval.py
Output · real5 lines
logs returned: 4
  hello   mockllm/model  accuracy=0.50  success
  banana  mockllm/model  accuracy=0.00  success
  hello   mockllm/other  accuracy=0.50  success
  banana  mockllm/other  accuracy=0.00  success

What to know about eval():

  • It returns list[EvalLog], one per task × model: two tasks and two models gave four logs. Always index or loop; never assume one.
  • tasks accepts many shapes: a Task object, a @task function (uncalled), a string ("hello.py@hello", a directory, a registered name), a list of these, or previous logs (for retries). Keep a list homogeneous: in 0.3.292 a list whose first element is a Task silently drops any strings that follow it (9.7).
  • model accepts a string, a Model object (such as the scripted mock), or a list of either. Omit it and Inspect falls back to the INSPECT_EVAL_MODEL environment variable; pass model=None for "no model" (the none provider).
  • Any CLI option is a keyword: limit=10, epochs=3, log_dir="...", display="none", fail_on_error=False, task_args={...}, and every generation setting (max_tokens=500, cache=True).
  • The returned logs are complete in memory, samples included (unless you turn sample logging off), so a script can analyse them straight away, as run_triage.py did. The same data is on disk at log.location.
  • from inspect_ai import eval shadows Python's built-in eval(). That is harmless in a short script, but in a larger module prefer from inspect_ai import eval as inspect_eval so nobody is surprised.
  • Async code calls eval_async() (same arguments, awaited). Calling eval() from inside a running event loop fails with RuntimeError: Already running asyncio in this thread. Jupyter notebooks run their own loop; Inspect depends on nest_asyncio2 to cope with that (not tested for this lesson; if a notebook complains, use await eval_async(...)).

When to use which: the CLI for running and sharing (a command line in a README or CI job is the most reproducible artefact there is); eval() when the run is part of a larger program (a notebook, a sweep over prompts, a post-processing step on the returned logs, or a keyless test with a scripted model).

5.5 .env and environment variables#

Inspect reads a .env file from the current directory, searching parent directories, and almost every CLI option has an environment-variable form: "All command line options can also be set via environment variable", mostly with the INSPECT_EVAL_ prefix and hyphens turned into underscores. The ones you will set first:

bash
# .env (never commit this file: it also holds your API keys; commit a .env.example)
INSPECT_EVAL_MODEL=mockllm/model     # the default --model
INSPECT_LOG_DIR=./logs-dev           # the default --log-dir; a relative path is relative to this .env file
INSPECT_DISPLAY=plain                # the default --display
OPENAI_API_KEY=...                   # provider keys, read by each provider

One catch, shown in full in 10B.9, 8.5: the INSPECT_EVAL_* twins of CLI flags (INSPECT_EVAL_EPOCHS, INSPECT_EVAL_LIMIT and so on) are read by the inspect command only. Python's eval() ignores them, except INSPECT_EVAL_MODEL. It does read the general settings in this block (INSPECT_LOG_DIR, INSPECT_DISPLAY, INSPECT_LOG_FORMAT). In scripts and notebooks, pass run settings to eval() explicitly.

Precedence: for the inspect command, a flag beats a shell variable, which beats .env. For eval(), an argument beats the few variables it reads. Two consequences: a stray INSPECT_EVAL_MODEL in your shell profile can quietly change which model a "default" run uses, and the VS Code Python extension also loads .env, so restart its terminals after changing INSPECT_LOG_DIR. When a run surprises you, check the log's eval.model and eval.config; they record what was actually used.

5.6 A model set on the Task beats --model#

The tasks page's override table puts eval() and the CLI at the top of the precedence order, and lists model as settable at every layer, so you would expect --model to replace a model set on the Task. In 0.3.292 it does not. Run the keyless variant from 4.10, whose Task carries the scripted mock, and ask for a different model:

bash
uv run inspect eval triage_scripted.py --model mockllm/other --display plain
Output · real, results panel only5 lines
triage_scripted (12 samples): mockllm/model
triage_format         triage_labels
accuracy       0.917  mean           0.889
stderr         0.083  stderr         0.075
Log: logs/2026-11-24T16-30-31-00-00_triage-scripted_iKXfBGKa5h76dfSgGgRGC7.eval

The header says mockllm/model, and the scores are the scripted mock's, so the Task's model was used and --model mockllm/other was ignored, without a warning. The installed source shows why: when tasks are resolved, the model is taken as task.model or model (inspect_ai/_eval/loader.py), so a model on the Task always wins over the one passed to eval() or the CLI.

What this means for you as an engineer:

  • Do not set model= on a task you mean to reuse. Leave the model to the run. If a task needs a fixed second model (a grader, a simulated user), use a model role instead (get_model(role="grader")), which the caller can still rebind with --model-role (10B.11).
  • When you run someone else's task, check the log's eval.model, not just your command line. That field records what actually ran.
  • Treat the docs' precedence table as the intent and the log as the truth. This is a docs-versus-behaviour gap in one release; it may change. The habit that protects you from this whole class of surprise is the same one as in 5.5: read back what the log says was used.

Part 6: Where logs go, and Inspect View#

6.1 Where logs go, and how they are named#

Every run writes one log per task × model. By default the log goes to ./logs relative to the current working directory, which means the folder you ran the command from, not the folder the task file lives in. Run the same task from two folders and you get two logs folders. Override it per run with --log-dir (CLI) or log_dir= (Python), or per project with INSPECT_LOG_DIR in .env. Logs can also live on S3 (s3://bucket/path) or other filesystems that fsspec supports, which is how teams share a log directory (10B.13).

The file name is {timestamp}_{task}_{id}.eval:

text
2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval
└──────── UTC time ────────┘ └task┘ └──── unique id ────┘

The timestamp is UTC with its offset (-00-00), so files sort by start time; underscores in a task name become hyphens (triage_scripted became triage-scripted); the id is unique per run. INSPECT_EVAL_LOG_FILE_PATTERN (for example {task}_{model}_{id}) changes everything after the timestamp, which helps when one folder holds many models.

6.2 What is inside a .eval file#

Since Inspect 0.3.46 the default format is .eval, which is a zip archive with zstd compression. The docs describe it as "optimised for size and speed. Typically 1/8 the size of .json files", and it can be read one sample at a time. You can look inside with any zip tool:

bash
unzip -l logs-triage/2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval
Output · real22 lines
Archive:  logs-triage/2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval
  Length      Date    Time    Name
---------  ---------- -----   ----
     3344  11-24-2026 22:06   _journal/start.json
    12279  11-24-2026 22:06   samples/T01_epoch_1.json
    11849  11-24-2026 22:06   samples/T02_epoch_1.json
    11635  11-24-2026 22:06   samples/T03_epoch_1.json
    11821  11-24-2026 22:06   samples/T04_epoch_1.json
    11746  11-24-2026 22:06   samples/T05_epoch_1.json
    11712  11-24-2026 22:06   samples/T06_epoch_1.json
    11708  11-24-2026 22:06   samples/T07_epoch_1.json
    11840  11-24-2026 22:06   samples/T08_epoch_1.json
    11833  11-24-2026 22:06   samples/T09_epoch_1.json
    10818  11-24-2026 22:06   samples/T10_epoch_1.json
    11803  11-24-2026 22:06   samples/T11_epoch_1.json
    11896  11-24-2026 22:06   samples/T12_epoch_1.json
    10755  11-24-2026 22:06   _journal/summaries/1.json
    10755  11-24-2026 22:06   summaries.json
     4116  11-24-2026 22:06   reductions.json
     4341  11-24-2026 22:06   header.json
---------                     -------
   174251                     17 files

(unzip shows the files' times in your local time zone; the log's file name uses UTC.) Inside: one JSON file per sample and epoch (samples/T01_epoch_1.json), a header.json with everything except the samples, summaries.json (a thin record per sample, for fast listing), reductions.json (the per-sample values after epoch reduction), and a _journal/ that Inspect writes while the run is in progress, which is how a crashed run can be recovered.

The alternative is --log-format json (or INSPECT_LOG_FORMAT=json): one plain JSON file. It is larger, and the docs warn it "can be slow to load in Inspect View if larger than 50MB". Two rules hold for both formats:

  • Read logs through Inspect's API (read_eval_log(), Part 7) or inspect log dump (7.5), not by unzipping and parsing JSON yourself. The internal layout is an implementation detail that has changed before, and the API also resolves de-duplicated content: since 0.3.206 repeated messages are stored once and referenced.
  • Expect NaN in the JSON. Samples that a scorer could not score carry a NaN value, which strict JSON parsers (browsers, Node, jq in some modes) reject. 10B.13 covers formats, sizes and conversion in depth.

6.3 Inspect View and the VS Code extension#

Inspect View is the web viewer for a log directory. Start it from the project folder:

bash
uv run inspect view                       # serves ./logs at http://127.0.0.1:7575
uv run inspect view --log-dir logs-triage --port 6565

(This lesson does not start the server; the descriptions below come from the official log-viewer page.) By default it binds to 127.0.0.1 on port 7575, stops any other inspect view already on that port, and serves the configured log directory. It updates live while an eval runs, so the usual workflow is to start it once per working session and leave it open. To view logs on a remote machine, the docs recommend an SSH tunnel (ssh -L 7575:127.0.0.1:7575 user@remote) rather than binding to a public address.

What you see:

View What it shows Use it for
Log list Every log in the directory with task, model, status and headline score Finding the run you want
Task results The metrics per scorer, as in the terminal panel The summary
Sample list One row per sample (and epoch) with input, target, answer and score; filter by score, sort by sample or score Jumping straight to the failures
Sample, Messages tab The full conversation: system, user, assistant and tool messages Reading what the model actually saw and said
Sample, Scoring tab Each scorer's value, answer and explanation Checking that the scorer judged what you think it judged
Sample, Metadata tab Metadata written by solvers, tools and scorers Context such as retrieved documents
Sample, Transcript Every event in order: solver spans, model calls with the raw request, state changes, scoring Debugging solvers, agents and scorers

Python logging calls inside your solvers and scorers also land in the transcript: by default messages at warning and above print on the console, and info and above are saved in the sample transcript.

The VS Code extension (1.3) embeds the same viewer: a Logs pane in the activity bar lists log files and opens them in an editor tab, and a View Log link appears while a task runs. If you live in VS Code, you may never start inspect view yourself.

6.4 Sharing logs: inspect view bundle, and what a log reveals#

To share results with someone who does not have Inspect installed, bundle the viewer and the logs into a static website:

bash
uv run inspect view bundle --log-dir logs-triage --output-dir triage-www
Output · real; the directory listing is trimmed to the top level8 lines
Creating view bundle in 'triage-www'

View bundle 'triage-www' created
assets/
content-security-policy.json
index.html
logs/
robots.txt

triage-www/ is a self-contained site (about 11 MB here, almost all of it the viewer's assets, with the .eval files and a listing.json under logs/). Deploy it to any static host that supports HTTP range requests (GitHub Pages, an S3 bucket, Netlify, per the docs), or pass an --output-dir starting with hf/ to publish to a Hugging Face Space (private by default). bundle_log_dir() is the Python equivalent, and eval sets can bundle automatically (10B.12).

Before you publish anything, know what a log contains beyond the scores. Here is what Inspect recorded about the repository when the hello task was run inside a throwaway git repository whose remote was set to a placeholder URL:

python
# revision.py: what a log records about your repository (lesson 10B.8)
from inspect_ai import eval

from hello import hello

log = eval(hello(), model="mockllm/model", display="none")[0]
print("revision:", log.eval.revision)
print("packages:", log.eval.packages)

The output below is real; run in a scratch git repository with origin set to https://example.com/acme/support-evals.git.

Output · real2 lines
revision: type='git' origin='https://example.com/acme/support-evals.git' commit='d06162d' dirty=True
packages: {'inspect_ai': '0.3.292'}

The log records your git remote URL, the commit and whether the working tree had uncommitted changes (dirty=True: the run's own logs/ folder and script were untracked). That is excellent for reproducibility (you can check out the exact commit that produced a number) and a leak if the repository is private and the bundle is public. A log also contains every prompt (your system prompts and templates), every model reply, every dataset input and target (which may be customer data), sample metadata, model arguments and the path of the task file. Before publishing: review what is in it, never publish logs built from production data, and run the eval from a checkout whose remote you are happy to reveal. 10B.13 covers editing logs and their tags and metadata.

6.5 From log back to config: inspect log export-config#

A log knows how it was produced, and Inspect can turn that back into a run-config file:

bash
uv run inspect log export-config logs-triage/2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval
Output · real13 lines
task:
  task: triage.py@triage
model:
  model: mockllm/model
  args:
    custom_outputs: null
eval_config:
  epochs: 1
  fail_on_error: true
  continue_on_fail: false
  score_on_error: false
metadata:
  source: lesson 10A.1 triage_eval.py

That YAML can be fed back with inspect eval --run-config run.yaml to repeat the run (10B.9 covers run configs). Look at the model section, though: custom_outputs: null. The scripted function was not serializable, so the config describes "plain mockllm/model", and re-running it would give you the null run of 4.10, not the scripted one. The general rule: a log can only reproduce what can be rebuilt by name. Registered tasks, solvers and scorers with simple arguments round-trip; Python objects passed in at run time (a scripted model, a lambda, a client object) do not. For real providers this is rarely a problem, because a model is a string plus settings.


Part 7: Reading the log back in Python#

Deep-dive

The viewer is for people; the log API in inspect_ai.log is for code: reports, CI gates, comparisons and anything that turns runs into decisions. This part reads the triage log from 4.7 with the core functions. 10B.13 covers the rest of the API (writing, editing, streaming, attachments) and the pandas dataframes built on top of it.

7.1 The whole read, in one script#

python
# read_log.py: open the triage log and read it like an engineer (lesson 10B.8)
from inspect_ai.log import (list_eval_logs, read_eval_log, read_eval_log_sample,
                            read_eval_log_sample_summaries)

# 1. Find logs: newest first. Each EvalLogInfo.name is a URI, not a plain path.
infos = list_eval_logs("logs-triage")
info = infos[0]
print("found:", len(infos), "| task:", info.task, "| name starts:", info.name[:8])

# 2. The header: everything except the samples. Fast, even for huge logs.
head = read_eval_log(info, header_only=True)
print("status:", head.status, "| samples loaded:", head.samples)
print("task:", head.eval.task, "version", head.eval.task_version, "| model:", head.eval.model)
print("dataset:", head.eval.dataset.samples, "samples, ids", head.eval.dataset.sample_ids[:3], "...")
print("plan:", [step.solver for step in head.plan.steps])
print("scorers:", [s.name for s in head.eval.scorers])
print("packages:", head.eval.packages, "| task metadata:", head.eval.metadata)
for s in head.results.scores:
    print("result:", s.name, {k: round(m.value, 4) for k, m in s.metrics.items()},
          "| scored", s.scored_samples, "unscored", s.unscored_samples)
print("usage:", {m: (u.input_tokens, u.output_tokens) for m, u in head.stats.model_usage.items()})

# 3. The full log: every sample, with messages, output and scores.
log = read_eval_log(info)
print("\nsample ids in log order:", [s.id for s in log.samples])
t11 = next(s for s in log.samples if s.id == "T11")
print("T11 messages:", [(m.role, m.text[:40]) for m in t11.messages])
print("T11 output:  ", t11.output.completion[:60], "...")
for name, sc in t11.scores.items():
    print(f"T11 {name}: value={sc.value!r} answer={sc.answer!r} reason={sc.reason!r}")
print("T11 events:", len(t11.events), "| kinds:", sorted({e.event for e in t11.events}))

# 4. Reductions: the per-sample values the metrics were computed from.
for r in log.reductions or []:
    print("reduction:", r.scorer, [(x.sample_id, round(x.value, 3)) for x in r.samples[:3]], "...")

# 5. One sample without loading the rest, and the cheap summaries.
t02 = read_eval_log_sample(info.name, id="T02")
print("\nT02 alone:", t02.output.completion[:45], "... |", t02.scores["triage_labels"].explanation)
summaries = read_eval_log_sample_summaries(info.name)
print("summaries:", len(summaries), "| first:", summaries[0].id,
      {k: v.value for k, v in summaries[0].scores.items()})
bash
uv run python read_log.py
Output · real22 lines
found: 1 | task: triage | name starts: file:///
status: success | samples loaded: None
task: triage version 1 | model: mockllm/model
dataset: 12 samples, ids ['T01', 'T02', 'T03'] ...
plan: ['prompt_template', 'generate']
scorers: ['triage_format', 'triage_labels']
packages: {'inspect_ai': '0.3.292'} | task metadata: {'source': 'lesson 10A.1 triage_eval.py'}
result: triage_format {'accuracy': 0.9167, 'stderr': 0.0833} | scored 12 unscored 0
result: triage_labels {'mean': 0.8889, 'stderr': 0.0749} | scored 12 unscored 0
usage: {'mockllm/model': (3343, 1032)}

sample ids in log order: ['T01', 'T02', 'T03', 'T04', 'T05', 'T06', 'T07', 'T08', 'T09', 'T10', 'T11', 'T12']
T11 messages: [('user', '# Task\nTriage a customer support ticket '), ('assistant', 'Sure! This looks like a billing issue, I')]
T11 output:   Sure! This looks like a billing issue, I would mark it P2. H ...
T11 triage_format: value='I' answer='{"priority": "P2"}' reason='invalid_response_format'
T11 triage_labels: value=0.3333333333333333 answer='P2|None' reason=None
T11 events: 20 | kinds: ['model', 'sample_init', 'score', 'span_begin', 'span_end', 'state']
reduction: triage_format [('T01', 1.0), ('T02', 1.0), ('T03', 1.0)] ...
reduction: triage_labels [('T01', 1.0), ('T02', 0.333), ('T03', 1.0)] ...

T02 alone: {"priority": "P2", "category": "billing", "su ... | wrong: priority, category
summaries: 12 | first: T01 {'triage_format': 'C', 'triage_labels': 1.0}

The subsections below walk through it.

7.2 Finding logs, and the header#

list_eval_logs(log_dir="./logs") returns EvalLogInfo records, newest first, searching subfolders by default (recursive=True); a filter= function and formats= narrow it. Each record has the task name, task id, size and modification time, and a name that is a URI (file:///...), not a plain path. Pass the EvalLogInfo itself (or its name) to Inspect's functions, which understand URIs; os.path.getsize(info.name) and friends fail with FileNotFoundError until you strip the file:// prefix. log.location follows whatever you opened the log with: a URI when read through an EvalLogInfo, a plain path when returned by eval() or read from a path. Code that needs a filesystem path should strip a file:// prefix if present.

read_eval_log(info, header_only=True) loads everything except the samples (samples is None), which is fast even for a log with thousands of long transcripts. The header is enough for most reporting: status, results, configuration, usage. Its shape:

flowchart LR
    LOG["EvalLog"] --> ST["status<br/>started, success,<br/>cancelled, error"]
    LOG --> EV["eval: EvalSpec<br/>task, version, model, dataset,<br/>config, revision, packages"]
    LOG --> PL["plan<br/>solver steps and their args"]
    LOG --> RS["results<br/>one EvalScore per scorer x reducer,<br/>each with metrics"]
    LOG --> STATS["stats<br/>times, model_usage"]
    LOG --> SM["samples: list of EvalSample<br/>messages, output, scores,<br/>metadata, events, error"]
    LOG --> RD["reductions<br/>per-sample values the<br/>metrics were computed from"]
    LOG --> ERR["error<br/>message and traceback"]
Field What it holds In the output above
status "started" (still running, or crashed), "success", "cancelled", "error" success
eval (an EvalSpec) The run's identity and configuration: task, task_version, task_args, model, model_generate_config, model_roles, dataset (name, sample count, sample ids, shuffled flag), config (limits, epochs, error policy), scorers, revision, packages, metadata, created triage version 1, 12 samples, the task's metadata
plan The solver chain, step by step, with each solver's arguments prompt_template, generate
results scores: a list of EvalScore, one per scorer (and per reducer when there are several), each with metrics, scored_samples and unscored_samples; plus totals the two results lines
stats Start and end times, model_usage per model (input, output, total, cache and reasoning tokens; cost only when configured) 3,343 input, 1,032 "output" (fake, 9.5)
samples The full per-sample records (only when read without header_only) None in the header
reductions The per-sample values after epoch reduction read in 7.3
error For a failed run: the error message and traceback absent here

7.3 Samples, scores and reductions#

read_eval_log(info) without header_only loads every EvalSample. Each one holds the sample's id and epoch, its input, target and metadata, the full messages list (here: the rendered user prompt and the assistant reply; a system message or tool calls would appear too), the final output, a scores dict keyed by scorer name, per-sample model_usage and timings, any error, the store, and the events list, which is the transcript the viewer draws.

Three details from the output:

  • Per-sample scores keep their original values. T11's format score is the string 'I' with the answer the scorer extracted ({"priority": "P2"}) and its reason (invalid_response_format). The labels score is the float 0.333....
  • Reductions are floats. reductions lists, per scorer, the value each sample contributed to the metric after epoch reduction: T01's format 'C' became 1.0. Inspect applies the reducer (default: mean, via value_to_float()) even when there is only one epoch, which is why metrics always see numbers (10B.10 explains why that matters for custom metrics).
  • Events are the transcript. T11 has 20 events of six kinds: span_begin/span_end (the solver and scorer steps), sample_init, state (changes to the TaskState), model (the request, the response and the raw call) and score. You rarely read them in code; the viewer renders them. 10B.13 has the full event catalogue.

7.4 Reading one sample, and the summaries#

For big logs, loading every sample to look at one is wasteful. Two cheaper reads:

  • read_eval_log_sample(log_file, id="T02", epoch=1) loads a single EvalSample. In the output, T02's reply and its explanation (wrong: priority, category) came back without the other eleven samples being read.
  • read_eval_log_sample_summaries(log_file) returns a thin EvalSampleSummary per sample (id, epoch, input, target, metadata, score values, usage, timings, error), which the docs describe as orders of magnitude faster than full samples. The pattern for large logs: filter on summaries (for example "all samples whose format score is I"), then read just those samples in full.

7.5 From other languages: inspect log dump and inspect log list#

If the code that consumes logs is not Python (a dashboard, a Node service, a shell script in CI), let the CLI convert:

bash
uv run inspect log list --log-dir logs-triage --json
uv run inspect log dump --header-only logs-triage/2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval > header.json

inspect log list --json printed (real):

text
[
 {
  "name": "logs-triage/2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval",
  "type": "file",
  "size": 44524,
  "mtime": 1795538212987.5195,
  "task": "triage",
  "task_id": "VzsYfMnkPEdgFaPoiwFttC",
  "suffix": null
 }
]

inspect log dump prints the log as JSON whatever its storage format, using your configured credentials for remote logs; --header-only skips the samples. A few lines of standard-library Python summarize header.json (dump_summary.py):

python
# dump_summary.py: summarise `inspect log dump --header-only` JSON with the standard library
import json
import sys

d = json.load(open(sys.argv[1]))
print("top-level keys:", list(d))
print("eval keys (first 8):", list(d["eval"])[:8])
first = d["results"]["scores"][0]
print("first score:", first["name"], {k: v["value"] for k, v in first["metrics"].items()},
      "| scored_samples:", first["scored_samples"])
print("revision fields:", sorted(d["eval"].get("revision") or {}))
Output · real, python3 dump_summary.py header.json4 lines
top-level keys: ['version', 'status', 'eval', 'plan', 'results', 'stats', 'invalidated', 'total_samples', 'tags', 'metadata', 'reductions']
eval keys (first 8): ['eval_id', 'run_id', 'created', 'task', 'task_id', 'task_version', 'task_file', 'task_display_name']
first score: triage_format {'accuracy': 0.9166666666666666, 'stderr': 0.08333333333333333} | scored_samples: 12
revision fields: ['commit', 'dirty', 'origin', 'type']

The JSON mirrors the Python objects field for field (fields with no value, such as an empty reducer, are left out). inspect log list --status error lists only failed runs, and inspect log schema prints the JSON schema of the format. Parse the dump with a NaN-tolerant reader if any sample might be unscored (6.2).


Part 8: evalkit ↔ Inspect: the complete mapping#

Reference

8.1 The mapping table#

evalkit's public names are listed in 10A.10, Appendix A. Here is where each idea lives in Inspect, and what differs. The rows marked with a lesson number are taught in depth there.

evalkit Inspect What differs
Example(id, input, reference, metadata) Sample(id, input, target, metadata, choices, files, setup, sandbox, description) reference is target (a string or a list of acceptable strings); input may be a list of chat messages; id is optional (auto-numbered at run time if absent)
A list of Examples, dataset.py loaders (10A.2) A list of Samples, MemoryDataset, csv_dataset, json_dataset, hf_dataset, FieldSpec, record_to_sample (10B.9) No Parquet loader (read with pandas and build samples); filtering, slicing, shuffling built in
task: Example -> prompt str The solver chain: system_message(), prompt_template(), user_message()... then generate() Prompt shaping is a sequence of solvers; solvers can also loop, call tools, critique; recorded in the log with arguments
call_model: str -> str The model chosen at run time (--model provider/name, eval(model=...)), get_model() inside solvers and scorers The model is not wired into the task. For a custom callable, script mockllm/model (Part 4) or write a @modelapi provider (10B.12)
FakeTriageModel and other fakes mockllm/model with custom_outputs The fake is a provider, so solvers, scorers and logs run unchanged
Scorer.score(example, output) -> Score @scorer factory returning async def score(state, target) -> Score The scorer sees the whole TaskState (messages, metadata, store), not only the output text; metrics are declared on the scorer
Score(name, value in [0,1], passed, detail) Score(value, answer, explanation, reason, metadata) No name (the scorer's registered name is used) and no passed: the value is the verdict. Values may be C/I/P/N, any number, a bool, a list or a dict
Row passes iff every scorer passes; EvalReport.pass_rate No built-in equivalent: each scorer has independent metrics Compute it from the log (4.8), or write a combined scorer or a multi_scorer() reduction (10B.10)
EvalReport.mean_score (mean over scorers, then rows) accuracy() or mean() per scorer Per-scorer numbers; a cross-scorer mean is yours to compute and name
repeats= in run_eval epochs= on the Task, eval() or --epochs; Epochs(n, reducer) Epoch scores are reduced per sample (mean, mode, pass@k, at_least_k...) before metrics; the reducer is explicit and logged (10B.10)
slice_breakdown() by metadata The grouped(metric, "key") metric, or samples_df() metadata_* columns plus pandas Metadata alone does not slice; you ask for a grouped metric or group the dataframe (10B.10, 10B.13)
failing_examples() Filter samples by score in Inspect View, or filter log.samples / samples_df() in code
summary() printed report The terminal results panel, Inspect View
to_jsonl() rows The .eval log (plus inspect log dump for JSON) The log holds full transcripts, config and provenance, not just rows
Row-level error capture (the run never crashes) fail_on_error (default: the task stops at the first sample error), --no-fail-on-error, retry_on_error, score_on_error Opposite defaults: evalkit records and continues, Inspect fails fast (8.2)
cache dict keyed on (model, run, prompt) cache=True or CachePolicy on disk, keyed on model, arguments, messages, epoch, config and tools (10B.12) The same "run index in the key" idea, persistent across processes
runner.py budget caps (10A.8) Per-sample message_limit, token_limit, time_limit, working_limit, cost_limit Inspect's limits are per sample, not per run
compare.py, paired bootstrap, cli.py gate (10A.8) None built in; inspect eval exits 0 even when a run fails A gate is your code over logs (9.6, 10B.12)
judges.py (10A.4) and judge_validation.py (10A.5) model_graded_qa(), model_graded_fact(), grader roles, panels (10B.11) The built-in graders' prompts are Inspect's, not yours; human-label calibration is still 10A.5's code
agent_eval.py World, AgentFn (10A.7) Agents as solvers, tools, sandboxes (10B.14, 10B.15)

What this means for you as an engineer: nothing you learned in 10A.1 to 10A.8 is obsolete. Inspect replaces core.py's runner, the report and the caching with better-engineered versions, and adds solvers, agents, sandboxes and the viewer. It does not replace your dataset design (10A.2), your choice of scorer (10A.3), judge validation (10A.5) or the statistics for comparing runs (10A.8): those you still bring, and the log is the data you bring them to.

8.2 Where the defaults differ#

Ported evals go wrong at the defaults, not at the API. The ones that change numbers or behaviour:

Concern evalkit default Inspect default Consequence
A sample raises Recorded on the row; the run continues The task stops at the first error; status error Set --no-fail-on-error (or a threshold such as fail_on_error=0.1) for flaky tools, and report errored samples
Errored or unscored samples Counted as failures in pass_rate (but left out of mean_score) Left out of the denominator Inspect's accuracy can be higher for the same run; always read scored_samples
Multiple scorers One pass/fail per row (all must pass) Independent metrics per scorer Decide and document how you combine them (4.8)
Repeats repeats produces more rows epochs reduced per sample (mean) before metrics n in the stderr is the number of samples, not samples × epochs
Concurrency Sequential in core.py (parallel in 10A.8's runner.py) Concurrent from the start (adaptive: starts at 20 requests, 10 to 100) Fakes and scorers must not depend on order (2.3)
Where results go Where you write the JSONL ./logs under the current directory Set log_dir per project (5.5)
Prompt templates Python f-strings / str.format str.format rules with unknown placeholders left in place Single braces are mangled and typos pass silently (9.2)

8.3 What changed since 10A.10's Inspect section#

10A.10, Part 4 introduced Inspect with a sketch of this eval. Checked against inspect-ai 0.3.292 on 24 November 2026, these statements are out of date or wrong, and this lesson's version supersedes them:

10A.10 says As of 0.3.292
Landscape table: inspect-ai 0.3.288 0.3.292 (23 November 2026); Python ≥ 3.11 since 0.3.281
4.4: "Inspect gives you per-sample transcripts, token/cost accounting" Transcripts and tokens yes; cost only when you configure model prices (--model-cost-config, set_model_cost()), otherwise total_cost is empty
4.4: run with inspect eval triage_task.py --model ... Correct. A keyless dry run is --model mockllm/model, which returns a fixed string, so an exact-JSON scorer scores 0 (4.10); to see passes, script the mock (4.6)
4.4: agents through use_tools()/basic_agent() basic_agent() still exists, but the docs now lead with react() from inspect_ai.agent (10B.14)
4.5: partial credit is "Score.value in [0,1]" Score.value is any Value: C/I/P/N labels, any number, a bool, a list or a dict; metrics convert with value_to_float() (4.4)
4.5: repeats are "--epochs / sample-level epochs" There are no sample-level epochs: epochs are set on the Task, eval() or --epochs, and scores are reduced per sample before metrics
4.5: dataset storage "json_dataset, parquet" No Parquet loader; CSV, JSON, JSON Lines, Hugging Face and in-memory
4.5: slices are "dataset metadata columns" Slicing is the grouped() metric (or grouping samples_df() by metadata_* columns)
4.5: one test case is a "dataset row (input/target)" Name the type: a Sample
4.5: report is ".eval log + inspect view" Add the log API (Part 7) and the dataframes (evals_df(), samples_df(), which need pandas and pyarrow)
4.5: CI gate is "inspect eval + your wrapper" Correct, and essential: inspect eval exits 0 even when the log's status is error (9.6); inspect eval-set does exit 1 when tasks stay incomplete
⚠️ "In evalkit and Inspect AI the judge is your code" (and the same claim in 10A.10's recap and misconceptions) Only for custom judges. model_graded_qa() and model_graded_fact() ship Inspect's template, instructions and grade pattern, which change between releases; re-validate them as you would promptfoo's llm-rubric (10B.11)
Glossary: "Solver (Inspect AI): Inspect's name for 'task'" Misleading: an Inspect Task is dataset + solver + scorer; a solver is the pipeline that produces the output, and corresponds to evalkit's task callable plus the model call
Further reading links "scorers" to the docs root The scorers page is https://inspect.aisi.org.uk/scorers.html

10A.10's failure gallery should also gain the Inspect rows from 9.7 below: empty targets, silent template placeholders, the task-level model, the exit code and the mixed task list.

8.4 When to reach for Inspect#

Situation Reach for Why
A single-turn product eval you already run in evalkit, and the team is happy Keep evalkit (or port when you need the viewer) A port is cheap (Part 4), but it is not free; do it for a reason
Agents, tools, multi-turn conversations, code execution Inspect Solvers, agents, sandboxes and the transcript viewer are its core (10B.14 to 10B.16)
Comparing many models or prompt variants on one task, reproducibly Inspect One task file, --model a,b,c, task parameters, logs with full provenance
Running public benchmarks Inspect with Inspect Evals 200-plus implementations (10B.16)
pytest-style metric thresholds in CI with ready-made RAG and safety metrics DeepEval (10B.2) Its home ground
A team that wants both Both, with clear ownership (10B.17) DeepEval metrics can run inside an Inspect scorer, and Inspect logs feed evalkit's statistics
Non-engineers need to review results in a hosted UI A platform over your logs (10A.10) Inspect View bundles help, but they are not a review workflow

Part 9: First-day pitfalls, reproduced#

Deep-dive

Each pitfall below was reproduced with inspect-ai 0.3.292 and the mock model. They are the mistakes that cost people a day in their first week, and most fail silently: no error, just a wrong number.

9.1 Every task in a file runs#

Covered in 5.1: inspect eval two_tasks.py ran both tasks, and the -T parameter meant for one only produced a warning for the other. Name the task (file.py@task), and run inspect list tasks when you are not sure what a file contains.

9.2 Single braces in templates are silently mangled#

Inspect's template solvers (system_message(), user_message(), assistant_message(), prompt_template()) fill {placeholders} from the sample's metadata, the store and their keyword arguments, using Python's str.format rules with one twist: unknown placeholders are left in place instead of raising an error. That twist makes two mistakes silent:

python
# braces.py: what Inspect's template solvers do to braces (lesson 10B.8)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.solver import generate, system_message

INSTRUCTIONS = [
    'Single braces: reply like {"priority": "P1"}',      # JSON pasted as-is
    'Doubled braces: reply like {{"priority": "P1"}}',   # escaped, as for str.format()
    'Ticket {ticket_id}, customer tier {tier}',          # {tier} exists, {ticket_id} does not
]

if __name__ == "__main__":
    for text in INSTRUCTIONS:
        task = Task(dataset=[Sample(input="hi", metadata={"tier": "gold"})],
                    solver=[system_message(text), generate()])
        log = eval(task, model="mockllm/model", display="none")[0]
        sent = log.samples[0].messages[0].text          # the system message as sent
        print(f"template: {text}\nsent:     {sent}\n")
bash
uv run python braces.py
Output · real8 lines
template: Single braces: reply like {"priority": "P1"}
sent:     Single braces: reply like {{"priority"}: "P1"}

template: Doubled braces: reply like {{"priority": "P1"}}
sent:     Doubled braces: reply like {"priority": "P1"}

template: Ticket {ticket_id}, customer tier {tier}
sent:     Ticket {ticket_id}, customer tier gold
  • A JSON example with single braces is corrupted. {"priority": "P1"} reached the model as {{"priority"}: "P1"}: the formatter read "priority" as a field name and : "P1" as a format specification, failed to find either, and re-emitted them in a broken shape. No error, no warning. Your output-format instruction is now wrong, and the model's format accuracy drops for a reason that has nothing to do with the model.
  • Doubled braces are the fix, exactly as with str.format(): {{"priority": "P1"}} arrives as {"priority": "P1"}.
  • A misspelt placeholder ships as literal text. {tier} was filled from metadata; {ticket_id}, which exists nowhere, reached the model as {ticket_id}. A typo in a placeholder name (or a metadata key that a few samples lack) produces prompts with raw braces in them, and nothing tells you.

What this means for you as an engineer: after writing or changing any template, run one sample against the mock (--limit 1 --model mockllm/model) and read the prompt as sent, in the viewer's Messages tab or with log.samples[0].messages. For a check you can automate, assert in a test that no rendered prompt still contains a { followed by a letter. 10A.10's failure gallery recorded the promptfoo version of this bug ({{vars}} rendering literally); this is Inspect's.

9.3 An empty target passes everything#

Sample.target defaults to the empty string, and the empty string is contained in every string:

python
# pitfalls.py: three first-day surprises, reproduced (lesson 10B.8)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import Score, Target, accuracy, includes, scorer
from inspect_ai.solver import TaskState

# 1. A Sample with no target has target "", and "" is contained in every string.
log = eval(Task(dataset=[Sample(id=1, input="Classify: my card was charged twice")],
                scorer=includes()), model="mockllm/model", display="none")[0]
s = log.samples[0]
print("1. target:", repr(s.target), "| output:", repr(s.output.completion),
      "| includes():", s.scores["includes"].value)

# 2. mockllm's usage numbers are synthesised: output_tokens counts characters.
usage = log.stats.model_usage["mockllm/model"]
print("2. output_tokens:", usage.output_tokens, "| len(output):", len(s.output.completion))

# 3. A scorer factory must return an *async* function.
try:
    @scorer(metrics=[accuracy()])
    def sync_scorer():
        def score(state: TaskState, target: Target) -> Score:   # missing async
            return Score(value="C")
        return score

    sync_scorer()
except TypeError as e:
    print("3. TypeError:", str(e)[:90])
bash
uv run python pitfalls.py
Output · real3 lines
1. target: '' | output: 'Default output from mockllm/model' | includes(): C
2. output_tokens: 33 | len(output): 33
3. TypeError: 'sync_scorer' is not declared as an async callable.

Line 1 is this pitfall: a sample with no target scored C under includes(). The same happens with match(), and a comment in the source of includes() says it outright: an empty target "is contained in anything". A dataset loaded from a file where some rows have an empty answer column will quietly score those rows as correct. Always set a target for text scorers, validate your dataset for empty targets when you load it (10A.2, 8.4 makes that the loader's job), and use a scorer that does not need a target (a model grader with a fixed rubric, a format check) for samples that genuinely have none.

Lines 2 and 3 are the next two pitfalls.

9.4 Scorers and solvers must be async#

Line 3 of the output: a scorer whose inner function is a plain def is rejected when the factory is called, with TypeError: 'sync_scorer' is not declared as an async callable. Solvers behave the same way. The fix is async def. Two places mislead you here: the docstrings inside the installed package's @solver and Solver show a def solve(...) without async (that example fails), and some older blog posts do the same. The message names the factory, so look for the missing async on the function it returns.

9.5 Mock usage numbers are fake#

Line 2 of the output: the mock reported 33 output tokens for a 33-character reply. mockllm/model fills in usage when its output has none, counting input tokens with Inspect's token counter and output "tokens" as characters. That is why the hello run showed O: 66 for two 33-character replies, and why the triage runs report 1,032 output tokens for twelve short JSON strings. Keyless runs are for plumbing and logic; never quote their token counts, timings or costs as estimates of a real run. For a cost estimate, run a handful of samples against the real model and multiply (03.7 covers cost tracking).

9.6 inspect eval exits 0 when the eval failed#

boom.py has a solver that raises on one of four samples, a stand-in for a flaky tool or a timeout:

python
# boom.py: a task whose solver fails on one sample (lesson 10B.8)
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver


@solver
def flaky_tool() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        if state.sample_id == "b2":
            raise RuntimeError("order service timed out")
        return state
    return solve


@task
def boom() -> Task:
    return Task(
        dataset=[Sample(id=f"b{i}", input="Say: default output", target="default output")
                 for i in range(1, 5)],
        solver=[flaky_tool(), generate()],
        scorer=includes(),
    )
bash
uv run inspect eval boom.py --model mockllm/model --log-dir logs-boom --display plain
echo "inspect eval exit code: $?"
Output · real, the end of the traceback panel and the summary10 lines
RuntimeError: order service timed out
Task interrupted (2 of 4 total samples logged before interruption). Resume task
with:

inspect eval-retry
logs-boom/2026-11-24T16-43-07-00-00_boom_mffVYBPPJyMWL42E869Zk9.eval
Log: logs-boom/2026-11-24T16-43-07-00-00_boom_mffVYBPPJyMWL42E869Zk9.eval
---------------------------------------------------------

inspect eval exit code: 0

Two behaviours to absorb. First, the default error policy is fail-fast: the first sample error stopped the task, the log's status is error, and Inspect suggests inspect eval-retry to finish it (10B.12). Second, the process exit code was 0. A CI job that runs inspect eval and trusts the exit code goes green on a crashed eval. (In the installed source, only inspect eval-set sets a failing exit code when tasks remain incomplete.)

With --no-fail-on-error, the run completes, and the number looks perfect:

bash
uv run inspect eval boom.py --model mockllm/model --no-fail-on-error --log-dir logs-boom2 --display plain
Output · real, results panel8 lines
total time:                0:00:01
mockllm/model              111 tokens [I: 12, O: 99]
includes
accuracy  1.000
stderr    0.000

WARNING: 1 of 4 executed samples (25%) had errors and were not scored.
Log: logs-boom2/2026-11-24T16-43-09-00-00_boom_5QtwKJhbv3ub4mFRwfCM2D.eval

Accuracy 1.000, computed over the three samples that did not error. The warning line is the only hint, and it is easy to miss in a CI log. This is the "unscored samples leave the denominator" rule from 8.2 in action.

The fix is a gate that reads the log. A minimal one (10B.12 builds the production version with eval sets and retries):

python
# gate.py: fail a CI step unless the newest log really succeeded (lesson 10B.8)
"""Usage: python gate.py LOG_DIR SCORER METRIC MIN_VALUE

`inspect eval` exits 0 even when the run failed, so CI must read the log.
"""
import sys

from inspect_ai.log import list_eval_logs, read_eval_log


def gate(log_dir: str, scorer: str, metric: str, minimum: float) -> int:
    infos = list_eval_logs(log_dir)
    if not infos:
        print(f"FAIL: no logs in {log_dir}")
        return 1
    log = read_eval_log(infos[0], header_only=True)          # newest first
    name = infos[0].name.rsplit("/", 1)[-1]
    if log.status != "success":
        print(f"FAIL: {name} status={log.status}: {log.error.message if log.error else ''}")
        return 1
    result = next((s for s in log.results.scores if s.name == scorer), None)
    if result is None or metric not in result.metrics:
        print(f"FAIL: {name} has no {scorer}/{metric}")
        return 1
    value = result.metrics[metric].value
    total = log.results.total_samples
    if result.scored_samples != total:                       # errored or unscored samples
        print(f"FAIL: {name} scored {result.scored_samples} of {total} samples")
        return 1
    verdict = "PASS" if value >= minimum else "FAIL"
    print(f"{verdict}: {name} {scorer}/{metric}={value:.3f} (min {minimum}), "
          f"scored {result.scored_samples}/{total}")
    return 0 if verdict == "PASS" else 1


if __name__ == "__main__":
    log_dir, scorer, metric, minimum = sys.argv[1], sys.argv[2], sys.argv[3], float(sys.argv[4])
    sys.exit(gate(log_dir, scorer, metric, minimum))
Output · real, run against the three log folders above9 lines
$ uv run python gate.py logs-boom includes accuracy 0.9
FAIL: 2026-11-24T16-43-07-00-00_boom_mffVYBPPJyMWL42E869Zk9.eval status=error: RuntimeError('order service timed out')
exit code: 1
$ uv run python gate.py logs-boom2 includes accuracy 0.9
FAIL: 2026-11-24T16-43-09-00-00_boom_5QtwKJhbv3ub4mFRwfCM2D.eval scored 3 of 4 samples
exit code: 1
$ uv run python gate.py logs-triage triage_format accuracy 0.9
PASS: 2026-11-24T16-36-52-00-00_triage_VzsYfMnkPEdgFaPoiwFttC.eval triage_format/accuracy=0.917 (min 0.9), scored 12/12
exit code: 0

The crashed run fails on status, the "perfect" run fails on coverage (3 of 4 scored), and the triage run passes its threshold with full coverage. Three checks, each one a number this lesson showed can lie: status, coverage and the metric. In CI, run inspect eval ... and then python gate.py ... as the step that decides.

Symptom Cause Fix
Two (or ten) tasks ran and the bill doubled inspect eval file.py runs every @task in the file file.py@task; check with inspect list tasks (5.1)
--model was ignored, silently The Task sets model=, which beats eval()/CLI in 0.3.292 Do not set model on reusable tasks; use model roles; read eval.model in the log (5.6)
A task_args change made no difference The task was passed to eval() as an already-built Task Pass it by name with task_args, or call the @task function with the arguments (5.2)
eval([my_task(), "other.py@x"]) ran only my_task A list starting with a Task drops the strings after it (0.3.292 source) Keep the list homogeneous: all Task objects or all strings (5.4)
Format accuracy collapsed after a prompt edit Single braces in a template were mangled Double them; read the prompt as sent (9.2)
Prompts contain literal {something} Unknown placeholders pass through silently Check metadata keys and spelling; test the rendered prompt (9.2)
Some samples always pass, whatever the model says Empty target with includes()/match() Validate targets at load time (9.3)
TypeError: '...' is not declared as an async callable. The inner solver or scorer function is a plain def async def (9.4)
"Inspect said the run used 1,032 output tokens" mockllm counts characters as output tokens Never quote mock usage (9.5)
CI green, eval crashed inspect eval exits 0 on status error Gate on the log: status, coverage, metric (9.6)
Accuracy 1.000 that nobody believes Errored or unscored samples left the denominator Report scored_samples of total_samples (7.2, 9.6)
The scripted mock gave sample B sample A's answer A list of custom_outputs is consumed in request order, which concurrency shuffles Key replies on the input (3.5, 4.6)
"Where did my logs go?" ./logs is relative to the directory you ran from Set INSPECT_LOG_DIR or --log-dir (6.1)
A shared bundle exposed the private repo URL Logs record the git remote, commit and dirty flag Review before publishing; run from a suitable checkout (6.4)
FileNotFoundError on a path from list_eval_logs EvalLogInfo.name (and log.location when read through it) is a URI (file:///...) Pass them to Inspect functions, or strip file:// (7.2)
Joined two runs and the comparison is nonsense Samples were matched by position Join on (id, epoch) (7.3)
--model openai/... fails immediately The provider SDK is not installed (inspect-ai does not include it) uv add openai (1.3)
Google runs use a different key than expected Both GOOGLE_API_KEY and GEMINI_API_KEY are set; Inspect prefers GOOGLE_API_KEY Keep one Google key in .env (4.9)
samples_df() raises about missing packages pandas and pyarrow are not dependencies uv add pandas pyarrow (1.3)
.env setting ignored when running from Python INSPECT_EVAL_* variables configure the CLI, not eval() Pass the setting to eval() (5.5)
RuntimeError: Already running asyncio in this thread eval() called inside a running event loop Use await eval_async(...) (5.4)
A re-run from export-config gives different numbers Run-time Python objects (a scripted mock) are not serialized Reproduce only what can be rebuilt by name (6.5)

Part 10: Methodology: defending the first number#

Deep-dive

A framework makes numbers easy to produce. This part is about the work that makes them worth quoting, applied to the very first Inspect run. Nothing here is new methodology (10A.1 to 10A.8 taught it); it is where each habit attaches to Inspect.

10.1 What the number is#

"Accuracy 0.917" from Inspect is precisely: for the scorer triage_format, the mean over the scored samples of each sample's reduced value, where the reduction turned each sample's epoch scores into one float (here one epoch, so C became 1.0 and I became 0.0). Every part of that sentence can change the number:

  • Which scorer. The same run gave 0.917, 0.889 and (computed) 0.833 (4.8).
  • Which samples were scored. Errored and unscored samples are not in the denominator (9.6).
  • Which reducer. With several epochs, mean, majority vote and pass@k give different numbers from the same scores (10B.10).
  • How values become floats. value_to_float() maps unknown labels to 0 (4.4).
  • What produced the outputs. The model, the solver chain, the prompt version, the generation settings and the Inspect version, all of which the log records and none of which the number shows.

So the minimum honest report of an Inspect result names the task and its version, the scorer and metric, the model, the number of samples scored out of the total, the standard error (or better, an interval), and the log file it came from.

10.2 Controls: oracle and null runs#

Before trusting a scorer on real model output, prove it can reach both ends of its scale. 10A.7, 5.5 called these self-tests; with the mock they take a minute:

python
# controls.py: an oracle run and a null run, to prove the scorers can reach 1 and 0 (lesson 10B.8)
from inspect_ai import eval
from inspect_ai.model import ModelOutput, get_model

from triage import TICKETS, triage

TARGETS = {text: ref for _tid, text, ref, _meta in TICKETS}


def oracle(input, tools, tool_choice, config) -> ModelOutput:
    """Answers every ticket perfectly, built from the dataset's own targets."""
    prompt = input[-1].text
    ref = next((r for text, r in TARGETS.items() if text and text in prompt),
               "P3|other")                     # the empty ticket T10
    priority, category = ref.split("|")
    content = ('{"priority": "%s", "category": "%s", "summary": "Oracle summary."}'
               % (priority, category))
    return ModelOutput.from_content(model="mockllm", content=content)


if __name__ == "__main__":
    runs = {
        "oracle": get_model("mockllm/model", custom_outputs=oracle, memoize=False),
        "null": get_model("mockllm/model", memoize=False),   # always "Default output from mockllm/model"
    }
    for label, model in runs.items():
        log = eval(triage(), model=model, display="none")[0]
        summary = {s.name: {k: round(m.value, 3) for k, m in s.metrics.items()}
                   for s in log.results.scores}
        print(f"{label:6} {log.status}  {summary}")
bash
uv run python controls.py
Output · real2 lines
oracle success  {'triage_format': {'accuracy': 1.0, 'stderr': 0.0}, 'triage_labels': {'mean': 1.0, 'stderr': 0.0}}
null   success  {'triage_format': {'accuracy': 0.0, 'stderr': 0.0}, 'triage_labels': {'mean': 0.0, 'stderr': 0.0}}

The oracle (a fake model that returns the reference answer for every sample) scores 1.0 on both scorers, so no sample is unwinnable: no label is mistyped, no metadata rule is impossible, the parser accepts valid output. The null model (the mock's fixed Default output from mockllm/model) scores 0.0, so the scorers reject garbage. If the oracle scored 0.92, you would have found a broken label or a scorer bug before any real model was blamed for it; if the null run scored above zero, a scorer would be passing nonsense (an empty target, 9.3, is the classic cause).

What this means for you as an engineer: keep an oracle and a null run next to every task, run them whenever the dataset or a scorer changes, and fail CI if the oracle drops below 1.0 or the null rises above 0. They cost nothing, need no key, and catch the bugs that otherwise surface as "the new model is mysteriously worse".

10.3 Read the transcripts#

A metric tells you how many samples failed; only the samples tell you why. For every new task and every surprising result, open the log in Inspect View, filter to the failures, and read them (10A.1, 4.5 says how many traces to read and when to stop). For each failure, decide which of three things happened:

  1. The model was wrong (T02: an outage labelled as billing). This is the signal you wanted.
  2. The scorer was wrong: it failed to extract a correct answer, or compared it too strictly. The answer and explanation fields exist so you can see this at a glance.
  3. The task was wrong: a mislabelled target, a broken template (9.2), a sample that cannot be answered from its input.

Only the first kind belongs in the metric. Fix the other two in the task, bump version, and re-run.

10.4 Twelve samples is not much#

The triage task's format accuracy is 0.917 with a standard error of 0.083. How much does that pin down? The standard error is the scale of the uncertainty; the usual "plus or minus about two standard errors" interval is a normal approximation that misbehaves for proportions near 0 or 1 with small samples. A pure-Python comparison with the Wilson interval, which 10A.7 used for pass rates:

python
# wilson.py: how wide is the uncertainty around 11 of 12? (lesson 10B.8)
import math


def normal_interval(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
    p = k / n
    se = math.sqrt(p * (1 - p) / (n - 1))        # Inspect's stderr uses ddof=1
    return p - z * se, p + z * se


def wilson_interval(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
    p = k / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return centre - half, centre + half


for k, n in [(11, 12), (110, 120), (1100, 1200)]:
    lo, hi = normal_interval(k, n)
    wlo, whi = wilson_interval(k, n)
    print(f"{k:>4}/{n:<5} accuracy={k / n:.3f}  mean±1.96·stderr=[{lo:.3f}, {hi:.3f}]"
          f"  Wilson 95%=[{wlo:.3f}, {whi:.3f}]")
bash
python3 wilson.py
Output · real3 lines
  11/12    accuracy=0.917  mean±1.96·stderr=[0.753, 1.080]  Wilson 95%=[0.646, 0.985]
 110/120   accuracy=0.917  mean±1.96·stderr=[0.867, 0.966]  Wilson 95%=[0.853, 0.954]
1100/1200  accuracy=0.917  mean±1.96·stderr=[0.901, 0.932]  Wilson 95%=[0.900, 0.931]

At n = 12 the normal interval runs past 1.0 (impossible for an accuracy), and the Wilson interval says the true format accuracy could plausibly be anywhere from about 65% to 98%. At n = 1,200 the two agree and the interval is a few points wide. Three consequences:

  • A 12-sample eval is a smoke test, not a measurement. It is the right size for checking plumbing and catching gross failures, and the wrong size for choosing between two models that differ by five points. 10A.2, Part 5 gives the sample sizes for the decisions you actually want to make.
  • Inspect reports the standard error; it does not report an interval by default, and it does not compare runs. It has interval metrics you can add (ci(), and ci_wilson(), which the docs recommend for binary scores), clustered standard errors for grouped samples, and per-group metrics (10B.10). It has no built-in paired comparison between two runs, no multiple-comparison correction and no power analysis: those are 10A.8's tools, applied to the per-sample scores you read from the logs (Part 7).
  • Compare models on the same samples, paired. Two logs of the same task version, joined on (id, epoch), give you paired differences, which are far more sensitive than comparing two accuracies with their separate standard errors.

10.5 A checklist before you quote an Inspect number#

  • The run's status is success, and scored_samples equals the total (or the gap is reported and explained).
  • You know which scorer, metric and reducer the number is, and you name them.
  • The oracle run scores 1.0 and the null run 0.0 on the current task version.
  • You read the failing samples (or a stated number of them) and classified each as model, scorer or task error.
  • The prompts as sent look right: no mangled braces, no literal {placeholders}.
  • The log's eval.model, model_generate_config and task_args are what you intended (5.6).
  • The task version was bumped after any change to the dataset, prompt or scorers, and you only compare runs with the same version.
  • The run came from a committed tree (revision.dirty is False) if the number will be quoted in a decision.
  • The uncertainty is reported (standard error, or an interval), and the sample size fits the decision.
  • Comparisons between runs are paired on (id, epoch) and use 10A.8's statistics.
  • The log file name is written next to the number.

Part 11: Older code and tutorials#

Reference

Inspect has been public since 2024 and has renamed things along the way. Current APIs first, always; when you meet an older name in a tutorial, notebook or someone else's task, this is what replaced it (as of 0.3.292). Most old names still work, some silently, so old code runs but reads differently from the docs.

You may see Use instead Status in 0.3.292
Task(plan=...) Task(solver=...) Still accepted, no warning (the source says a warning "would affect 100% of evals in the wild")
plan(...), Plan chain(...) or a list of solvers Still exported
Task(max_messages=...) Task(message_limit=...) Accepted without a warning
Task(tool_environment=...) Task(sandbox=...) Accepted with a deprecation warning
Task(epochs_reducer=...) Task(epochs=Epochs(n, reducer)) Accepted with a deprecation warning
multiple_choice(shuffle=True) shuffle_choices=True on the dataset loader Deprecated keyword (10B.9)
basic_agent() react() from inspect_ai.agent basic_agent() still exported, but the docs lead with react() (10B.14)
.json logs as the default .eval (default since 0.3.46) --log-format json still available (6.2)
--max-connections 10 described as "the default" Adaptive concurrency, starting at 20 and growing to 100 (since 0.3.217) Some docs pages still say 10, which is now the default only in static mode (10B.12)
Python 3.10 in setup instructions Python 3.11 or newer Required since 0.3.281
Model ids such as openai/gpt-4o The current ids from the provider pages Old ids in examples are placeholders; 02.9 explains model versioning
Recent features missing (Score.unscored(), pass_k, krippendorff_alpha, headline_metric, ci_wilson(), cascade()) Present since 0.3.214 to 0.3.262 (April to September 2026) Posts older than that will not mention them (10B.10)

When a tutorial and the docs disagree, the docs for your installed version win, and the installed package wins over both: inspect eval --help, help(Task) and the reference pages describe what you actually have.


Common misconceptions#

Misconception Reality
"Inspect is a safety-research tool, not for product evals." It was built for frontier safety and capability testing, but a product eval is an ordinary task: the triage port in Part 4 is about 180 lines including the data, and it runs keyless.
"An Inspect Task is the system under test." A Task is the whole eval: dataset + solver + scorer. The system under test is the solver chain plus the model chosen at run time.
"A solver is the model." A solver is the code that drives the model for one sample: prompt shaping, generate(), loops, tools. The model is a separate, run-time choice.
"--model always decides which model runs." In 0.3.292 a model set on the Task wins, silently. Check eval.model in the log.
"The exit code tells CI whether the eval worked." inspect eval exits 0 even when the log's status is error. Gate on the log.
"Accuracy is over all the samples in the dataset." It is over the samples that were scored. Errors (with --no-fail-on-error) and unscored samples leave the denominator.
"Inspect's accuracy should match evalkit's pass rate." They aggregate differently: Inspect reports each scorer separately; evalkit's pass rate requires every scorer to pass. Reconcile them per sample (4.8).
"Score.value must be between 0 and 1." It can be a label, any number, a bool, a list or a dict; metrics convert values with value_to_float(), which turns unknown strings into 0.
"A typo in a template placeholder raises an error." Unknown placeholders are left in place, and single braces in JSON examples are mangled, both silently.
"Mock runs tell me roughly what a real run will cost." mockllm counts characters as output tokens. Mock runs test plumbing and logic only.
"The log is just for debugging." The log is the product: the record you quote, compare, re-score, share and gate on.
"pip install inspect-ai gives me everything." Provider SDKs, pandas and pyarrow, the math extra and datasets are separate installs.
"A patch release of Inspect is safe to take blindly." It is 0.x; releases can carry breaking changes. Pin through the lock file and read the changelog.
"If a task file ran cleanly, the scorer must be right." Prove it with an oracle run (1.0) and a null run (0.0), and read the failing transcripts.

Key takeaways#

  • Inspect is UK AISI's MIT-licensed eval framework (co-developed with Meridian Labs): a Python library, the inspect CLI and the Inspect View log viewer. As of 24 November 2026 it is inspect-ai 0.3.292, needs Python 3.11+, and releases every few days with occasional breaking changes, so pin it with your lock file and upgrade on purpose.
  • Task = Dataset + Solver + Scorer. A dataset is a list of Samples; a solver transforms a TaskState and calls generate(); a scorer turns the final state and the target into a Score, and declares its metrics. The model is chosen at run time.
  • Ingredients are decorated factories (@task, @solver, @scorer) whose inner functions are async. The decorators register them, so the log records their names and arguments.
  • A run builds a TaskState per sample and epoch, runs the solver chain and the scorers concurrently, reduces epochs per sample, computes metrics per scorer and writes an EvalLog. Never depend on call order.
  • mockllm/model makes every run keyless: a fixed reply by default, or a scripted function keyed on the input. Its token counts are fake.
  • The triage eval ports cleanly, and the numbers reconcile: Inspect reports 0.917 (format) and 0.889 (labels) per scorer; evalkit's 83.3% and 0.903 are recomputed exactly from the same per-sample scores. Inspect has no built-in "all scorers must pass" aggregate.
  • inspect eval file.py runs every task in the file; use file.py@task. Task parameters come from -T, --task-config or task_args (which do nothing for an already-built Task). eval() returns list[EvalLog], one per task × model.
  • Logs go to ./logs under the current directory as {timestamp}_{task}_{id}.eval (a zip). Open them with inspect view or VS Code, share them with inspect view bundle, and remember they record your git remote, commit and dirty flag and every prompt and reply.
  • Read logs with list_eval_logs() (URIs, newest first), read_eval_log(header_only=True) for results and config, the full read for samples, read_eval_log_sample() for one, and inspect log dump from other languages. Look samples up by (id, epoch), not position.
  • First-day traps, all silent: a Task-level model beats --model; single braces in templates are mangled and unknown placeholders pass through; an empty target passes includes(); mixed task lists drop entries; inspect eval exits 0 on a failed run; unscored samples leave the denominator.
  • Defend every number: name the scorer and metric, report scored_samples of the total, run oracle and null controls, read the failing transcripts, remember that 12 samples is a smoke test, and compare runs paired on (id, epoch) with 10A.8's statistics.

Terms introduced in this lesson#

Term One-line definition
Inspect (Inspect AI) UK AISI's open-source eval framework: the inspect_ai Python package, the inspect CLI and the Inspect View log viewer
Task (Inspect) The complete definition of an eval: dataset + solver + scorer(s), plus defaults such as epochs and limits
@task The decorator that registers a function returning a Task, so the CLI can find it and the log can record its arguments
Task parameter An argument of a @task function, set with -T key=value, --task-config or task_args
Sample One case in an Inspect dataset: input, target, optional id, metadata and choices
Target A sample's ideal answer, list of acceptable answers or grading guidance; defaults to the empty string
Solver An async function that transforms a TaskState, for example by adding a system message or calling the model; the code that produces each sample's output
Solver chain A list of solvers run in order for each sample
TaskState The per-sample state solvers and scorers work on: messages, output, metadata, store, target
generate() The built-in solver (and the function passed to every solver) that calls the active model and appends its reply
Scorer (Inspect) An async function score(state, target) -> Score, registered with @scorer and its metrics
Score A scorer's verdict for one sample: value, answer, explanation, reason, metadata
CORRECT / INCORRECT The conventional score values "C" and "I" (with "P" partial and "N" no answer), converted to 1, 0, 0.5 and 0 by metrics
Metric (Inspect) A function computed over all samples' scores for one scorer, such as accuracy(), mean() or stderr()
Epoch (Inspect) One repetition of every sample; several epochs are reduced per sample before metrics
Reducer The rule that turns a sample's epoch scores into one value (default: mean)
EvalLog The structured record of a run: status, spec, plan, results, stats, samples and reductions
.eval file Inspect's default log format: a zip archive with one JSON file per sample and epoch plus header and summaries
Inspect View Inspect's web viewer for log directories, started with inspect view or built into the VS Code extension
View bundle A static website of the viewer plus logs, made with inspect view bundle, for sharing
mockllm/model Inspect's built-in fake model provider: a fixed reply by default, or scripted replies through custom_outputs
custom_outputs The mockllm model argument that scripts its replies: a list, a generator or a function of the input
Model string Inspect's provider/model-name identifier for a model, such as openai/gpt-6-luna
Task version The version you set on a Task to mark incompatible changes; logged as task_version
Header-only read read_eval_log(..., header_only=True): a log without its samples, fast for results and config
scored_samples The number of samples a scorer's metrics were computed over, which excludes errored and unscored samples
Fail-fast error policy Inspect's default fail_on_error=True: the first sample error stops the task with status error
Log gate A CI step that reads the log's status, coverage and metric instead of trusting the exit code
Oracle run / null run Control runs with a model that always answers correctly (should score 1) or always answers nonsense (should score 0)

Exercises#

All exercises run keyless with the files from this lesson.

  1. Sample selection (3.2, 5.3). Predict the accuracy of inspect eval hello.py@hello --model mockllm/model --sample-id h2, then of --limit 1. Run both and check.
  2. The all-gates scorer (4.8). Write a third scorer, triage_all, that returns C only when the format verdict is C and the labels value is 1.0, by calling the two existing scorers inside it. Add it with task_with() and run it with the scripted mock. Which evalkit number should it reproduce?
  3. Fix one answer (4.6, 4.8). Change T02's scripted reply to the correct labels (P1, technical) and predict all four numbers (format accuracy, labels mean, evalkit pass rate and mean score) before running.
  4. Epochs with a deterministic mock (5.3). Run inspect eval triage_scripted.py --epochs 3. Predict what happens to the metrics, the standard errors and the token counts, then explain each.
  5. A prompt bug the mock cannot see (9.2). Replace the doubled braces in PROMPT_TEMPLATE with single braces and run run_triage.py. Do the scores change? Why or why not, and what does that tell you about scripted mocks? How would you catch this bug automatically?
  6. Failures from the log (Part 7). Write a script that reads the newest log in logs-triage and prints, for every sample whose triage_format score has reason == "invalid_response_format", its id, the extracted answer and the explanation.
  7. Controls in CI (10.2, 9.6). Extend gate.py, or write a second script, so that CI fails if the oracle run scores below 1.0 or the null run above 0.0 on either scorer.
  8. The override surprise (5.6). Without running it, say which model the scored samples came from in eval(triage_scripted(), model="mockllm/other"), and how you would prove it from the log alone.
  9. A system_message variant (4.3, 2.5). Build a variant task that sends the rules as a system message with system_message() and the ticket as the user message, keeping the dataset and scorers. Does fake_triage still find the ticket? What would you expect to differ against a real model, and which field in the log tells a reader which variant produced a number?
Hints and what you should see
  1. --sample-id h2 runs only the banana sample, which the mock fails: accuracy 0.000. --limit 1 runs the first sample in dataset order, h1, which passes: accuracy 1.000. Each is a one-sample run, so the standard error is 0, which shows that a zero stderr can mean "too few samples to estimate", not "certain".

  2. A working version (run for this lesson, exercises.py):

    python
    @scorer(metrics=[accuracy(), stderr()])
    def triage_all() -> Scorer:
        fmt, lab = triage_format(), triage_labels()
    
        async def score(state: TaskState, target: Target) -> Score:
            f, l = await fmt(state, target), await lab(state, target)
            ok = f.value == CORRECT and l.value == 1.0
            return Score(value=CORRECT if ok else INCORRECT, answer=l.answer,
                         explanation=f"format={f.value} labels={l.value:.2f}")
        return score

    With task_with(triage(), scorer=[triage_format(), triage_labels(), triage_all()]) the real output was {'triage_format': 0.917, 'triage_labels': 0.889, 'triage_all': 0.833}: triage_all reproduces evalkit's 83.3% pass rate. Calling scorers from a scorer is fine: they are async functions.

  3. Format accuracy stays 0.917 (T11 still fails the format). Labels: eleven samples now score 1 and T11 scores 1/3, so (11 + 1/3) / 12 = 0.944 (the real run printed 0.944). evalkit pass rate: 11/12 = 91.7%. Mean score: ((11 + 11.333) / 2) / 12 = 0.931.

  4. The metrics and the standard errors are unchanged (0.917 ± 0.083 and 0.889 ± 0.075): the mock gives each sample the same answer in every epoch, the mean reducer turns three identical scores into the same value, and the standard error is computed over 12 reduced samples, not 36 sample-epochs. The usage roughly tripled (the real run reported 13,125 tokens [I: 10,029, O: 3,096], against 4,375 for one epoch). With a real model, epochs expose run-to-run variance; with a deterministic mock they only cost time.

  5. The scores do not change. The scripted mock answers by looking up the ticket text, so it never reads the broken instruction; a real model would. A scripted mock tests your scorers and plumbing, not your prompt. Catch the bug with a check on the rendered prompt: read log.samples[i].messages[0].text and assert that it contains {"priority": "P1"|"P2"|"P3" and no {{ or }: fragments, or more generally that no { is followed by a quote or a letter where you did not intend a placeholder.

  6. Read the full log (read_eval_log(list_eval_logs("logs-triage")[0])), loop over log.samples, and test sample.scores["triage_format"].reason == "invalid_response_format". Only T11 should print, with the answer {"priority": "P2"} and the explanation keys=['priority']; category=None; summary not a string. For large logs, filter read_eval_log_sample_summaries() on the score value first, then read only the matching samples with read_eval_log_sample() (summaries carry score values but not reasons).

  7. Run controls.py-style evals with log_dir="logs-oracle" and log_dir="logs-null", then check every scorer's first metric: the oracle's must equal 1.0 and the null's must equal 0.0, and both runs must have status success with full coverage. Exit 1 on any violation. Run this whenever triage.py changes.

  8. The Task's scripted mock (mockllm/model with custom_outputs), because task.model or model prefers the Task's model. Proof from the log alone: log.eval.model is mockllm/model, not mockllm/other, and the scores (0.917 and 0.889) are the scripted mock's, not the null run's zeros.

  9. Use solver=[system_message(RULES), prompt_template("<ticket>\n{prompt}\n</ticket>"), generate()], with the JSON braces in RULES doubled. fake_triage still works because input[-1].text is the last user message, which contains the ticket. Against a real model, moving instructions into the system role can change format compliance and accuracy (04.5). The log's plan (solver steps and their arguments) records which variant ran; bump the task version or give the variant its own task name so runs are never compared across variants by mistake.


Check yourself#

  1. What are the three ingredients of an Inspect Task, and which important thing is deliberately not one of them?
  2. In evalkit, task renders the prompt. What is the closest Inspect equivalent, and what does the word Task mean in Inspect instead?
  3. Why are solvers and scorers written as decorated factories with an inner async def, rather than as plain functions?
  4. What does mockllm/model return by default, and how do you make it return realistic, per-sample answers?
  5. Why should a scripted mock be a function keyed on the input rather than a list of outputs?
  6. inspect eval evals.py --model openai/gpt-6-luna ran three tasks. Why, and how do you run only one?
  7. What type does eval() return, and how many items for two tasks and three models?
  8. Where does a log go by default, and what three things does its file name encode?
  9. Name four things a log records besides the scores that matter for reproducibility, and one that matters for privacy.
  10. What is the difference between read_eval_log(path, header_only=True) and read_eval_log(path), and when do you use each?
  11. The same triage run shows 0.917, 0.889 and 83.3%. Which is "the" accuracy?
  12. A CI job runs inspect eval and is green, but the eval crashed on sample 2. Explain, and say what the job should do instead.
  13. With --no-fail-on-error, a run reports accuracy 1.000. Why should you not believe it yet?
  14. Your system prompt says Reply like {"label": "spam"} and format accuracy is mysteriously low. What happened, and how do you fix it?
  15. Why is an oracle run that scores 0.92 good news?

Further resources#

Official documentation (every URL checked on 24 November 2026; each page also exists as Markdown by adding .md to the URL, and llms.txt indexes them all for an LLM assistant):

  • Inspect home and "Hello, Inspect": what Inspect is, installation and the two first examples.
  • Tutorial: worked examples of benchmarks, model grading, multiple choice, custom scorers and solvers.
  • Tasks: task options, parameters, task_with(), the configuration layers and the override reference, packaging.
  • Datasets, Solvers and Scorers: the three ingredients, in depth (lessons 10B.9 and 10B.10 follow them).
  • Scoring policy: what counts in the denominator and why; read it before you trust any metric.
  • Options: every CLI option and its environment variable, and .env handling.
  • Models and Providers: model strings, SDKs and key variables for every provider; more complete than any table in this lesson.
  • Log Viewer and VS Code Extension: Inspect View, live viewing, bundling and publishing.
  • Eval Logs: log formats, the EvalLog schema and the reading API.
  • Reference pages: inspect_ai (Task, eval, task_with), inspect_ai.log and the inspect eval CLI.
  • CHANGELOG: read the Breaking Changes section of every release between your version and the one you upgrade to.

Code and packages:

  • UKGovernmentBEIS/inspect_ai on GitHub: the source, issues and licence. When the docs and behaviour disagree (as in 5.6), the source is the final word for your version.
  • inspect-ai on PyPI: versions, release dates and the Python requirement.

Within this course: 10B.1 for why and when to adopt a framework, 10B.9 to 10B.13 for each Inspect component in depth, and 10B.18 for a reading plan through the official docs.


← 10B.7: DeepEval in Production: Red Teaming, CI/CD, Prompt Optimization and Confident AI | Module 10B overview | 10B.9: Inspect Datasets, Solvers and Task Configuration (optional) →

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