10B.13 Inspect Logs, Analysis and Extending Inspect (optional)

ProductionLesson 13 of 1822,908 wordsOptional13 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

An Inspect run produces one thing that outlives it: the log. Everything you will ever say about the run (the number in the launch review, the regression you block in CI, the ticket you show a colleague, the comparison with last month's model) is read out of a log file, so the quality of your analysis depends on how well you know that file and the tools that read it. 10B.8 showed where logs go and how to read one back; this lesson opens them up completely. You will learn the two file formats and when each fits, the whole EvalLog schema level by level, the event transcript and its attachments, every way of reading a log from the cheapest to the most expensive, how to write, convert, tag and annotate logs with an audit trail, how to count a sample as a failure on the record, how to publish logs safely, and the four pandas dataframes that turn a directory of logs into tables you can group, join and query with SQL. Then you will use them the way an evaluation owner does: refuse to compare runs that did not measure the same thing, put coverage next to every number, find what changed ticket by ticket, and turn a log into the run record that 10A.8 asks for. The last part extends Inspect itself: a package that ships a task, a scorer, a model provider that wraps any call_model(prompt) -> str function, and a tracking hook, all registered through one entry point. Every sample runs keyless on Inspect's mock model and every output shown is what the run printed.

What you'll learn

  • The analysis workflow from run to decision, and where each tool (viewer, log API, dataframes, evalkit's statistics) fits in it
  • The .eval and .json formats: what is inside the zip, the size difference measured, conversion, the NaN trap for strict JSON parsers, and every option that controls what is written (--no-log-samples, image, model-API and refusal logging, buffering, shared live logs, transcript log levels, file-name patterns)
  • Where logs can live (local disk, S3, Hugging Face storage buckets, Azure, any fsspec filesystem) and the security and cost notes that come with each
  • The complete EvalLog schema: EvalSpec, EvalConfig, EvalPlan, EvalResults, EvalScore, EvalStats, EvalSample, reductions, status, error, log_updates, and what the log of a failed run still contains
  • What a log lets you reproduce, and what no log can pin
  • The event transcript: the event catalogue, the span tree, model events with the raw provider call, state diffs, score events, and attachments with resolve_sample_attachments()
  • The reading API as a cost ladder: headers, summaries, single samples, batches by id, streaming, exclude_fields, reading from bytes, async variants, and inspect log list | dump | convert | schema for other languages
  • Writing and editing: write_eval_log() semantics, tags and metadata edits with edit_eval_log() and provenance, the whole editing family, zeroing a sample with an empty attempt and zero_samples(), and the trust rules for logs written by someone else
  • Inspect View for teams: task views with ViewerConfig, untrusted content, live and shared logs, secure remote access, bundling and publishing, and scrubbing a log before it leaves your machine
  • The four dataframes (evals_df, samples_df, messages_df, events_df): their real shapes and columns, naming rules, id versus sample_id, one row per epoch, column groups, custom columns, strict mode, prepare() operations and SQL joins with DuckDB
  • Analysis recipes: comparability checks, run tables with coverage, slices, per-sample changes and flakiness, failed runs, and a log turned into a 10A.8-style run manifest with a dataset fingerprint
  • Extending Inspect: the registry and inspect_ai entry points, a packaged task and scorer, a custom model provider with recorded raw calls and model arguments, lifecycle hooks for experiment tracking, required hooks, and where approvers, sandboxes and filesystems plug in
  • The evalkit ↔ Inspect mapping for logs, analysis and extension, what 10A.10 now gets wrong, and the older APIs you will meet in tutorials

What you don't need

  • An API key. Every runnable sample uses mockllm with scripted outputs, a rule-based provider you write yourself, or plain log files. The few samples that would need cloud credentials (S3, Hugging Face, Azure) are labelled illustrative.
  • A server. Nothing here starts one: inspect view is described, not run, and inspect view bundle writes static files.
  • The eval concepts themselves. Paired statistics are 10A.8 and their Inspect form is 10B.10, Part 8; score edits and exclusions for judge adjudication are 10B.11, Part 10; eval sets, retries and the CI gate are 10B.12. This lesson links to them rather than repeating them.
  • Inspect's components. Tasks, datasets and solvers are 10B.9; scorers and metrics are 10B.10. Tools, agents and sandboxes (whose transcripts you will analyse with the same tools) are 10B.14 and 10B.15; Inspect Scout and the wider ecosystem are 10B.16.

Setup

You need Python 3.11 or newer 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 pandas pyarrow duckdb
# or: pip install inspect-ai pandas pyarrow duckdb

pandas and pyarrow are required by the dataframe functions (Inspect does not install them), and duckdb is used in one SQL sample only. The samples build on the triage eval of 10B.8, Part 4: put triage.py and fake_triage.py from that lesson in the same folder, save each sample under the file name its first comment gives, and run Python files with uv run python file.py and CLI commands with uv run inspect ... from that folder. Part 10 builds a small package in a subfolder, acme-evals/, and installs it with uv add --editable ./acme-evals (or pip install -e ./acme-evals). It is a different package from the acme_evals of 10B.9, 8.8, so build it in a fresh project folder.

Make the folder a git repository first. Inspect records the git remote, commit and dirty flag in every log, and two samples below (3.1 and 7.5) depend on that. In the lab folder, once, before the first run:

bash
printf 'logs*/\npublish/\ntriage-www/\n.venv/\n__pycache__/\n' > .gitignore   # outputs must not make the tree dirty
git init -q && git add -A && git commit -qm lab
git remote add origin https://example.com/acme/support-evals.git          # a placeholder remote

Without the .gitignore line the fresh logs-lab/ folder makes the tree dirty (dirty=True); without a repository eval.revision is None. The commit hash in your logs will differ from the one printed here (fada17f); the dirty=False flag and the remote will match.

Versions (current at time of writing, checked on PyPI on 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT licence, Python ≥ 3.11), inspect-viz 0.4.2 (described, not installed). Inspect is on 0.x and releases every few days, sometimes with breaking changes, so treat every field list here as a snapshot and check the reference pages of the version you run. Every sample marked as run was executed on 24 November 2026 with Python 3.13.14, inspect-ai 0.3.292, pandas 3.1.1, pyarrow 26.0.1 and duckdb 2.0.1, inside a throwaway git repository built with the recipe above, whose remote was the placeholder https://example.com/acme/support-evals.git (logs record your remote; 7.5 shows why that matters). Timestamps, random ids and file sizes in the outputs will differ on your machine; the numbers will not.


What you must be able to do after this lesson#

  • Choose the right log read for the job (header-only, summaries, single sample, full read)
  • Read an EvalLog and find its status, scores and samples
  • Check that two runs are comparable using what the log records
  • Build a samples_df or evals_df dataframe and count its rows
  • Walk a sample's events to see what the model saw and did
  • Protect yourself from logs that name code to run
  • Defend a number back to the log it came from

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Logs are the product. Where is the number coming from?" Part 1
"The log directory is 40 GB. Can we make it smaller?" 2.2 and 2.4
"The dashboard crashes parsing the log JSON." 2.3
"Put the logs in the bucket so everyone can see them." 2.5
"Which field says which prompt produced this?" Part 3
"Can we reproduce last month's number exactly?" 3.10
"Show me the raw request that went to the provider." 4.3
"Reading the log takes minutes. Is there a faster way?" Part 5
"Mark this run as reviewed, and say who reviewed it." 6.2
"That sample was contaminated. Count it as a failure." 6.4
"Publish the logs for the partner team, without our repo URL." 7.5
"Give me a table of every run by model and slice." Part 8
"Is v2 better than v1, and what broke?" Part 9
"Can we run Inspect against our in-house model endpoint?" 10.3
"Send every run's scores to our tracking system automatically." 10.5
"Make sure nobody on the team runs evals without the tracking hook." 10.7

Part 1: From runs to decisions: the analysis workflow#

1.1 What 10B.8 covered, and what this lesson adds#

10B.8, Parts 6 and 7 gave you the basics: logs go to ./logs under the current directory as {timestamp}_{task}_{id}.eval, a .eval file is a zip archive, Inspect View shows a log directory in the browser, inspect view bundle makes a static site, inspect log export-config turns a log back into a run config, and list_eval_logs(), read_eval_log(), read_eval_log_sample() and read_eval_log_sample_summaries() read a log back in Python. That lesson also warned about three traps you should keep in mind here: EvalLogInfo.name and log.location are URIs, not paths; log.samples is ordered by epoch then id, not dataset order; and logs record your git remote.

This lesson goes the rest of the way:

Topic 10B.8 This lesson
Formats .eval is a zip; .json exists Sizes measured, conversion, NaN, every logging option, remote storage (Part 2)
Schema The top-level fields Every level, including failed runs and what a log cannot pin (Part 3)
Events "The transcript the viewer draws" The catalogue, the span tree, raw calls, attachments (Part 4)
Reading The four core functions The full API as a cost ladder, plus the CLI (Part 5)
Editing Mentioned Writing, tags and metadata with provenance, zeroing, trust (Part 6)
Viewer Starting it, the tabs, bundling Task views, untrusted content, team access, scrubbing (Part 7)
Dataframes Named All four in depth (Part 8) and used for analysis (Part 9)
Extending Not covered Packages, providers, hooks and the other extension points (Part 10)

1.2 The workflow#

Every serious use of Inspect follows the same loop. Runs write logs into a directory; people look at the logs in the viewer, and code reads them through the log API or the dataframes; before any number is compared, the code checks that the runs are comparable and complete; then come error analysis and paired statistics; and the result is a decision, a gate verdict and a tracking record. Annotations about the decision (who reviewed it, what was excluded and why) go back into the logs with provenance, so the log directory stays the single source of truth.

flowchart LR
    RUN["eval() / inspect eval<br/>one log per task x model"] --> DIR[("Log directory<br/>local, s3://, hf://, az://")]
    DIR --> VIEW["Inspect View<br/>and bundles<br/>(people)"]
    DIR --> API["inspect_ai.log<br/>headers, summaries,<br/>samples, events<br/>(code)"]
    DIR --> DF["inspect_ai.analysis<br/>evals_df, samples_df,<br/>messages_df, events_df"]
    API --> CHECK["Comparability and<br/>coverage checks"]
    DF --> CHECK
    CHECK --> STATS["Paired statistics<br/>(evalkit 10A.8 on reductions)"]
    CHECK --> ERR["Error analysis<br/>slices, failing transcripts"]
    STATS --> DEC["Decision, gate,<br/>tracking record"]
    ERR --> DEC
    DEC -. "tags, metadata,<br/>score edits with provenance" .-> DIR

Two design choices in Inspect make this loop work, and they are worth naming because they are not universal:

  • The log is complete. It holds the configuration, the transcripts and the scores, not just the metrics. That is what lets you re-score a run with a new scorer (10B.11, Part 11), re-reduce it, audit it or analyse a slice nobody thought of when it ran, without paying for the model calls again.
  • The log is a file you own. No server, no account. You choose where it lives, who sees it and how long it is kept. The price is that the governance (retention, access, scrubbing) is your job, which Parts 2 and 7 cover.

1.3 The lab: three runs to analyse#

An analysis lesson needs more than one log. The lab is a log directory with three runs of the triage task from 10B.8, each with two epochs, against three scripted "model versions":

Run Model string Behaviour Tags
v1 mockllm/triage-v1 10B.8's scripted answers: T02 wrong, T11 broken JSON baseline
v2 mockllm/triage-v2 Fixes T02 and T11, regresses T06 (wrong category), and is flaky on T05 (every second call gets the priority wrong) candidate
v3 mockllm/triage-v3 Like v1, but the "provider" fails on T09, so the run ends in error candidate

mockllm accepts any model name after the slash, which gives each run its own model string in the logs and in the dataframes, exactly as real provider models would.

python
# lab_models.py: three scripted "models" for the analysis lab (lesson 10B.13)
"""Stand-ins for three model versions, so every analysis in the lesson runs keyless.

triage-v1: 10B.8's fake_triage answers (T02 wrong, T11 broken JSON).
triage-v2: fixes T02 and T11, regresses T06, and is flaky on T05.
triage-v3: like v1, but the "provider" fails on T09, so the run ends in error.
mockllm accepts any model name after the slash, which gives each run its own
model string in the logs and the dataframes.
"""
from collections import defaultdict

from inspect_ai.model import ChatMessage, GenerateConfig, Model, ModelOutput, get_model

from fake_triage import RESPONSES
from triage import TICKETS

V2 = dict(
    RESPONSES,
    T02='{"priority": "P1", "category": "technical", "summary": "Whole team locked out by 500 errors."}',
    T06='{"priority": "P2", "category": "account", "summary": "App crashes on reports tab."}',  # regression
    T11='Sure! Here is the JSON: {"priority": "P2", "category": "billing", '
        '"summary": "Second duplicate Pro charge, refund requested."}',
)


def ticket_id(prompt: str) -> str:
    for tid, text, _ref, _meta in TICKETS:
        if text and text in prompt:
            return tid
    return "T10"                                     # the empty ticket


def scripted(name: str, responses: dict[str, str], *, flaky: str | None = None,
             fail_on: str | None = None) -> Model:
    calls: dict[str, int] = defaultdict(int)

    def generate(input: list[ChatMessage], tools, tool_choice,
                 config: GenerateConfig) -> ModelOutput:
        tid = ticket_id(input[-1].text)
        if tid == fail_on:
            raise RuntimeError("503 from the model gateway (simulated)")
        calls[tid] += 1
        reply = responses[tid]
        if tid == flaky and calls[tid] % 2 == 0:     # every second call gets the priority wrong
            reply = reply.replace('"P2"', '"P3"')
        return ModelOutput.from_content(model=name, content=reply)

    return get_model(f"mockllm/{name}", custom_outputs=generate, memoize=False)


def model_v1() -> Model:
    return scripted("triage-v1", RESPONSES)


def model_v2() -> Model:
    return scripted("triage-v2", V2, flaky="T05")


def model_v3() -> Model:
    return scripted("triage-v3", RESPONSES, fail_on="T09")

The script that writes the lab, with tags and metadata set at run time (both are recorded in the log and editable later, 6.2):

python
# l01_make_lab.py: write the log directory that the rest of the lesson analyses (lesson 10B.13)
from inspect_ai import eval

from lab_models import model_v1, model_v2, model_v3
from triage import triage

RUNS = [  # (model, tags, metadata)
    (model_v1(), ["baseline"], {"variant": "v1", "owner": "support-evals"}),
    (model_v2(), ["candidate"], {"variant": "v2", "owner": "support-evals"}),
    (model_v3(), ["candidate"], {"variant": "v3", "owner": "support-evals"}),
]

for model, tags, metadata in RUNS:
    log = eval(triage(), model=model, epochs=2, log_dir="logs-lab",
               tags=tags, metadata=metadata, display="none")[0]
    scores = {s.name: round(next(iter(s.metrics.values())).value, 3)
              for s in (log.results.scores if log.results else [])}
    print(f"{log.eval.model:20} {log.status:8} {scores or log.error.message[:60]}")
bash
uv run python l01_make_lab.py
Output3 lines
mockllm/triage-v1    success  {'triage_format': 0.917, 'triage_labels': 0.889}
mockllm/triage-v2    success  {'triage_format': 1.0, 'triage_labels': 0.958}
mockllm/triage-v3    error    RuntimeError('503 from the model gateway (simulated)')

v1 reproduces 10B.8's numbers (epochs do not change a deterministic model's mean). v2 looks better on both scorers, which is exactly the situation where an evaluation owner should slow down: a better mean can hide a regression, and the flaky ticket means the number moves between runs. v3 failed, and its log has no results at all, but as 3.9 shows, it is far from empty. The rest of the lesson analyses these three files.

A small helper finds each run's log by its model name, so later samples do not depend on file names or timestamps:

python
# lab_paths.py: find each lab run's log by its model name (lesson 10B.13)
from inspect_ai.log import EvalLogInfo, list_eval_logs, read_eval_log


def lab_logs(log_dir: str = "logs-lab") -> dict[str, EvalLogInfo]:
    """{'v1': info, 'v2': info, 'v3': info}, keyed on the model name's suffix."""
    return {read_eval_log(i, header_only=True).eval.model.rsplit("-", 1)[-1]: i
            for i in list_eval_logs(log_dir)}

Part 2: Log files: formats, storage and what gets written#

2.1 Inside a .eval file#

10B.8, 6.2 listed a .eval archive with unzip -l. Here the same look is taken from Python, on the v1 lab log (two epochs, so two files per sample), together with the compression and a format comparison:

python
# l02_formats.py: what is in a .eval file, .eval vs .json, and the NaN trap (lesson 10B.13)
import json
import os
import zipfile

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.log import convert_eval_logs, list_eval_logs, read_eval_log, write_eval_log
from inspect_ai.scorer import CORRECT, Score, Target, accuracy, scorer
from inspect_ai.solver import TaskState


def path_of(uri: str) -> str:
    return uri.removeprefix("file://")          # EvalLogInfo.name is a URI


# 1. A .eval file is a zip archive: list its members and their compression.
v1 = next(i for i in list_eval_logs("logs-lab")
          if read_eval_log(i, header_only=True).eval.model.endswith("v1"))
with zipfile.ZipFile(path_of(v1.name)) as z:
    members = z.infolist()
    print("members:", len(members), "| compression ids:", sorted({m.compress_type for m in members}))
    for m in members:
        if not m.filename.startswith("samples/") or m.filename.startswith("samples/T01"):
            print(f"  {m.filename:32} {m.file_size:>7} bytes -> {m.compress_size:>6} stored")

# 2. The same log as .json, and a whole directory converted.
log = read_eval_log(v1)
write_eval_log(log, "logs-json/v1.json", format="json")
eval_size, json_size = os.path.getsize(path_of(v1.name)), os.path.getsize("logs-json/v1.json")
print(f"\n.eval {eval_size:,} bytes | .json {json_size:,} bytes | ratio {json_size / eval_size:.1f}x")
convert_eval_logs("logs-lab", to="json", output_dir="logs-lab-json", overwrite=True)
print("converted:", len(os.listdir("logs-lab-json")), "files, extensions",
      sorted({os.path.splitext(f)[1] for f in os.listdir("logs-lab-json")}))
same = read_eval_log("logs-lab-json/" + os.path.basename(path_of(v1.name)).replace(".eval", ".json"))
print("round trip identical results:", same.results.model_dump() == log.results.model_dump())


# 3. Unscored samples are NaN, and NaN is not valid JSON for strict parsers.
@scorer(metrics=[accuracy()])
def picky():
    async def score(state: TaskState, target: Target) -> Score:
        if state.sample_id == "s2":
            return Score.unscored(explanation="grader unavailable")
        return Score(value=CORRECT)
    return score


nan_log = eval(Task(dataset=[Sample(id="s1", input="a"), Sample(id="s2", input="b")],
                    scorer=picky()), model="mockllm/model", log_dir="logs-nan",
               log_format="json", display="none")[0]
text = open(path_of(nan_log.location)).read()
print("\n'NaN' appears in the .json log:", "NaN" in text)


def reject(constant: str):
    raise ValueError(f"strict JSON has no {constant}")


try:
    json.loads(text, parse_constant=reject)      # what a browser's JSON.parse does
except ValueError as e:
    print("strict parse fails:", e)
print("Python's default json.loads accepts it:", type(json.loads(text)).__name__)
bash
uv run python l02_formats.py
Output18 lines
members: 29 | compression ids: [93]
  _journal/start.json                 3395 bytes ->   1254 stored
  samples/T01_epoch_1.json           12325 bytes ->   2927 stored
  samples/T01_epoch_2.json           12341 bytes ->   2928 stored
  _journal/summaries/1.json          21599 bytes ->   2867 stored
  summaries.json                     21599 bytes ->   2867 stored
  reductions.json                     4116 bytes ->    740 stored
  header.json                         4557 bytes ->   1601 stored

.eval 81,326 bytes | .json 433,588 bytes | ratio 5.3x
Converting log files...

converted: 3 files, extensions ['.json']
round trip identical results: True

'NaN' appears in the .json log: True
strict parse fails: strict JSON has no NaN
Python's default json.loads accepts it: dict

What the first block tells you:

  • Compression id 93 is Zstandard (zstd). Every member is zstd-compressed, which is why the stored sizes are a quarter or less of the real sizes. Python's own zipfile can list the members but (before Python 3.14) cannot decompress zstd members, which is one more reason to read logs through Inspect's API and not by hand.
  • One member per sample per epoch (samples/T01_epoch_1.json, samples/T01_epoch_2.json), so a reader can load one sample without touching the others. This is what makes header-only reads, summaries and single-sample reads cheap (Part 5).
  • header.json holds everything except the samples (spec, plan, results, stats); summaries.json holds the thin per-sample records; reductions.json holds the per-sample values after epoch reduction; _journal/ is written while the run is in progress (start record and periodic summary flushes), which is what crash recovery and live viewing read.

2.2 .eval or .json#

The second block is the size comparison: the same log was 81 KB as .eval and 434 KB as .json, 5.3 times larger. The docs say "typically 1/8 the size"; the ratio grows with transcript length because, since 0.3.206, .eval logs also de-duplicate repeated messages across model events (an agent that resends a growing conversation on every turn would otherwise store it quadratically; the docs report 10:1 improvements on agentic benchmarks and more on long-horizon tasks). Twelve short single-turn samples cannot show that effect, so expect a bigger gap on your agent logs.

.eval (default since 0.3.46) .json
What it is Zip archive of JSON members, zstd-compressed One plain JSON document
Size Small; de-duplicated content Several times larger
Partial reads One sample, the header or the summaries without the rest The whole file is parsed
Inspect View Loads incrementally, fast at any size "Can be slow to load in Inspect View if larger than 50MB" (docs)
Readable without Inspect No (zstd, de-duplicated attachments) Yes, but still use the API: NaN values and attachments
Choose it when Always, unless you have a reason not to A tool outside Python must read the file directly and cannot call inspect log dump

Switch per run with --log-format json (or log_format="json" in eval()), or per project with INSPECT_LOG_FORMAT=json in .env. Convert existing logs with convert_eval_logs() or inspect log convert, which the probe used on the whole lab directory: three .json files came out, and the round trip preserved the results exactly. Both formats can sit side by side in one directory and every reading function accepts both (format="auto" decides by extension).

Three conversion rules from the docs:

  • An output directory is always required, deliberately: converting in place would leave two files that differ only in format, and tools that list the directory would count the run twice.
  • Existing files are not overwritten unless you pass overwrite=True (--overwrite); logs already in the target format are copied.
  • --stream N limits how many samples are held in memory during conversion, which matters for multi-gigabyte logs. Converting old .json logs to .eval is also how you get the de-duplication and compression on logs written before 0.3.206.

2.3 NaN and Inf: the strict-JSON trap#

The third block of the output is a trap that bites the first time someone builds a dashboard on top of Inspect logs. A sample that a scorer could not score (here Score.unscored(), 10B.10, 4.1) carries the value NaN, and Inspect writes it as the bare token NaN in the JSON. Python's json module accepts that by default; a strict parser (the probe's parse_constant=reject behaves like a browser's JSON.parse, Node, many Go and Java libraries and some jq modes) rejects the whole document.

What to do about it:

  • Read logs from Python with Inspect's API and export only what the other system needs, converting NaN to null yourself (math.isnan() checks, or pandas' to_json(), which writes null for NaN).
  • From JavaScript, the docs recommend a JSON5 parser, which accepts NaN and Infinity; for other languages they list JSON5 implementations.
  • Never treat NaN as zero when you convert. It means "not scored", and it is outside the denominator (10B.10, 4.6). A silent NaN → 0 conversion turns unscored samples into failures and changes the metric.

2.4 Controlling what is logged#

By default Inspect logs everything a reviewer could need. Each default has a cost (disk, transfer, privacy), and each can be turned down. The options, all available as eval() arguments, CLI flags and (most) INSPECT_EVAL_* variables in .env:

Option (CLI) Default What it changes When to change it
--no-log-samples (log_samples=False) Samples logged Writes results and config only Huge sweeps where only the metrics matter; you lose re-scoring and error analysis
--no-log-images (log_images=False) Images and media kept Drops media bytes from the completed log (they are still sent to the model) Multimodal evals with .json logs; images are what make logs huge (10B.9, 2.7)
--log-model-api / --no-log-model-api Raw request and response for the first few calls per model, plus every failed call Logs every raw provider call, or errors only All calls when debugging a provider integration; off for large production-like runs
--log-refusals Off Logs model refusals as warnings (a refusal counter is always shown in the display) Safety-sensitive evals; --fail-on-refusal fails the sample instead (10B.12)
--no-log-realtime Realtime events on Stops writing live events used by the viewer during a run Very high-throughput runs where nobody watches live
--log-buffer N 10 samples per flush (100 for .json on remote filesystems) How many completed samples are buffered before a write Bigger for throughput on remote storage; smaller to lose less in a crash
--log-shared [secs] Off Also syncs live-log data to the shared filesystem every 10 s (or secs) Colleagues watching a live run on S3 (7.3)
--log-level-transcript LEVEL info Which Python logging records are saved into sample transcripts http or debug when chasing a provider problem (2.7)
--log-dir DIR / INSPECT_LOG_DIR ./logs Where logs go Always, per project (2.5)
--log-format (eval or json) / INSPECT_LOG_FORMAT eval File format Rarely (2.2)

Provider request ids are logged regardless of these options (ModelEvent.request_ids for OpenAI and OpenAI-compatible providers, Anthropic, Groq, Mistral and Bedrock, except in batch mode, and ModelOutput.response_id), so you can always point a provider's support team at a specific request.

What log_samples=False does in practice, on the v1 scripted model:

python
# l13_log_options.py: what the logging options change in the file (lesson 10B.13)
import os

from inspect_ai import eval
from inspect_ai.log import list_eval_logs, read_eval_log

from lab_models import model_v1
from triage import triage

os.environ["INSPECT_EVAL_LOG_FILE_PATTERN"] = "{task}_{model}_{id}"   # read when the log is named

for label, options in [("default", {}), ("log_samples=False", {"log_samples": False})]:
    log = eval(triage(), model=model_v1(), log_dir=f"logs-opt-{len(options)}",
               display="none", **options)[0]
    info = list_eval_logs(f"logs-opt-{len(options)}")[0]
    full = read_eval_log(info)
    print(f"{label:18} {info.size:>7,} bytes | samples in file: "
          f"{None if full.samples is None else len(full.samples)} | "
          f"accuracy {full.results.scores[0].metrics['accuracy'].value:.3f}")
print("file name:", info.name.rsplit("/", 1)[-1])
Output3 lines
default             44,598 bytes | samples in file: 12 | accuracy 0.917
log_samples=False    3,925 bytes | samples in file: 0 | accuracy 0.917
file name: 2026-11-24T18-01-55-00-00_triage_mockllm-triage-v1_iKSubrGRugneTHuQDuB6De.eval

The metrics are identical and the file is a tenth of the size, but samples is an empty list: no transcripts, no per-sample scores, no reductions to compare runs with. That trade is almost never worth it for an eval you will act on, because every analysis in Part 9 and every paired comparison in 10B.10, 8.3 needs per-sample data. Reserve it for exploratory sweeps whose only output is a chart.

2.5 Where logs can live#

--log-dir, INSPECT_LOG_DIR, list_eval_logs(), read_eval_log() and write_eval_log() all accept any fsspec URI, so a log directory can be a local folder, a bucket or a mounted share, and every function in this lesson works the same on each:

Storage URI Needs Notes from the docs (as of November 2026)
Local disk ./logs, /data/evals Nothing A relative INSPECT_LOG_DIR in .env resolves relative to the .env file, not to where you run the command
Amazon S3 s3://bucket/prefix Built in (s3fs); AWS credentials Large .eval logs use multipart uploads; a killed write leaves an unfinished upload that is billed as storage until removed, so add a lifecycle rule that aborts incomplete multipart uploads after a day
Hugging Face storage buckets hf://buckets/<owner>/<bucket>/<path> huggingface_hub (≥ 1.6.0), hf auth login or HF_TOKEN Inspect does not create the bucket; bucket contents are mutable, so use a unique prefix per shared run
Azure Blob / Data Lake az://, abfs://, abfss:// adlfs (≥ 2025.8.0) Prefer managed identity; set AZURE_STORAGE_ANON=false explicitly, or the default is anonymous access and your credentials are ignored
Google Cloud Storage, DVC and others gs://, ... The matching fsspec package Any fsspec implementation; custom filesystems are in 10.9

A shared bucket is how a team turns Inspect logs into a shared record. An illustrative .env for S3:

bash
# .env (illustrative: needs a real bucket and credentials)
INSPECT_LOG_DIR=s3://acme-eval-logs/support-triage
AWS_DEFAULT_REGION=eu-west-2
# credentials come from your normal AWS profile or role, not from this file

2.6 Log file names#

The default name is {timestamp}_{task}_{id}, and the timestamp prefix is mandatory so files sort by start time. INSPECT_EVAL_LOG_FILE_PATTERN customizes the rest with any combination of {task}, {model} and {id}; the probe in 2.4 set {task}_{model}_{id} and got:

text
2026-11-24T18-01-55-00-00_triage_mockllm-triage-v1_iKSubrGRugneTHuQDuB6De.eval

The slash in mockllm/triage-v1 became a hyphen. Putting the model in the name helps humans scanning a directory with many models; code should still select logs by their header fields, not by parsing file names.

2.7 Python logging inside the transcript#

Inspect installs a handler for Python's standard logging module, so the logger.info(...) calls in your solvers, scorers and tools are saved into the sample's transcript (as logger events) and shown in the viewer. The defaults: warning and above print on the console; info and above are saved in the transcript. The levels, from most to least verbose, are debug, trace, http, info, warning, error, critical.

Setting Controls
--log-level / INSPECT_LOG_LEVEL Console output level
--log-level-transcript / INSPECT_LOG_LEVEL_TRANSCRIPT Transcript level
INSPECT_PY_LOGGER_FILE (+ INSPECT_PY_LOGGER_LEVEL) Also write log records to an external file (follow it with tail -f)
INSPECT_PY_LOGGER_FORMAT Console formatter: rich, plain or json (use plain or json in CI and containers)

The practical rule: log with logger = logging.getLogger(__name__) and logger.info() generously inside scorers (what was extracted, which branch decided the verdict). It costs nothing on the console and makes the transcript answer "why did this sample score 0?" without re-running anything.


Part 3: The EvalLog schema, level by level#

3.1 The whole schema in one script#

10B.8, 7.2 drew the top level of an EvalLog. This script walks every level on the v2 lab log, then looks at the failed v3 log:

python
# l03_schema.py: the EvalLog schema, level by level, on the lab logs (lesson 10B.13)
from inspect_ai.log import EvalLog, list_eval_logs, read_eval_log


def fields(obj) -> list[str]:
    return list(type(obj).model_fields)


logs = {read_eval_log(i, header_only=True).eval.model.split("-")[-1]: i
        for i in list_eval_logs("logs-lab")}
log: EvalLog = read_eval_log(logs["v2"])

print("EvalLog     :", fields(log))
print("EvalSpec    :", len(fields(log.eval)), "fields, e.g.", fields(log.eval)[:6], "...")
print("EvalConfig  :", log.eval.config.model_dump(exclude_none=True))
print("EvalDataset :", log.eval.dataset.model_dump(exclude_none=True)["samples"], "samples, shuffled =",
      log.eval.dataset.shuffled)
print("EvalPlan    :", [(s.solver, list(s.params)) for s in log.plan.steps])
print("tags/meta   :", log.eval.tags, log.eval.metadata)
print("revision    :", log.eval.revision)

r = log.results
print("\nEvalResults :", fields(r))
print("  totals    :", r.total_samples, "total,", r.completed_samples, "completed")
for s in r.scores:
    print(f"  EvalScore : name={s.name} scorer={s.scorer} reducer={s.reducer} "
          f"scored={s.scored_samples} unscored={s.unscored_samples} "
          f"metrics={ {k: round(m.value, 3) for k, m in s.metrics.items()} }")
print("EvalStats   :", fields(log.stats))
u = log.stats.model_usage[log.eval.model]
print("ModelUsage  :", u.model_dump(exclude_none=True))

smp = next(s for s in log.samples if s.id == "T05" and s.epoch == 2)
print("\nEvalSample  :", len(fields(smp)), "fields")
print("  T05/2     :", {k: getattr(smp, k) for k in ("id", "epoch", "target")},
      "| scores", {k: v.value for k, v in smp.scores.items()},
      "| error", smp.error, "| uuid", smp.uuid[:8] + "...")
print("  log order :", [(s.id, s.epoch) for s in log.samples][:4], "...")
red = log.reductions[1]
print("Reductions  :", red.scorer, red.reducer, [(x.sample_id, round(x.value, 3)) for x in red.samples[4:6]])

bad = read_eval_log(logs["v3"])
print("\nv3 status   :", bad.status, "| results:", bad.results, "| samples logged:", len(bad.samples or []))
print("v3 error    :", bad.error.message, "| traceback lines:", len(bad.error.traceback.splitlines()))
print("v3 errored samples:", [(s.id, s.epoch, s.error.message[:30]) for s in bad.samples if s.error])
bash
uv run python l03_schema.py
Output23 lines
EvalLog     : ['version', 'status', 'eval', 'plan', 'results', 'stats', 'error', 'invalidated', 'log_updates', 'config_updates', 'total_samples', 'tags', 'metadata', 'samples', 'reductions', 'location', 'etag']
EvalSpec    : 34 fields, e.g. ['eval_set_id', 'eval_id', 'run_id', 'created', 'task', 'task_id'] ...
EvalConfig  : {'epochs': 2, 'fail_on_error': True, 'continue_on_fail': False, 'score_on_error': False, 'sandbox_cleanup': True, 'sandbox_prebuilt': False, 'log_samples': True, 'log_realtime': True, 'log_images': True, 'score_display': True}
EvalDataset : 12 samples, shuffled = False
EvalPlan    : [('prompt_template', ['template']), ('generate', ['tool_calls'])]
tags/meta   : ['candidate'] {'variant': 'v2', 'owner': 'support-evals', 'source': 'lesson 10A.1 triage_eval.py'}
revision    : type='git' origin='https://example.com/acme/support-evals.git' commit='fada17f' dirty=False

EvalResults : ['total_samples', 'completed_samples', 'logged_samples', 'early_stopping', 'scores', 'headline', 'metadata']
  totals    : 24 total, 24 completed
  EvalScore : name=triage_format scorer=triage_format reducer=None scored=12 unscored=0 metrics={'accuracy': 1.0, 'stderr': 0.0}
  EvalScore : name=triage_labels scorer=triage_labels reducer=None scored=12 unscored=0 metrics={'mean': 0.958, 'stderr': 0.03}
EvalStats   : ['started_at', 'completed_at', 'model_usage', 'role_usage', 'connection_limit_history']
ModelUsage  : {'input_tokens': 6686, 'output_tokens': 2126, 'total_tokens': 8812}

EvalSample  : 36 fields
  T05/2     : {'id': 'T05', 'epoch': 2, 'target': 'P2|shipping'} | scores {'triage_format': 'C', 'triage_labels': 0.6666666666666666} | error None | uuid SLvAgyht...
  log order : [('T01', 1), ('T02', 1), ('T03', 1), ('T04', 1)] ...
Reductions  : triage_labels None [('T05', 0.833), ('T06', 0.667)]

v3 status   : error | results: None | samples logged: 24
v3 error    : RuntimeError('503 from the model gateway (simulated)') | traceback lines: 112
v3 errored samples: [('T09', 1, "RuntimeError('503 from the mod"), ('T09', 2, "RuntimeError('503 from the mod")]

The sections below take the output apart, one class at a time. (Which epoch of T05 gets the wrong priority depends on scheduling, so your run may show the flaky answer under epoch 1 instead of 2; the per-sample mean is the same.)

3.2 EvalLog: the top level#

Field Holds Notes
version Log format version (2) Not the Inspect version; that is eval.packages
status "started", "success", "cancelled", "error" started means still running or crashed before the end was written
eval EvalSpec: what ran and how (3.3) Present in every log, including failed ones
plan EvalPlan: the solver steps with their arguments (3.4)
results EvalResults (3.5) None when the run errored
stats EvalStats: times and token usage (3.6)
error EvalError with message and traceback Only for status == "error"
samples list[EvalSample] (3.7) None in a header-only read; [] when run with log_samples=False
reductions Per-sample values after epoch reduction (3.8) Included in header-only reads of .eval logs, not of .json logs
total_samples Sample-epochs accepted for this attempt Saved even when results is absent
tags, metadata Current values: eval-time values merged with later edits The eval-time originals stay in eval.tags and eval.metadata (6.2)
log_updates Append-only list of post-run edits to tags and metadata, with provenance
invalidated, config_updates Flags and records of post-run changes (sample invalidation, configuration edits) Rarely needed in analysis; check the reference page when you meet them
location, etag Where the log was read from or written to (a URI), and the storage etag for conditional writes location is empty when read from a byte stream (5.5)

3.3 EvalSpec: identity, configuration and provenance#

log.eval has 34 fields in 0.3.292. Grouped by the question they answer:

Question Fields
Which run is this? run_id (one eval() call), eval_id (one task × model execution), eval_set_id (when part of an eval set), task_id, created
Which task? task, task_version, task_file, task_display_name, task_description, task_registry_name, task_attribs, task_args, task_args_passed
Which solver and scorers? solver, solver_args, solver_args_passed (set when --solver replaced the task's chain), scorers, metrics, headline_metric
Which data? dataset (name, location, samples, sample_ids, shuffled)
Which model? model, model_generate_config, model_base_url, model_args, model_roles
Which settings? config (an EvalConfig: limits, epochs and reducers, sample selection, error policy, concurrency, logging), sandbox
Which code? revision (git origin, commit, dirty), packages ({"inspect_ai": "0.3.292"})
What else did you say? tags, metadata (task metadata merged with run metadata: v2's shows variant and owner from the run and source from the task), viewer, shards

EvalConfig is printed with exclude_none=True, which is the useful way to read it: what you see is what was set or defaulted, here epochs: 2, the error policy (fail_on_error: True, continue_on_fail: False, score_on_error: False) and the logging flags. Limits, max_samples, sample_id, sample_shuffle and the rest appear when used. Two fields matter for comparisons: epochs_reducer (absent here because the default mean was used) and the selection fields (limit, sample_id), because a run on a subset is not comparable with a run on the full set even when everything else matches.

3.4 EvalPlan: the solver chain as run#

log.plan.steps lists each solver with its parameters as recorded: here prompt_template with its template (the full prompt text, so a prompt change is visible in the log) and generate with tool_calls. plan.config holds the generation config the plan used, and plan.finish an optional final step. The plan is what to compare when someone asks "did these two runs use the same prompt?"; 9.1 compares it field by field, and 9.6 hashes the template.

3.5 EvalResults, EvalScore and EvalMetric#

results holds total_samples and completed_samples (sample-epochs: 24 here, twelve samples times two epochs), logged_samples, early_stopping (set when an early-stopping policy ended the run), headline and metadata, and the list scores, with one EvalScore per scorer per reducer. Each EvalScore has name, scorer, reducer, scored_samples and unscored_samples (counted in samples after reduction: 12, not 24), params, metadata and metrics, a dict of EvalMetric(name, value, params, metadata, group).

Notice reducer=None in the output. When a task uses the default reducer (the mean), the EvalScore records no reducer name, and the dataframe columns built from it carry no reducer segment (8.2). When you set a reducer, even a single one, EvalScore.reducer holds its name ('max'), but the column names change only when several reducers collide on one scorer and metric. Code that looks a result up should match on (name, reducer) and treat None as "the default", rather than indexing scores[0].

3.6 EvalStats and ModelUsage#

stats has started_at, completed_at, model_usage (per model), role_usage (per model role, for example a grader), and connection_limit_history (how the adaptive concurrency controller moved, 10B.12). ModelUsage has input_tokens, output_tokens, total_tokens, input_tokens_cache_write, input_tokens_cache_read, reasoning_tokens and total_cost; the probe printed only the fields that were set. total_cost is None unless you configured model prices (--model-cost-config or set_model_cost()), and mock token counts are fake (10B.8, 9.5).

3.7 EvalSample: one sample, one epoch#

EvalSample has 36 fields. The ones you will use:

Group Fields
Identity id (the dataset id), epoch, uuid (globally unique per sample execution)
The case input, target, choices, metadata, description, files, setup, sandbox
What happened messages (the final conversation), output (the final ModelOutput), store (per-sample state), events (the transcript, Part 4), timelines, attachments
Verdicts scores (a dict keyed by scorer name, each Score with value, answer, explanation, reason, metadata and an edit history)
Cost and time model_usage, role_usage, model_fallbacks, total_time, working_time, started_at, completed_at, turn_count
Trouble error (with message and traceback), error_retries (errors that were retried), limit (which limit stopped it and why), token_limit, message_limit, time_limit, token_limit_usage, invalidation

Two things to remember from the output: the T05 epoch-2 sample has its own scores, so per-epoch disagreement is visible in the log (the reduction hides it), and log.samples came back as ('T01', 1), ('T02', 1), ...: all of epoch 1, then epoch 2, sorted by id. Join samples across logs on (id, epoch); never zip two lists of samples by position.

3.8 Reductions#

log.reductions has one entry per scorer (and reducer), each with the reduced value of every sample. For v2's triage_labels, T05 is 0.833 (one epoch at 1.0, one at 0.667, mean 0.833) and T06 is 0.667 (wrong category in both epochs). These are exactly the numbers the metrics were computed from, which makes reductions the right input for paired comparisons (10B.10, 8.3) and, because they come with a header-only read of an .eval log, the cheapest one.

3.9 The log of a failed run#

The last block is v3, the run whose provider failed on T09. Its log says a lot:

  • status is error, error.message is the exception, and error.traceback has the full traceback (112 lines here).
  • results is None. There are no metrics at all, not even for the samples that succeeded. Anything that reads log.results.scores without checking the status crashes on this log, or worse, a try/except around it reports "no data" as if the run had not happened.
  • 24 samples were logged, including both epochs of T09 with their errors. With the default fail_on_error=True the task stops at the first error, but samples already in flight complete and are written, so the log of a failed run is often almost complete evidence. That is what eval_retry() and eval sets reuse to avoid paying twice (10B.12).

A started log is a different case: the run is either still going or died without writing its end. Tell them apart by asking whether anything is still running: inspect ctl task list lists the tasks of running evals (10B.12); if nothing lists it and no Python process is evaluating, the log is a crash. The _journal/ member (2.1) holds what was flushed, and inspect log recover rebuilds a log from it (10B.12; not run here). Recent releases (the changelog for 0.3.290 to 0.3.292) let recover_eval_log() finalize a crashed log even without a sample buffer, with a status you choose, and added inspect log merge-shards --delete-shards.

What this means for you as an engineer: a failed run is not a missing data point to retry silently. Its log tells you which sample failed and why; a provider error on one ticket, a scorer bug, a sandbox that did not start. Read the error before you retry, and if you decide to count the run anyway, do it explicitly (retry the errored samples, or report coverage), never by reading partial samples as if they were a result.

3.10 What a log lets you reproduce, and what it cannot pin#

A log records So you can
Task name, file, registry name, arguments and version Re-run the same task definition, and refuse comparisons across versions
The solver chain with arguments, including full prompt templates See exactly which prompt produced a number
Scorer and metric names and options, reducers Re-score and re-reduce from the transcripts
Model string, base URL, model arguments, generation config, model roles Re-run against the same model settings
Eval config: epochs, limits, sample selection, shuffle, error policy Reproduce the selection and the denominator
Dataset name, location, sample ids, shuffled flag Detect subset and ordering differences
Git origin, commit and dirty flag; Inspect version Check out the code; know whether it was committed
Every message, raw provider call (first few by default), usage, timing, error and retry Audit and debug without re-running
Every score with explanation and edit history; tag and metadata edits with provenance Audit every change to the record

What no log can pin, and what to do about each:

Not pinned Why Mitigation
The model's sampling Inspect does not seed models, and provider determinism varies; many reasoning models ignore temperature Epochs and reducers (10B.10, Part 7), the cache for replays (10B.12)
The model behind an alias A hosted alias can point at a new snapshot tomorrow Use dated model ids where the provider offers them
Built-in grader prompts They are Inspect's, versioned with Inspect, and include a random nonce per request Pin Inspect through your lock file; re-validate graders on upgrade (10B.11, 10.7)
Remote datasets A Hugging Face or URL dataset can change Pin revision (10B.9, 3.7) and fingerprint content (9.6)
Your other packages packages records only inspect_ai Commit uv.lock and run from a clean tree, so commit identifies the lock file
Uncommitted code dirty=True means the code is not the named commit Commit before runs you will quote (10B.8, 6.4)
Bootstrap randomness bootstrap_stderr is unseeded Prefer analytic standard errors, or seed your own bootstrap (10B.10, 6.6)
Python objects passed at run time A scripted model or client object is not serializable Register components by name; use a @modelapi provider instead of an in-process object when runs must be reproducible (Part 10, 10B.8, 6.5)

The lab logs were written from a clean, committed tree (the Setup recipe), which is why every header in this lesson says dirty=False; on an uncommitted tree they say dirty=True. That single flag is the difference between "this number came from commit fada17f" and "this number came from commit fada17f plus some edits nobody recorded".


Part 4: Events: the transcript in code#

Deep-dive

4.1 The event catalogue#

EvalSample.events is the ordered record of everything that happened to one sample: Inspect View's Transcript tab draws it, and events_df() (8.5) flattens it. Each event is a Pydantic model from inspect_ai.event with an event field naming its type, a timestamp, a working_start, a uuid and the span_id of the step that produced it. The types you will meet, as of 0.3.292:

event value Class Recorded when You read it to
span_begin, span_end SpanBeginEvent, SpanEndEvent A step starts and ends: init, solvers, each solver, scorers, each scorer, tools, agents Attribute every other event to the step that caused it
sample_init SampleInitEvent The sample is set up (the sample and its initial state) See the exact starting state
model ModelEvent A model call: model, role, input, tools, tool_choice, config, output, retries, cache, request_ids, error, call (the raw request and response), timing Debug prompts, providers, caching and retries (4.3)
tool ToolEvent A tool call with its arguments, result and error Agent trajectories (10B.14)
state, store StateEvent, StoreEvent The TaskState or the store changed; changes is a list of JSON-patch operations See what each solver changed, and when
score ScoreEvent A scorer returned (score, target, intermediate for scores taken inside solvers) Check what each scorer saw and decided
score_edit ScoreEditEvent A score was edited after the run (6.3) Audit post-run changes
error ErrorEvent The sample raised Find the failing step
sample_limit SampleLimitEvent A token, message, time, working-time or cost limit fired Tell limit stops from errors (10B.15)
logger, info LoggerEvent, InfoEvent A Python logging record (2.7) or an informational note from your code Your own diagnostics
approval, sandbox, subtask, compaction, input, interrupt ApprovalEvent, SandboxEvent, SubtaskEvent, CompactionEvent, InputEvent, InterruptEvent Tool approvals, sandbox commands and file operations, subtasks, context compaction, human input and interruption Agent and sandbox evals (10B.14, 10B.15)

The module also exports newer types used by agent features (branch, anchor, review, sentinel, communication, swarm, step) and tree and timeline helpers (event_tree, event_tree_walk, event_sequence, timeline_build and friends). Their semantics belong to the agent lessons and change faster than the core; check the inspect_ai.event reference for your version before you write code against them.

4.2 Walking one transcript#

python
# l04_events.py: one sample's transcript, event by event (lesson 10B.13)
from collections import Counter

from inspect_ai.event import EventTreeSpan, ModelEvent, ScoreEvent, StateEvent, event_tree
from inspect_ai.log import read_eval_log_sample, resolve_sample_attachments

from lab_paths import lab_logs

v1 = lab_logs()["v1"]
sample = read_eval_log_sample(v1, id="T11", epoch=1)
print("events:", len(sample.events), dict(Counter(e.event for e in sample.events)))


# 1. The span tree: which solver or scorer produced each event.
def show(nodes, depth=0):
    for node in nodes:
        if isinstance(node, EventTreeSpan):
            print("  " * depth + f"[{node.type}] {node.name}")
            show(node.children, depth + 1)
        else:
            print("  " * depth + f"- {node.event}")


show(event_tree(sample.events))

# 2. The model event: what was sent, what came back, and the raw call.
model_event = next(e for e in sample.events if isinstance(e, ModelEvent))
print("\nmodel:", model_event.model, "| retries:", model_event.retries,
      "| cache:", model_event.cache)
print("input as stored :", model_event.input[0].text[:45])
resolved = resolve_sample_attachments(sample)
model_event = next(e for e in resolved.events if isinstance(e, ModelEvent))
print("input resolved  :", model_event.input[0].text[:45].replace("\n", " | "))
print("output          :", model_event.output.completion[:50], "...")
print("raw call keys   :", sorted(model_event.call.request), "| response keys:",
      sorted(model_event.call.response)[:4])

# 3. State changes are JSON-patch diffs; score events carry the verdicts.
for e in sample.events:
    if isinstance(e, StateEvent):
        print("state change    :", [(c.op, c.path) for c in e.changes][:3])
    if isinstance(e, ScoreEvent):
        print("score event     :", e.score.value, "| target:", e.target,
              "| explanation:", (e.score.explanation or "")[:40])
print("attachments     :", len(sample.attachments), "blobs")
bash
uv run python l04_events.py
Output25 lines
events: 20 {'span_begin': 7, 'sample_init': 1, 'span_end': 7, 'state': 2, 'model': 1, 'score': 2}
[init] init
  - sample_init
[solvers] solvers
  [solver] prompt_template
    - state
  [solver] generate
    - model
    - state
[scorers] scorers
  [scorer] triage_format
    - score
  [scorer] triage_labels
    - score

model: mockllm/triage-v1 | retries: None | cache: None
input as stored : attachment://5a38b8f498af574317d03bbe7437cabe
input resolved  : # Task | Triage a customer support ticket for A
output          : Sure! This looks like a billing issue, I would mar ...
raw call keys   : ['messages', 'model'] | response keys: ['content']
state change    : [('replace', '/messages/0/content')]
state change    : [('add', '/messages/1'), ('add', '/output/usage'), ('add', '/output/input_context_tokens')]
score event     : I | target: P2|billing | explanation: keys=['priority']; category=None; summar
score event     : 0.3333333333333333 | target: P2|billing | explanation: wrong: category, summary
attachments     : 3 blobs

Read it in three steps.

The tree. event_tree() nests the flat list into spans: init holds sample_init; solvers holds one span per solver (prompt_template produced one state change, the rewritten user message; generate produced the model call and a state change that added the reply); scorers holds one span per scorer with its score event. Twenty events for a one-call sample; an agent sample has hundreds or thousands, which is why you navigate them through spans rather than as a list.

The model event. The input as stored is attachment://5a38b8f4..., not the prompt. Long content in events is stored once in sample.attachments (three blobs here) and referenced, which is part of what keeps .eval logs small (2.2). After resolve_sample_attachments(), the same field holds the rendered prompt. The call holds the raw provider request (messages, model) and response, as the provider (here the mock) saw them.

The state diffs and scores. state events are JSON-patch operations (replace /messages/0/content, add /messages/1, add /output/usage), so you can see exactly which solver changed which part of the state. The two score events carry each scorer's value, the target it compared against and the explanation: T11's broken JSON scored I on format and one third on labels.

4.3 Model events and the raw provider call#

The ModelEvent is the most useful event for debugging, because it answers "what exactly was sent?" at two levels: input, tools, tool_choice and config in Inspect's provider-neutral form, and call.request / call.response in the provider's own wire format. Use the second when a provider behaves unexpectedly: a parameter Inspect dropped or translated (for example temperature on a reasoning model, 10B.12), a system message merged into the first user message, a tool schema rewritten for the provider.

Three details:

  • By default only the first few raw calls per model (and all failed ones) are logged (2.4). If call is None on the event you care about, re-run with --log-model-api.
  • retries counts provider-level retries for that call, and request_ids lists each request id and HTTP status, including the retries, for the providers that report them. A sample that "took 90 seconds" often shows three rate-limit retries here.
  • cache says whether the call was served from Inspect's local cache ("read") or written to it ("write"); None means caching was off (10B.12). A comparison between a cached and an uncached run compares one old answer with a new one.

4.4 Attachments#

To keep logs small, images and other large or repeated content (prompts that recur across model events, long tool outputs) are stored once in sample.attachments and referenced as attachment://<hash>. Most of the time you do not want them resolved: messages, output and scores hold readable values anyway. Resolve them when you read events directly, or when you need base64 images from input and messages:

Way Effect
resolve_sample_attachments(sample) Returns the sample with references replaced by content
read_eval_log(..., resolve_attachments=True) or read_eval_log_sample(..., resolve_attachments=True) Resolves while reading; "full" and "core" choose how deep (check the reference for your version)
condense_sample(), condense_events(), expand_events() The low-level functions Inspect uses to de-duplicate and re-expand; needed only if you write logs yourself

4.5 When to read events in code#

Most analysis never touches events: scores, messages and summaries answer most questions. Read events when the question is about process, not outcome:

  • Where did the time go? Model events have working_time and timing; events_df(columns=EventTiming + ModelEventColumns) turns them into a table (8.5).
  • Did the solver do what I think? state diffs per solver span.
  • Retries, cache hits, fallbacks, per call rather than per sample.
  • Agent behaviour: tool-call sequences, approvals, limits, compaction (10B.14 to 10B.16); for large-scale transcript analysis, Inspect Scout (10B.16) is built on exactly this data.

Part 5: Reading logs efficiently: the cost ladder#

5.1 Read the least you need#

A header is a few kilobytes; a full agent log can be gigabytes. The reading API is a ladder, and good analysis code climbs it only as far as the question requires:

flowchart TB
    Q{"What do you need?"} --> H["Results, config, status,<br/>per-sample reduced values"]
    Q --> S["Per-sample scores,<br/>metadata, errors, usage"]
    Q --> F["Messages, outputs,<br/>events of a few samples"]
    Q --> A["Every transcript"]
    H --> H1["read_eval_log(header_only=True)<br/>evals_df()"]
    S --> S1["read_eval_log_sample_summaries()<br/>samples_df() default columns"]
    F --> F1["read_eval_log_sample()<br/>read_eval_log_samples_by_id()"]
    A --> A1["read_eval_log_samples() streaming<br/>exclude_fields, parallel dataframes"]
    H1 --> C1["cheapest"]
    A1 --> C4["most expensive"]

The same probe climbs every rung on the lab logs:

python
# l05_reading.py: the reading API in depth, cheapest read first (lesson 10B.13)
import io

from inspect_ai.log import (EvalLog, list_eval_logs, read_eval_log, read_eval_log_sample,
                            read_eval_log_sample_summaries, read_eval_log_samples,
                            read_eval_log_samples_by_id)

# 1. Listing with a filter. The filter receives each log's HEADER (an EvalLog).
def finished_candidates(log: EvalLog) -> bool:
    return log.status == "success" and "candidate" in log.eval.tags


every = list_eval_logs(".", formats=["eval"])            # recursive: finds logs in every subfolder
top = list_eval_logs(".", formats=["eval"], recursive=False)
chosen = list_eval_logs("logs-lab", filter=finished_candidates)
print("recursive:", len(every), "| top level only:", len(top), "| filtered:", len(chosen))
info = chosen[0]
print("chosen:", info.task, info.name.rsplit("/", 1)[-1][:30], "...", f"{info.size:,} bytes")

# 2. Summaries: thin records for every sample, without loading transcripts.
summaries = read_eval_log_sample_summaries(info)
imperfect = [(s.id, s.epoch) for s in summaries if s.scores["triage_labels"].value < 1]
print("\nsummaries:", len(summaries), "| imperfect (id, epoch):", imperfect)
print("summary fields kept:", {k: v.value for k, v in summaries[0].scores.items()},
      "| metadata:", summaries[0].metadata)

# 3. Read only those samples in full: one at a time, or a batch by id.
one = read_eval_log_sample(info, id="T06", epoch=1)
print("\nT06/1 output:", one.output.completion[:60])
batch = read_eval_log_samples_by_id(info, imperfect)
print("by id:", [(s.id, s.epoch, round(s.scores["triage_labels"].value, 3)) for s in batch])

# 4. Leave heavy fields out when you do read everything.
light = read_eval_log(info, exclude_fields={"events", "attachments"})
print("\nexclude_fields: events per sample =", {len(s.events) for s in light.samples})

# 5. Streaming: one sample in memory at a time. Refuses incomplete logs by default.
error_log = list_eval_logs("logs-lab", filter=lambda log: log.status == "error")[0]
try:
    sum(1 for _ in read_eval_log_samples(error_log))
except Exception as e:
    print("stream an error log:", type(e).__name__, "-", str(e)[:70])
n = sum(1 for _ in read_eval_log_samples(error_log, all_samples_required=False))
print("with all_samples_required=False:", n, "samples")

# 6. Any binary stream works too (a download, a blob from object storage).
with open(info.name.removeprefix("file://"), "rb") as f:
    from_bytes = read_eval_log(io.BytesIO(f.read()), header_only=True)
print("\nfrom bytes:", from_bytes.eval.model, from_bytes.status, "| location:", from_bytes.location)
bash
uv run python l05_reading.py
Output14 lines
recursive: 3 | top level only: 0 | filtered: 1
chosen: triage 2026-11-24T18-01-46-00-00_tria ... 80,726 bytes

summaries: 24 | imperfect (id, epoch): [('T06', 1), ('T05', 2), ('T06', 2)]
summary fields kept: {'triage_format': 'C', 'triage_labels': 1.0} | metadata: {'intent': 'billing', 'edge': 'multi-intent'}

T06/1 output: {"priority": "P2", "category": "account", "summary": "App cr
by id: [('T06', 1, 0.667), ('T05', 2, 0.667), ('T06', 2, 0.667)]

exclude_fields: events per sample = {0}
stream an error log: RuntimeError - This log does not have all samples (status=error). Specify all_samples
with all_samples_required=False: 24 samples

from bytes: mockllm/triage-v2 success | location:

5.2 Listing and filtering#

list_eval_logs(log_dir="./logs", formats=None, filter=None, recursive=True, descending=True, fs_options={}) returns EvalLogInfo records (name as a URI, type, size, mtime, task, task_id, suffix), newest first.

  • recursive=True is the default: listing . found the three lab logs inside logs-lab/ (and would have found every other log below the folder), while recursive=False found none at the top level. Point it at the directory you mean.
  • formats=["eval"] skipped the .json copies made in 2.2; without it, a converted directory would be counted twice.
  • filter= receives each log's header as an EvalLog, so you can filter on anything in the header: status, task, model, tags, metadata, task version, creation time. The probe kept successful runs tagged candidate, which left one log (v2) and dropped v3 (error) and v1 (baseline). The filter reads each header, so it costs one small read per log.

5.3 Summaries first, then the samples you need#

read_eval_log_sample_summaries() returns one EvalSampleSummary per sample and epoch, read from summaries.json without touching the transcripts. The docs describe it as orders of magnitude faster than reading samples, and it is "thinned": images removed from input, metadata reduced to scalars with strings truncated to 1,000 characters, scores reduced to their value. The fields: id, epoch, input, choices, target, description, metadata, scores, model_usage, role_usage, model_fallbacks, started_at, completed_at, total_time, working_time, uuid, error, limit, limit_reason, retries.

The pattern in the probe is the one to copy: filter on summaries, then read only the samples that matter. Of 24 sample-epochs, three were imperfect, and only those were read in full:

  • read_eval_log_sample(log, id="T06", epoch=1) reads one (by id and epoch, or by uuid);
  • read_eval_log_samples_by_id(log, [(id, epoch), ...], concurrency=8) reads a batch concurrently, in the order you asked for.

The summaries also show v2's whole story in one line: T06 is wrong in both epochs (a real regression), T05 only in epoch 2 (flakiness).

5.4 Reading everything: exclude_fields and streaming#

When you do need every sample, two options keep memory under control:

  • exclude_fields (on read_eval_log, read_eval_log_sample, read_eval_log_samples and samples_df) skips heavy fields while parsing. With {"events", "attachments"} every sample came back with zero events, which for agent logs is most of the bytes.
  • read_eval_log_samples() is a generator that yields one sample at a time, so memory stays flat however large the log.

The streaming reader has a guard: on a log whose status is not success it raises RuntimeError: This log does not have all samples (status=error)... unless you pass all_samples_required=False. With the flag, v3 yielded all 24 logged samples. The guard is deliberate: code that streams "all samples" of a failed run and computes a mean is computing the mean of whatever happened to finish. Pass the flag only in code that is about failures (error analysis, retries), never in code that produces a metric.

5.5 Bytes, remote files and async#

  • Any binary stream works as input: read_eval_log(io.BytesIO(data)) read the header from bytes, which is how you read a log fetched from an artefact store, an HTTP response or a message queue. The location is then empty, so write_eval_log(log) without a location has nowhere to write; pass one explicitly.
  • Remote URIs (s3://, hf://, az://) work everywhere a path does (2.5); Inspect reads the zip members it needs with ranged reads (the docs' filesystems page describes this for zipped log members), so a header read from a bucket is much cheaper than downloading the log.
  • Async variants exist for use inside async code (a web service, a hook, a custom solver): list_eval_logs_async, read_eval_log_async, read_eval_log_headers_async, read_eval_log_sample_async, read_eval_log_sample_summaries_async, read_eval_log_samples_by_id_async, write_eval_log_async. Do not call the synchronous functions from inside a running event loop.

5.6 The command line, for scripts and other languages#

10B.8, 7.5 showed inspect log list --json and inspect log dump. The rest of the family, run on the lab:

bash
# l15_cli.sh: the log commands for scripts and other languages (lesson 10B.13)
inspect log list --log-dir logs-lab --status error --json
inspect log schema | python3 -c "import json, sys; s = json.load(sys.stdin); print('format:', 'openapi', s['openapi'], '| schemas:', len(s['components']['schemas']), '| has EvalLog:', 'EvalLog' in s['components']['schemas'])"
inspect log convert logs-lab --to json --output-dir logs-cli-json --overwrite
ls logs-cli-json
Output17 lines
[
  {
    "name": "logs-lab/2026-11-24T18-01-46-00-00_triage_LrQY2G55ZKLg5jn3TuhsuD.eval",
    "type": "file",
    "size": 86811,
    "mtime": 1795543306910.3892,
    "task": "triage",
    "task_id": "LrQY2G55ZKLg5jn3TuhsuD",
    "suffix": null
  }
]
format: openapi 3.1.0 | schemas: 181 | has EvalLog: True
Converting log files...

2026-11-24T18-01-46-00-00_triage_6WUDzisSyNAKhNn7oATbjw.json
2026-11-24T18-01-46-00-00_triage_FBUbRR9xinMvQpRSDt3jv9.json
2026-11-24T18-01-46-00-00_triage_LrQY2G55ZKLg5jn3TuhsuD.json
Command What it does Notes
inspect log list [--log-dir] [--json] [--status S] Lists logs, optionally one status (started, success, cancelled, error) The probe found exactly the v3 log with --status error. There is no "retryable" filter: compare the error and cancelled listings
inspect log dump <uri> [--header-only] Prints any log as JSON, with your configured credentials The bridge to non-Python tools; remember NaN (2.3)
inspect log convert <path> --to FORMAT --output-dir DIR [--overwrite] [--stream N] (FORMAT is eval or json) Converts a file or directory Output directory required (2.2)
inspect log schema Prints the schema of the log format In 0.3.292 it is an OpenAPI 3.1 document with 181 component schemas (including EvalLog), not a bare JSON Schema; generate typed clients from components.schemas
inspect log export-config <log> Writes a run config from a log 10B.8, 6.5
inspect log exclude, inspect log zero Edit a finished log's metrics on the record 6.3
inspect log recover, inspect log merge-shards Recover a crashed run's log from its journal; merge sharded runs 10B.12; not run in this lesson

Part 6: Writing, converting and editing logs#

Deep-dive

6.1 write_eval_log()#

write_eval_log(log, location=None, format="auto", if_match_etag=None, header_only=False) writes an EvalLog and returns a WriteEvalLogResult. The arguments in practice:

Argument Behaviour Use it to
location=None Writes back to log.location (the file it was read from or written to) Edit in place
location="other.eval" Writes a new file; the extension decides the format when format="auto" Keep the original untouched (do this by default)
format="json" or "eval" Forces a format Export one log as .json (2.1 did)
header_only=True Rewrites only the header of an .eval file, leaving the samples as they are Fast edits to tags, metadata or results on big logs
if_match_etag="..." Conditional write on S3: fails if someone else changed the file since you read it (log.etag) Safe concurrent edits on a shared bucket

Logs returned by eval_set() are headers only, so read the full log with read_eval_log(log.location) before editing and writing it back, or you would write a log without its samples (10B.12).

6.2 Tags and metadata, with an audit trail#

Run-time tags and metadata (set in 1.3) are good for things known before the run: which variant, which owner, which experiment. Decisions made after the run (reviewed, approved, rejected, why) belong in the log too, and edit_eval_log() records them with provenance:

python
# l06_edit_tags.py: tag and annotate a finished log, with an audit trail (lesson 10B.13)
import shutil

from inspect_ai.log import (MetadataEdit, ProvenanceData, TagsEdit, edit_eval_log,
                            read_eval_log, write_eval_log)

from lab_paths import lab_logs

# Work on a copy: edits rewrite the file, and the lab logs are reused later.
src = lab_logs()["v2"].name.removeprefix("file://")
shutil.copy(src, "v2-reviewed.eval")

log = read_eval_log("v2-reviewed.eval")
log = edit_eval_log(log, [
    TagsEdit(tags_add=["qa_passed", "candidate"], tags_remove=["needs_qa"]),
    MetadataEdit(metadata_set={"reviewer": "priya", "decision": "hold: T06 regression"},
                 metadata_remove=["owner"]),
], ProvenanceData(author="priya", reason="weekly eval review"))
write_eval_log(log)                                  # back to log.location

again = read_eval_log("v2-reviewed.eval", header_only=True)
print("current tags    :", again.tags)
print("original tags   :", again.eval.tags)
print("current metadata:", again.metadata)
print("original meta   :", again.eval.metadata)
for update in again.log_updates:
    p = update.provenance
    print("log_update      :", p.author, "|", p.reason, "|", p.timestamp.isoformat()[:19], "|",
          [type(e).__name__ for e in update.edits])
    for e in update.edits:
        print("   ", e.model_dump(exclude_none=True))
print("results untouched:", {s.name: round(list(s.metrics.values())[0].value, 3)
                             for s in again.results.scores})
bash
uv run python l06_edit_tags.py
Output8 lines
current tags    : ['candidate', 'qa_passed']
original tags   : ['candidate']
current metadata: {'variant': 'v2', 'source': 'lesson 10A.1 triage_eval.py', 'reviewer': 'priya', 'decision': 'hold: T06 regression'}
original meta   : {'variant': 'v2', 'owner': 'support-evals', 'source': 'lesson 10A.1 triage_eval.py'}
log_update      : priya | weekly eval review | 2026-11-24T18:01:49 | ['TagsEdit', 'MetadataEdit']
    {'type': 'tags', 'tags_add': ['qa_passed'], 'tags_remove': []}
    {'type': 'metadata', 'metadata_set': {'reviewer': 'priya', 'decision': 'hold: T06 regression'}, 'metadata_remove': ['owner']}
results untouched: {'triage_format': 1.0, 'triage_labels': 0.958}

What happened, line by line:

  • Current versus original. log.tags and log.metadata now show the reviewed state; log.eval.tags and log.eval.metadata still show what the run was started with. Analysis that filters on review status reads the current values; analysis that asks "how was this run configured?" reads the originals.
  • No-op edits are dropped. The script asked to add candidate (already present) and remove needs_qa (never present); the recorded TagsEdit contains only qa_passed. The audit trail shows what changed, not what was asked.
  • log_updates is append-only, each entry with ProvenanceData(author, reason, timestamp) and the list of edits. A second review appends a second entry.
  • Results are untouched. Tags and metadata never change scores; score changes go through the functions in 6.3.

A tagging vocabulary that works for teams: baseline, candidate, needs_qa, qa_passed, rejected, plus metadata keys reviewer, decision, ticket (the issue or change request it belongs to). Filter on them with list_eval_logs(filter=lambda log: "qa_passed" in log.tags), and they appear in evals_df() as the tags and metadata columns.

6.3 The editing family#

Function (CLI) Changes Records Owner lesson
edit_eval_log(log, [TagsEdit, MetadataEdit], provenance) Current tags and metadata log_updates This lesson (6.2)
edit_score(log, sample_id, score_name, ScoreEdit(...)) One score's value, answer, explanation or metadata; recomputes metrics by default The score's history, a score_edit event 10B.11, 10.5
recompute_metrics(log) Metrics from the current scores (results) 10B.11, 10.5
exclude_samples(log, samples, provenance) (inspect log exclude) Scores become unscored NaN with reason excluded; leaves the denominator Score history 10B.11, 10.6
zero_samples(log, empty_log, samples, provenance) (inspect log zero) Scores replaced by an empty attempt's verdicts with reason zeroed; stay in the denominator as failures Score history This lesson (6.4)
invalidate_samples(...) Marks samples invalid (recorded in EvalSample.invalidation) Check the log reference for your version

Shared rules for every function that changes scores:

  • Everything happens in memory until write_eval_log().
  • The log's task file is not imported. If the task used a custom metric or reducer, import its module first, or the recomputation raises a LookupError naming it and nothing changes. trust_log=True makes Inspect import the task file the log names (6.5).
  • Exclusion and zeroing change scores, not transcripts. An errored sample that you exclude or zero is still re-run by inspect eval-retry and eval-set retries, and its new result replaces the edit. Rescoring with inspect score --action overwrite replaces the edit too, so apply it again afterwards.
  • Say why, always. The reason is required for exclusion and zeroing for a good reason: a metric that moved because of edits must be explainable from the log alone.

6.4 Zeroing a sample: the empty-attempt workflow#

Sometimes a sample must count as a failure even though the model got it "right": the answer leaked into the prompt's examples, the agent was handed the solution, the sample was solved by exploiting a broken environment (10A.7, 5.5 calls this reward hacking). Excluding it would raise the metric; zeroing keeps it in the denominator with a failing verdict. What "failing" means depends on the scorers (I for one, 0.0 for another, a failed test in a sandbox), so Inspect asks the task's own scorers: run the sample again with the empty_attempt() solver, which does nothing, score the untouched state, and copy those verdicts in.

python
# l16_zero.py: count a sample as a failure, on the record: empty attempt + zero_samples (lesson 10B.13)
import shutil

from inspect_ai import eval
from inspect_ai.log import ProvenanceData, read_eval_log, write_eval_log, zero_samples
from inspect_ai.solver import empty_attempt

from lab_models import model_v2
from lab_paths import lab_logs
from triage import triage

shutil.copy(lab_logs()["v2"].name.removeprefix("file://"), "v2-zeroed.eval")
log = read_eval_log("v2-zeroed.eval")
before = {s.name: round(list(s.metrics.values())[0].value, 3) for s in log.results.scores}

# Step 1: score the untouched state of T02 with the task's own scorers (same epochs, same model).
empty = eval(triage(), solver=empty_attempt(), sample_id="T02", epochs=2, model=model_v2(),
             log_dir="logs-empty", display="none")[0]
print("empty attempt T02:", [(s.epoch, {k: v.value for k, v in s.scores.items()}) for s in empty.samples])

# Step 2: copy those verdicts into the real log, with provenance. Say why, always.
zero_samples(log, empty, ["T02"],
             ProvenanceData(author="priya", reason="T02 answer was in the few-shot examples"))
write_eval_log(log)

after = {s.name: round(list(s.metrics.values())[0].value, 3) for s in log.results.scores}
t02 = next(s for s in log.samples if s.id == "T02" and s.epoch == 1)
fmt = t02.scores["triage_format"]
print("before:", before)
print("after: ", after)
print("T02 format now:", fmt.value, "| reason:", fmt.reason, "| history:", [h.value for h in fmt.history])

# A sample the empty attempt did not run is refused, and nothing is edited.
try:
    zero_samples(log, empty, ["T06"], ProvenanceData(author="priya", reason="test"))
except Exception as e:
    print("zero T06:", type(e).__name__, "-", str(e)[:80])
bash
uv run python l16_zero.py
Output5 lines
empty attempt T02: [(1, {'triage_format': 'I', 'triage_labels': 0.0}), (2, {'triage_format': 'I', 'triage_labels': 0.0})]
before: {'triage_format': 1.0, 'triage_labels': 0.958}
after:  {'triage_format': 0.917, 'triage_labels': 0.875}
T02 format now: I | reason: zeroed | history: ['C', 'I']
zero T06: ValueError - Cannot zero these samples; nothing was edited. A sample without a counted verdic
  • The empty attempt produced I on format and 0.0 on labels for both epochs: an empty output has no JSON, so the scorers fail it, exactly as they would fail a model that said nothing. Task.setup (if any) still runs, so a sandbox would be prepared as for a real attempt.
  • After zeroing, v2's format accuracy fell from 1.0 to 0.917 and its labels mean from 0.958 to 0.875: T02 is now a failure in both epochs, with reason: zeroed and the original C kept in the score history.
  • Refusals protect the record. Zeroing T06, which the empty attempt did not run, was refused with "nothing was edited". The docs list the other refusals: integer sample ids (Inspect numbers id-less samples by position, so an integer need not name the same sample in another run, one more reason for string ids, 10B.9, 2.4); an empty attempt that errored, hit a limit or has no score; verdicts that are dicts, lists or unscored; and samples with scores the empty attempt does not produce.

The rules for the empty attempt, from the docs: write it to its own log directory (an eval set's directory is where it looks for logs to reuse), and run it with the same settings as the original (model, task arguments, sandbox, epochs), because zero_samples() checks only the task name and scorer names. From the command line the two steps are inspect eval triage.py --solver inspect_ai/empty_attempt --sample-id T02 --log-dir logs-empty and inspect log zero <log> --from <empty log> --sample T02 --reason "...", which rewrites the log in place.

6.5 Logs from others: what is safe to run#

A log is data that names code: its task file, its scorers, its model endpoint, its metrics' options. Inspect draws a clear line (docs, "Logs from Others"):

Operation Runs code named by the log? So
Reading, viewing, dataframes, inspect log dump No Safe on any log
Editing tags, metadata and scores; recomputing; excluding; recovering No: the task file is not imported, and metric options that would create a model or any non-metric object are refused with a ValueError Safe; import your own task module first when custom metrics are involved
The same with trust_log=True (--trust-log) Yes: imports the task file the log records and rebuilds metric options as recorded Only for logs you trust
inspect eval-retry, inspect score Yes: they re-run the task's code, scorers and settings (including the model endpoint) Only for logs you trust

Treat a log from outside your team like a pull request from a stranger: read it freely, run it never, until you have reviewed what it names.


Part 7: Inspect View for teams#

Deep-dive

10B.8, 6.3 covered starting inspect view, its tabs and the VS Code extension. This part is about using the viewer as a team: shipping a review layout with the task, protecting reviewers from model-controlled content, watching runs on shared storage, and publishing without leaking.

7.1 Task views: ship the review layout with the task#

By default the viewer guesses which columns to show. For a task you own, you know better: which scorer matters, which columns a reviewer needs, which order surfaces the problems. Task(viewer=ViewerConfig(...)) stores that layout in every log the task writes, so everyone who opens the log gets it:

python
# l17_task_view.py: ship a default viewer layout with the task (lesson 10B.13)
from inspect_ai import Task, eval, task, task_with
from inspect_ai.viewer import TaskSamplesColumn, TaskSamplesSort, TaskSamplesView, ViewerConfig

from lab_models import model_v2
from triage import triage

TRIAGE_VIEW = ViewerConfig(
    task_samples_view=TaskSamplesView(
        name="Triage review",
        columns=[
            TaskSamplesColumn(id="sampleId"),
            TaskSamplesColumn(id="epoch"),
            TaskSamplesColumn.score("triage_labels"),
            TaskSamplesColumn.score("triage_format"),
            TaskSamplesColumn(id="answer"),
            TaskSamplesColumn(id="input", visible=False),    # long ticket text: hidden by default
            TaskSamplesColumn(id="tokens", visible=False),
        ],
        sort=[TaskSamplesSort.score("triage_labels", dir="asc"),  # worst samples first
              TaskSamplesSort(column="sampleId", dir="asc")],
        multiline=True,
    ),
    trust_content=False,   # render model output as literal text in every viewer
)


@task
def triage_reviewed() -> Task:
    return task_with(triage(), viewer=TRIAGE_VIEW, name="triage_reviewed")


log = eval(triage_reviewed(), model=model_v2(), log_dir="logs-view", display="none")[0]
view = log.eval.viewer
print("stored in the log:", type(view).__name__, "| trust_content:", view.trust_content)
print("columns:", [(c.id, c.visible) for c in view.task_samples_view.columns])
print("sort:", [(s.column, s.dir) for s in view.task_samples_view.sort])
Output3 lines
stored in the log: ViewerConfig | trust_content: False
columns: [('sampleId', True), ('epoch', True), ('score__triage_labels__triage_labels', True), ('score__triage_format__triage_format', True), ('answer', True), ('input', False), ('tokens', False)]
sort: [('score__triage_labels__triage_labels', 'asc'), ('sampleId', 'asc')]
  • task_samples_view sets the sample list: column order and default visibility (built-in columns are sampleStatus, sampleId, sampleUuid, epoch, input, target, answer, tokens, duration, retries, error, limit; score columns come from TaskSamplesColumn.score("scorer"), or .score("scorer", "key") for one key of a dict-valued score), the sort, and multiline rows. Sorting by the labels score ascending puts T06 and T05 at the top of v2's list, which is where a reviewer should start.
  • sample_score_view configures the score panel of a single sample, and scanner_result_view the Scout results sidebar (10B.16); see the task views page for their fields, colour scales and score labels.
  • These are defaults, not overrides. A reviewer's own choices in the browser win (user override > view configuration > viewer built-in), so the layout helps without getting in anyone's way.
  • The score column ids are stored as score__<scorer>__<name>, as the output shows; you never type them, but you will see them if you inspect log.eval.viewer.

To change the view of a task you did not write, use task_with(task, viewer=...); it replaces the whole ViewerConfig, so copy the existing one with model_copy(update=...) to keep its other settings (10B.9, 8.4 explains why task_with mutates).

7.2 Untrusted content#

The viewer renders model output richly: markdown, maths, syntax highlighting, terminal colours, images, audio, video, clickable links. When the content comes from a model you cannot trust (a red-team target, a model without safeguards, an agent that browsed the web), rich rendering is an attack surface for the person reviewing it: deceptive links, hidden text, bidirectional-override characters that make text read differently from what it is. trust_content=False makes the viewer show literal source text, show escape sequences instead of interpreting them, replace media with placeholders, show links as text with their destination, and make invisible and bidirectional-override characters visible (for example ⟨U+202E⟩).

Where How
In the task (travels with every log) ViewerConfig(trust_content=False), as in 7.1; retries keep it
For every log a viewer shows inspect view --no-trust-content, INSPECT_VIEW_TRUST_CONTENT=false, or view(trust_content=False) in Python
Bundles and embedded viewers Only the log's own ViewerConfig applies; the inspect view flag does not reach a bundle

The flag only lowers trust: a log that sets trust_content=False is never rendered richly, whatever the viewer flag. Viewers that predate the setting (including older VS Code extensions) ignore it, and older Inspect versions drop it when they rewrite a log, so upgrade everyone who reviews untrusted logs. And it controls rendering only: content shown as text is still not safe to copy into a terminal or act on. Module 12 owns the wider topic of handling untrusted model output.

7.3 Live logs, shared logs and remote access#

  • Live view. The viewer updates while a run is in progress (completed samples, incremental metrics, transcripts as events arrive). From VS Code, the View Log link in the task display opens the live log; from the command line, the log history menu lists in-progress runs.
  • Live view on shared storage. Live data normally lives in a local database on the machine running the eval, so a colleague viewing the S3 log directory sees only flushed samples. inspect eval ... --log-shared also writes live data to the shared filesystem, every 10 seconds by default (--log-shared 30 for every 30).
  • Remote access, single user. Keep the viewer on loopback and forward the port: ssh -L 7575:127.0.0.1:7575 user@remote, then open http://127.0.0.1:7575 locally. If a local alias maps to loopback, declare it with --trusted-origin http://my-inspect:7575.
  • Remote access, a team. Binding beyond loopback (--host 0.0.0.0) requires request authorization: set INSPECT_VIEW_AUTHORIZATION_TOKEN to the complete Authorization header value the viewer should expect (for example Bearer ..., loaded from your secret manager), put the viewer behind an authenticating reverse proxy that strips any client-supplied copy of that header and injects the expected one, and declare the public origin with --trusted-origin. --unsafe-allow-unauthenticated exists and means what it says: anyone who can reach the address can call the viewer's APIs, which can read every log in the directory.

7.4 Publishing a bundle#

inspect view bundle --log-dir DIR --output-dir OUT (or bundle_log_dir(log_dir, output_dir, overwrite=False, fs_options={})) writes a self-contained static site: index.html, assets/, logs/ with the log files and a listing.json, content-security-policy.json and robots.txt (10B.8, 6.4 showed one). Details that matter when you deploy it:

  • The host must support HTTP range requests (a request that asks a server for just bytes 100 to 200 of a file, instead of the whole thing), because the viewer reads .eval members piecewise. GitHub Pages, S3 static hosting and Netlify do; Python's built-in http.server does not, so do not test a bundle with python -m http.server and conclude it is broken.
  • robots.txt excludes the site from indexing, but crawlers read it only at the root of a website. If you deploy the bundle in a subfolder, add the exclusion to your root robots.txt.
  • Link to one log with ?log_file=<file> on the bundle URL; the bundle opens the first log otherwise.
  • --output-dir hf/<org>/<space> publishes to a Hugging Face Space, private by default (public only with bundle_log_dir(..., fs_options={"private": False}) from Python); it needs huggingface_hub and a token. An S3 URL also works as the output, and INSPECT_VIEW_BUNDLE_OUTPUT_DIR sets a default.
  • An existing output directory is not overwritten without --overwrite, and eval sets can bundle automatically (eval_set(bundle_dir=...), 10B.12).

7.5 Scrubbing a log before it leaves your machine#

A bundle publishes the logs as they are, and 10B.8, 6.4 listed what they reveal: the git remote and commit, every prompt and template, every input and output, sample metadata, model arguments and the task file path. Inspect has no "scrub" command, but the log API is enough to write one: read, remove, write a copy to a separate directory, verify, then bundle that directory.

python
# l07_publish.py: scrub a log before publishing it as a static viewer bundle (lesson 10B.13)
import os
import zipfile

from inspect_ai.log import bundle_log_dir, read_eval_log, write_eval_log

from lab_paths import lab_logs



def contains(path: str, needle: str) -> bool:
    """Search a .eval archive's members (decompressed via Inspect) or a plain file."""
    if path.endswith(".eval"):
        log = read_eval_log(path)
        return needle in log.model_dump_json()
    return needle in open(path, encoding="utf-8", errors="ignore").read()


src = lab_logs()["v2"]
log = read_eval_log(src)
print("before:", log.eval.revision, "| task_file:", log.eval.task_file)

# Derive the needle from the log itself: your private remote URL, minus scheme and ".git".
# No git remote when the log was written means there is nothing to scrub and nothing to find.
if log.eval.revision is None or not log.eval.revision.origin:
    raise SystemExit("this log records no git remote: run the lab inside a git repo with an origin")
SECRET = log.eval.revision.origin.split("//")[-1].removesuffix(".git")
print("searching for:", SECRET)

# What to remove depends on your threat model. Here: repository identity and an internal owner.
log.eval.revision = None
log.eval.metadata = {k: v for k, v in (log.eval.metadata or {}).items() if k != "owner"}
os.makedirs("publish", exist_ok=True)
out = os.path.join("publish", os.path.basename(src.name))
write_eval_log(log, out)
print("after :", read_eval_log(out, header_only=True).eval.revision)
print("secret in original:", contains(src.name.removeprefix("file://"), SECRET),
      "| in scrubbed copy:", contains(out, SECRET))

bundle_log_dir(log_dir="publish", output_dir="triage-www", overwrite=True)
files = sorted(os.listdir("triage-www"))
print("bundle:", files, "| logs/:", sorted(os.listdir("triage-www/logs")))
size = sum(os.path.getsize(os.path.join(d, f)) for d, _, fs in os.walk("triage-www") for f in fs)
print(f"bundle size: {size / 1e6:.1f} MB")
bash
uv run python l07_publish.py
Output9 lines
before: type='git' origin='https://example.com/acme/support-evals.git' commit='fada17f' dirty=False | task_file: triage.py
searching for: example.com/acme/support-evals
after : None
secret in original: True | in scrubbed copy: False
Creating view bundle in 'triage-www'

View bundle 'triage-www' created
bundle: ['assets', 'content-security-policy.json', 'index.html', 'logs', 'robots.txt'] | logs/: ['2026-11-26T02-09-19-00-00_triage_dhjdm6eMvjRBqiK2EWE4gw.eval', 'listing.json']
bundle size: 11.3 MB

The search term is derived from the log's own remote, so the sample works on any machine (it stops with a message when the log records no remote, because then there is nothing to scrub). The original log still contains the remote URL; the scrubbed copy does not, and the bundle was built from the scrubbed directory only (about 11 MB, nearly all of it the viewer's assets). Three points about doing this for real:

  • Decide what to remove from a threat model, not a habit. The repository URL and internal owner are the easy part. If the dataset holds customer tickets, the inputs and outputs are the sensitive data, and no field-level scrub makes the log publishable: publish results and synthetic or redacted samples instead.
  • Verify by searching the output, not by trusting the code. The contains() check searches the whole serialized log for the secret; extend it with every pattern you care about (domains, customer names, email addresses, API key prefixes). Model outputs can repeat anything that was in the prompt.
  • Headers can carry secrets too. eval.model_args, eval.task_args and eval.metadata are free-form and are written as given; recent Inspect releases redact credentials embedded in the git remote URL and no longer write remote MCP server credentials to logs (check the changelog for your version), but nothing protects a token you put in a task argument. This is why the search step matters. Also, the changelog for the 0.3.29x releases says inspect view bundle and inspect log convert now keep files inside the output directory, so on older versions prefer a fresh, empty output directory.
  • Keep the scrubbed copy separate (publish/ here) and never write it back over the original: the original is your record.

Part 8: Dataframes#

Deep-dive

8.1 Four tables from a directory of logs#

inspect_ai.analysis flattens logs into pandas dataframes at four levels:

Function One row per Default columns Reads
evals_df() Log (task × model run) EvalColumns: info, task, model, dataset, configuration, results, scores Headers only: fast
samples_df() Sample per epoch SampleSummary: the summary fields, metadata and score values Summaries only by default: fast
messages_df() Message MessageColumns: role, content, source, tool calls Full samples: slower
events_df() Event EventInfo: event type and span Full samples: slower

Every function takes logs as a directory, a log path, a list of paths, EvalLogInfos (for example the output of a filtered list_eval_logs()), or EvalLog objects. Every frame includes a log column (the URI) and the id columns needed to join the levels: eval_id everywhere, sample_id from samples down, message_id and event_id at their levels. Row order in these frames follows the directory listing and carries no meaning (the three lab logs were written within the same second, so ties fall to random file names): sort or filter before you read rows, as the sample does. They need pandas ≥ 2.1.0 and pyarrow ≥ 10.0.1, which inspect-ai does not install; without them the call fails at run time.

python
# l08_dataframes.py: the four dataframes on the lab logs (lesson 10B.13; needs pandas and pyarrow)
import pandas as pd

from inspect_ai.analysis import evals_df, events_df, messages_df, samples_df

pd.set_option("display.width", 120)
pd.set_option("display.max_columns", 12)

# One row per log.
evals = evals_df("logs-lab", quiet=True)
print("evals_df   :", evals.shape)
print(evals[["model", "status", "tags", "task_version", "epochs", "completed_samples",
             "score_headline_name", "score_headline_value"]].sort_values("model").to_string(index=False))
print("score columns:", [c for c in evals.columns if c.startswith("score_") and "headline" not in c])

# One row per sample PER EPOCH.
samples = samples_df("logs-lab", quiet=True)               # default columns: SampleSummary
print("\nsamples_df :", samples.shape)
print("columns    :", list(samples.columns))
# Row order follows the directory listing, which means nothing: pick one run before looking at rows.
v2 = samples[samples["eval_id"] == evals.loc[evals["model"] == "mockllm/triage-v2", "eval_id"].item()]
print(v2[["id", "epoch", "sample_id", "score_triage_format", "score_triage_labels",
          "metadata_intent", "error"]].head(3).to_string(index=False))

# One row per message. In 0.3.292 the filter must be a callable: a list of roles
# (as in the docs) is silently ignored.
as_list = messages_df("logs-lab", filter=["assistant"], quiet=True)
print("\nmessages_df, filter=['assistant'] :", as_list.shape, as_list["role"].value_counts().to_dict())
messages = messages_df("logs-lab", filter=lambda m: m.role == "assistant", quiet=True)
print("messages_df, filter=callable      :", messages.shape, messages["role"].value_counts().to_dict())
print("columns    :", list(messages.columns))

# One row per event.
events = events_df("logs-lab", quiet=True)
print("events_df  :", events.shape, list(events.columns))
print("event kinds:", events["event"].value_counts().to_dict())
bash
uv run python l08_dataframes.py
Output19 lines
evals_df   : (3, 56)
            model  status      tags  task_version  epochs  completed_samples score_headline_name  score_headline_value
mockllm/triage-v1 success  baseline             1       2               24.0       triage_format              0.916667
mockllm/triage-v2 success candidate             1       2               24.0       triage_format                   1.0
mockllm/triage-v3   error candidate             1       2               <NA>                <NA>                  <NA>
score columns: ['score_triage_format_accuracy', 'score_triage_format_stderr', 'score_triage_labels_mean', 'score_triage_labels_stderr']

samples_df : (72, 26)
columns    : ['sample_id', 'eval_id', 'log', 'id', 'epoch', 'input', 'choices', 'target', 'description', 'metadata_allow_empty_summary', 'metadata_edge', 'metadata_intent', 'score_triage_format', 'score_triage_labels', 'model_usage', 'total_tokens', 'total_time', 'working_time', 'message_count', 'turn_count', 'token_limit_usage', 'error', 'limit', 'limit_reason', 'retries', 'fallbacks']
 id  epoch              sample_id score_triage_format  score_triage_labels metadata_intent error
T01      1 bECDiF53tJecjaRRzn3U7x                   C                  1.0         billing      
T02      1 Aj6ipmPGB46zt8PQfTPuX9                   C                  1.0       technical      
T03      1 Xb82hFX4zVV3tBPoHq2vPM                   C                  1.0         account      

messages_df, filter=['assistant'] : (144, 12) {'user': 72, 'assistant': 72}
messages_df, filter=callable      : (72, 12) {'assistant': 72}
columns    : ['message_id', 'sample_id', 'eval_id', 'log', 'role', 'source', 'content', 'tool_calls', 'tool_call_id', 'tool_call_function', 'tool_call_error', 'order']
events_df  : (1424, 7) ['event_id', 'sample_id', 'eval_id', 'log', 'event', 'span_id', 'order']
event kinds: {'span_begin': 498, 'span_end': 498, 'state': 142, 'score': 140, 'sample_init': 72, 'model': 72, 'error': 2}

8.2 evals_df(): one row per log#

Three logs, 56 columns. The columns come in groups (8.6) and follow naming rules worth knowing by heart:

  • Scores: score_<scorer>_<metric> (score_triage_format_accuracy, score_triage_labels_stderr), also when the task uses a single non-default reducer such as Epochs(5, "pass_k_2") (checked on 0.3.292 with Epochs(2, "max"): EvalScore.reducer is 'max', the columns are unchanged). The reducer is inserted, score_<scorer>_<reducer>_<metric> (score_triage_correct_pass_k_2_accuracy in 10B.10, 6.14), only when a scorer has several reducers reporting the same metric. Code that hard-codes one form breaks when someone adds a reducer; select columns by prefix or read EvalScores from headers when you need to be robust.
  • The headline: five columns, score_headline_name, score_headline_score, score_headline_metric, score_headline_value and score_headline_stderr. By default the headline is the first scorer's first metric (here triage_format's accuracy); a task can name a different one with headline_metric (10B.10, 6.13). A leaderboard built on score_headline_value across tasks compares whatever each task's author made first, which is rarely what you meant.
  • Task arguments become task_arg_<name> columns; revision becomes git_origin and git_commit.
  • Failed runs stay in the frame with <NA> results: v3's completed_samples and every score column are missing. That is correct and useful (a run table should show failed runs), but a groupby().mean() silently skips NA, so filter on status == "success" before aggregating anything.

8.3 samples_df(): one row per sample per epoch#

72 rows: 12 samples × 2 epochs × 3 logs. The columns: sample_id, eval_id, log, id, epoch, input, choices, target, description, one metadata_<key> column per metadata key, one score_<scorer> column per scorer, model_usage, total_tokens, total_time, working_time, message_count, turn_count, token_limit_usage, error, limit, limit_reason, retries, fallbacks.

The three rules that cause most analysis bugs:

  1. id is the dataset id; sample_id is a generated, globally unique id for one sample execution (different in every log and every epoch). Join runs on id and epoch, never on sample_id (10B.10, 8.4 makes the same point).
  2. One row per epoch. A mean over rows is a mean over sample-epochs, which weights samples by their number of epochs and ignores the task's reducer. Reduce per id first (as 9.3 does), with the reducer the task used.
  3. Score values stay raw. score_triage_format holds "C" and "I" strings; convert with score_to_float() (8.7) or an explicit mapping before averaging, and remember that NaN means unscored, not zero.

The error column is an empty string for samples without errors, not None; filter with df["error"] != "".

8.4 messages_df(): one row per message, and a filter trap#

The docs show messages_df("logs", filter=["assistant"]) to keep only assistant messages. In 0.3.292 a list is silently ignored: the probe got 144 rows (72 user and 72 assistant messages), the same as no filter. The installed signature types filter as a callable that receives each ChatMessage, and a callable works: filter=lambda m: m.role == "assistant" returned the 72 assistant messages. Use a callable until the docs and the code agree, and check the role counts whenever you filter.

The default columns are role, content (the message text), source, tool_calls (formatted calls, one per line), tool_call_id, tool_call_function, tool_call_error and order (the position in the conversation). For agent evals, tool_call_function and tool_call_error across all samples answer "which tools fail, and how often?" in one groupby.

8.5 events_df(): one row per event#

1,424 events across the three logs, with the counts by type in the output. Two error events are v3's T09 epochs; 140 score events rather than 144 because those two errored samples were never scored. The default columns are only event_id, sample_id, eval_id, log, event, span_id and order, because events are too varied for one default; you compose columns from the groups EventInfo, EventTiming (start and end, clock and working time), ModelEventColumns and ToolEventColumns, and filter with a callable on the event (8.6 has the example).

8.6 Column groups, custom columns and strict mode#

python
# l09_columns.py: column groups, custom columns, strict mode and prepare() (lesson 10B.13)
import pandas as pd

from inspect_ai.analysis import (EvalInfo, EvalModel, EvalResults, EventTiming, ModelEventColumns,
                                 SampleColumn, SampleScores, SampleSummary, evals_df, events_df,
                                 log_viewer, prepare, samples_df, score_to_float, task_info)
from inspect_ai.log import list_eval_logs

pd.set_option("display.width", 120)
ok = list_eval_logs("logs-lab", filter=lambda log: log.status == "success")

# 1. Column groups combine with +. Eval-level columns ride along on every sample row.
evals = evals_df(ok, columns=EvalInfo + EvalModel + EvalResults, quiet=True)
print("EvalInfo+EvalModel+EvalResults:", evals.shape)
rows = samples_df(ok, columns=EvalModel + SampleSummary + SampleScores, quiet=True)
print("EvalModel+SampleSummary+SampleScores:", rows.shape)
print("score detail columns:", [c for c in rows.columns if c.startswith("score_triage_format")])

# 2. Custom columns: a JSON path, a callable, and a full-sample read.
custom = samples_df(ok, quiet=True, columns=EvalModel + [
    SampleColumn("id", path="id", required=True, type=str),
    SampleColumn("epoch", path="epoch", required=True),
    SampleColumn("edge", path="metadata.edge"),
    SampleColumn("labels", path="scores.triage_labels.value"),
    SampleColumn("labels_why", path="scores.triage_labels.explanation", full=True),
    SampleColumn("tokens", path=lambda s: s.model_usage[next(iter(s.model_usage))].total_tokens),
])
bad = custom[custom["labels"] < 1]
print("\ncustom columns:", list(custom.columns))
print(bad[["model", "id", "epoch", "edge", "labels", "labels_why", "tokens"]].to_string(index=False))

# 3. strict=False: collect column errors instead of aborting the whole read.
df, errors = samples_df(ok, quiet=True, strict=False, columns=SampleSummary + [
    SampleColumn("customer", path="metadata.customer", required=True)])
print("\nstrict=False:", df.shape, "|", len(errors), "errors, first:", str(errors[0])[:90])

# 4. prepare(): built-in operations on a frame.
evals = prepare(evals_df(ok, quiet=True), [
    task_info({"triage": "Ticket triage (Acme Cloud)"}),
    log_viewer("eval", {"logs-lab": "https://evals.example.com/triage"}),
])
print("\nprepare() added:", [c for c in evals.columns if c in ("task_display_name", "log_viewer")])
print(evals[["task_display_name", "log_viewer"]].iloc[0].to_dict())
floats = prepare(samples_df(ok, quiet=True), score_to_float("score_triage_format"))
print("score_to_float:", floats["score_triage_format"].unique().tolist())

# 5. Event-level timing and model-call columns.
model_events = events_df(ok, columns=EventTiming + ModelEventColumns,
                         filter=lambda e: e.event == "model", quiet=True)
print("\nmodel events:", model_events.shape)
print("columns:", list(model_events.columns))
bash
uv run python l09_columns.py
Output22 lines
EvalInfo+EvalModel+EvalResults: (2, 26)
EvalModel+SampleSummary+SampleScores: (48, 37)
score detail columns: ['score_triage_format', 'score_triage_format_answer', 'score_triage_format_explanation', 'score_triage_format_reason']

custom columns: ['sample_id', 'eval_id', 'model', 'model_base_url', 'model_args', 'model_generate_config', 'model_roles', 'log', 'id', 'epoch', 'edge', 'labels', 'labels_why', 'tokens']
            model  id  epoch           edge    labels                labels_why  tokens
mockllm/triage-v2 T06      1     bug-report  0.666667           wrong: category     360
mockllm/triage-v2 T05      2 stale-tracking  0.666667           wrong: priority     363
mockllm/triage-v2 T06      2     bug-report  0.666667           wrong: category     360
mockllm/triage-v1 T02      1         outage  0.333333 wrong: priority, category     360
mockllm/triage-v1 T11      1          typos  0.333333  wrong: category, summary     390
mockllm/triage-v1 T02      2         outage  0.333333 wrong: priority, category     360
mockllm/triage-v1 T11      2          typos  0.333333  wrong: category, summary     390

strict=False: (48, 27) | 48 errors, first: Error reading column 'customer' from path 'metadata.customer': field not found (log: file:

prepare() added: ['task_display_name', 'log_viewer']
{'task_display_name': 'Ticket triage (Acme Cloud)', 'log_viewer': 'https://evals.example.com/triage/#/logs/2026-11-24T18-01-46-00-00_triage_FBUbRR9xinMvQpRSDt3jv9.eval'}
score_to_float: [1.0, 0.0]

model events: (48, 23)
columns: ['event_id', 'sample_id', 'eval_id', 'log', 'timestamp', 'completed', 'working_start', 'working_time', 'model_event_model', 'model_event_role', 'model_event_requested_model', 'model_event_input', 'model_event_tools', 'model_event_tool_choice', 'model_event_config', 'model_event_usage', 'model_event_time', 'model_event_completion', 'model_event_retries', 'model_event_error', 'model_event_cache', 'model_event_call', 'order']

Column groups combine with +, and eval-level groups can ride along on sample, message and event rows:

Level Groups (the default in bold)
Evals EvalColumns = EvalInfo + EvalTask + EvalModel + EvalDataset + EvalConfiguration + EvalResults + EvalScores
Samples SampleSummary; SampleScores (adds each score's answer, explanation, reason and metadata as score_<scorer>_<field> columns); SampleMessages (the conversation as text; needs full reads)
Messages MessageColumns = MessageContent + MessageToolCalls
Events EventInfo, EventTiming, ModelEventColumns, ToolEventColumns (no default beyond the ids and type)

EvalModel + SampleSummary + SampleScores gave 48 rows (the two successful logs) and 37 columns, including score_triage_format_reason, the machine-readable reason from 10B.10, 4.4 as a column you can group by.

Custom columns are EvalColumn, SampleColumn, MessageColumn or EventColumn objects with a name and a path:

Option Meaning
path="metadata.edge" A JSON path into the record (jsonpath syntax)
path=callable A function of the record (an EvalLog, EvalSampleSummary or EvalSample, a message, an event) returning a JSON value: the tokens column above
name="metadata_*" A wildcard name expands a dict into one column per key; drop the _* to keep the dict as one JSON column
required=True Missing values are errors, not None
default=, type=, value= A default when missing, a type to coerce to (strings are interpreted as YAML first, so "true" becomes True), and a transform of the extracted value
full=True Read from the full sample instead of the summary: needed for labels_why, because summaries keep only score values

When a name repeats in the column list, the last definition wins, which is how you override a default column. Custom extraction functions for messages and events must not mutate what they receive (renders are cached per sample).

Strict mode. By default a missing required field or a bad path raises and aborts the read. strict=False returns (df, errors) instead: the probe asked for a required metadata.customer that no sample has and got the frame plus 48 errors, one per row. Use strict mode in pipelines (fail loudly) and strict=False in exploration (see everything that is wrong at once). Note that samples_df(full=True) is a shorthand that reads full metadata, and parallel=True (or a worker count; the default is capped at 8 processes) speeds up full-sample reads of many logs; evals_df() has no parallel option because headers are cheap.

8.7 prepare(): built-in transformations#

prepare(df, operations) applies Operations to a frame:

Operation Adds or changes Notes
score_to_float("score_x") (or a list) Converts score columns to floats with value_to_float() C→1.0, I→0.0 in the probe; unknown strings become 0.0, as in metrics (10B.10, 2.4)
task_info({"triage": "Ticket triage (Acme Cloud)"}) task_display_name Human-readable names for charts and tables
log_viewer(target, {"logs-lab": "https://..."}), with target one of "eval", "sample", "event", "message" log_viewer URL column Maps local log paths to a published bundle (7.4), so every row of a report links to its evidence; the probe mapped logs-lab to https://evals.example.com/triage/#/logs/<file>
model_info() model_organization_name, model_display_name, model_snapshot, model_release_date, model_knowledge_cutoff_date Built-in metadata for many provider models (none for mockllm); you can supply your own
frontier() frontier (True when the model was the top scorer for the task among models released by then) Needs model_info() first; for capability tracking over time

8.8 SQL over the frames#

Because every frame carries its join keys, a directory of logs becomes a small relational database. With DuckDB, con.register("evals", evals_df(...)) and con.register("samples", samples_df(...)) make two tables you can join on eval_id; block 6 of 9.1's script does exactly that to compute tokens per model. Use SQL when the analysis is easier to say as a query (joins across levels, windows, group-bys that colleagues will read), and when you want to load the frames into a warehouse table that dashboards already query. The log and log_viewer columns keep every row traceable to its file.


Part 9: Analysis recipes#

Deep-dive

The tools are only half of analysis; the other half is the order of questions. This part runs the questions an evaluation owner asks about the lab, in that order, in one script, then turns a log into a tracking record. Statistics come last and are handed to 10B.10, Part 8, which already applies evalkit's paired tests to Inspect logs.

python
# l10_analysis.py: from a log directory to a review table (lesson 10B.13)
import duckdb
import pandas as pd

from inspect_ai.analysis import EvalModel, SampleSummary, evals_df, samples_df
from inspect_ai.log import EvalLog, read_eval_log

from lab_paths import lab_logs

pd.set_option("display.width", 120)
logs = lab_logs()


# 1. Refuse to compare runs that did not measure the same thing.
def comparable(a: EvalLog, b: EvalLog) -> list[str]:
    problems = []
    for log in (a, b):
        if log.status != "success":
            problems.append(f"{log.eval.model}: status {log.status}")
        elif log.results.completed_samples != log.results.total_samples:
            problems.append(f"{log.eval.model}: incomplete")
    checks = {
        "task": lambda l: l.eval.task,
        "task_version": lambda l: l.eval.task_version,
        "sample ids": lambda l: l.eval.dataset.sample_ids,
        "epochs": lambda l: l.eval.config.epochs,
        "reducers": lambda l: l.eval.config.epochs_reducer,
        "scorers": lambda l: [s.name for s in l.eval.scorers],
        "solver plan": lambda l: [(s.solver, s.params) for s in l.plan.steps],
    }
    problems += [f"{name} differs" for name, get in checks.items() if get(a) != get(b)]
    return problems


v1, v2, v3 = (read_eval_log(logs[k], header_only=True) for k in ("v1", "v2", "v3"))
print("v1 vs v2:", comparable(v1, v2) or "comparable")
print("v1 vs v3:", comparable(v1, v3) or "comparable")

# 2. The run table, with coverage next to every number.
evals = evals_df([logs[k] for k in ("v1", "v2", "v3")], quiet=True)
table = evals[["model", "status", "completed_samples", "total_samples",
               "score_triage_format_accuracy", "score_triage_labels_mean",
               "score_triage_labels_stderr"]].sort_values("model")
print("\n" + table.to_string(index=False))

# 3. Per-slice view, from per-sample rows (epochs reduced by mean first).
s = samples_df([logs["v1"], logs["v2"]], columns=EvalModel + SampleSummary, quiet=True)
per_ticket = (s.groupby(["model", "id", "metadata_intent"], as_index=False)["score_triage_labels"]
              .agg(labels="mean", spread=lambda x: x.max() - x.min()))
by_intent = per_ticket.pivot_table(index="metadata_intent", columns="model", values="labels",
                                   aggfunc="mean").round(3)
by_intent["n"] = per_ticket.groupby("metadata_intent")["id"].nunique()
print("\nlabels by intent (mean of per-ticket means):\n" + by_intent.to_string())

# 4. What changed, ticket by ticket, and what is flaky.
wide = per_ticket.pivot(index="id", columns="model", values="labels")
wide.columns = ["v1", "v2"]
wide["change"] = (wide["v2"] - wide["v1"]).round(3)
print("\nchanged tickets:\n" + wide[wide["change"] != 0].round(3).to_string())
flaky = per_ticket[per_ticket["spread"] > 0][["model", "id", "spread"]]
print("flaky (epochs disagree):", flaky.to_dict("records"))

# 5. The failed run: what errored, and how much was scored anyway.
e = samples_df(logs["v3"], quiet=True)
print("\nv3 rows:", len(e), "| errored:", sorted(set(e.loc[e["error"] != "", "id"])),
      "| error text:", e.loc[e["error"] != "", "error"].iloc[0][:45])

# 6. SQL over the frames: tokens per model, joined on eval_id.
con = duckdb.connect()
con.register("evals", evals_df([logs["v1"], logs["v2"], logs["v3"]], quiet=True))
con.register("samples", samples_df([logs["v1"], logs["v2"], logs["v3"]], quiet=True))
print("\n" + con.execute("""
    SELECT e.model, e.status, count(*) AS rows, round(avg(s.total_tokens), 1) AS avg_tokens
    FROM evals e JOIN samples s ON e.eval_id = s.eval_id
    GROUP BY e.model, e.status ORDER BY e.model
""").fetchdf().to_string(index=False))
bash
uv run python l10_analysis.py
Output32 lines
v1 vs v2: comparable
v1 vs v3: ['mockllm/triage-v3: status error']

            model  status  completed_samples  total_samples  score_triage_format_accuracy  score_triage_labels_mean  score_triage_labels_stderr
mockllm/triage-v1 success               24.0             24                      0.916667                  0.888889                    0.074911
mockllm/triage-v2 success               24.0             24                           1.0                  0.958333                    0.029906
mockllm/triage-v3   error               <NA>             24                          <NA>                      <NA>                        <NA>

labels by intent (mean of per-ticket means):
model            mockllm/triage-v1  mockllm/triage-v2  n
metadata_intent
account                        1.0                1.0  3
billing                      0.778                1.0  3
other                          1.0                1.0  2
shipping                       1.0              0.833  1
technical                    0.778              0.889  3

changed tickets:
        v1     v2  change
id
T02  0.333    1.0   0.667
T05    1.0  0.833  -0.167
T06    1.0  0.667  -0.333
T11  0.333    1.0   0.667
flaky (epochs disagree): [{'model': 'mockllm/triage-v2', 'id': 'T05', 'spread': 0.33333333333333337}]

v3 rows: 24 | errored: ['T09'] | error text: RuntimeError('503 from the model gateway (sim

            model  status  rows  avg_tokens
mockllm/triage-v1 success    24       364.6
mockllm/triage-v2 success    24       367.2
mockllm/triage-v3   error    24       334.3

9.1 Refuse to compare what is not comparable#

The first block answers "may these two runs be compared at all?" before anything else. comparable() checks both runs succeeded and are complete, then compares the fields that define the measurement: task, task version, sample ids, epochs, reducers, scorer names and the solver plan (which includes the prompt template). v1 and v2 pass; v3 is refused because it errored. The check is cheap (headers only) and it catches the comparisons that waste the most time later: a run on --limit 50 compared with a full run, a prompt edited between runs, a scorer added in one run but not the other, a task version bump.

What it deliberately does not compare is the model: v1 and v2 differ in model, and that difference is the experiment. Decide for each analysis which fields are the treatment (allowed to differ) and which are the controls (must match), and write the controls down as code, as here. For content changes behind unchanged ids, add the fingerprint of 9.6.

9.2 The run table, with coverage next to every number#

The second block is the table to put at the top of any report: one row per run, the status, completed_samples of total_samples, then the metrics. v3 appears with <NA>, which is the honest entry for a failed run; hiding it would make the candidate list look cleaner than the week actually was. Add scored_samples from the headers when scorers can return unscored values (10B.10, 4.6).

9.3 Slices, and what changed#

Blocks 3 and 4 work on per-sample rows from samples_df() with the model columns added, and they reduce epochs per ticket first (mean, the task's reducer), then aggregate. Two views come out:

  • By intent (the metadata_intent column, from the sample metadata of 10B.8, 4.2): v2 improves billing (0.778 → 1.0) and technical (0.778 → 0.889) and gets worse on shipping (1.0 → 0.833). The n column matters more than the numbers: shipping has one ticket, so "shipping regressed" means "T05 regressed". Always print slice sizes next to slice metrics, and treat small-slice differences as leads, not findings (10B.10, 8.6). Inspect's in-run alternative is the grouped() metric (10B.10, 6.8); the dataframe route lets you slice after the fact by anything in the metadata.
  • By ticket: four tickets changed. T02 and T11 improved by two thirds (the fixes), T06 lost a third (the wrong category, in both epochs: a regression), T05 lost a sixth (one epoch of two: flakiness). The spread column (max minus min across epochs) separates the two: T05 is the only ticket whose epochs disagree.

This is the error-analysis view that 10A.1, Part 4 put first, and it changes the decision. v2's mean is higher, yet it introduced a deterministic regression (T06 is now misrouted to the account team) and a flaky answer. Whether to ship is a product judgement; the analysis's job is to make sure nobody makes it from the mean alone. The next step is to read the two transcripts (read_eval_log_sample(log, "T06", 1), or the viewer with the layout of 7.1).

9.4 The failed run#

Block 5 reads v3's rows: 24 rows, errors only on T09, with the error text. The failure is isolated to one ticket and looks like a provider fault (a 503), not a task bug, which points to retry_on_error or eval_retry() (10B.12) rather than a code fix. Reading the error is the whole point: a scorer exception on every sample and a provider blip on one look identical in a run table.

9.5 Tokens and cost#

Block 6 joins evals to samples in DuckDB and averages total_tokens per model (the mock's counts are fake, 10B.8, 9.5, but the query is the one you would run on real logs). For real runs, cost per sample is a first-class result next to quality (10A.10, Part 6 treats cost as a non-functional quality): configure model prices so that total_cost is filled (3.6), or join a price table on the model column yourself. Note the errored run's average: errored samples have no usage, so "average tokens" for v3 is biased low. Exclude errored rows from per-sample averages, and count them separately.

9.6 From log to run record#

10A.8, 7.1 defined the fields every run record needs (run, created_at, git_sha, dataset version and fingerprint, prompt hash, model, judge, scores, per-case rows, config). An Inspect log contains almost all of them; this function extracts them in 10A.8's shape, adds the two that a log does not have (a dataset content fingerprint and a prompt hash), and refuses failed runs:

python
# l14_manifest.py: an Inspect log as a 10A.8-style run manifest plus per-case rows (lesson 10B.13)
import hashlib
import json

from inspect_ai.log import EvalLogInfo, read_eval_log, read_eval_log_sample_summaries

from lab_paths import lab_logs


def sha16(text: str) -> str:
    return hashlib.sha256(text.encode()).hexdigest()[:16]


def dataset_fingerprint(info: EvalLogInfo) -> str:
    """Hash of every (id, input, target) the run saw: catches edited content behind unchanged ids."""
    seen = {(str(s.id), str(s.input), str(s.target)) for s in read_eval_log_sample_summaries(info)}
    return sha16("\x00".join("\x01".join(row) for row in sorted(seen)))


def manifest_from_log(info: EvalLogInfo) -> tuple[dict, list[dict]]:
    log = read_eval_log(info, header_only=True)
    assert log.status == "success", f"refusing to record a run with status {log.status!r}"
    rev = log.eval.revision
    template = next((s.params.get("template", "") for s in log.plan.steps
                     if s.solver == "prompt_template"), "")
    manifest = {
        "run": f"{log.eval.task}-{log.eval.model.replace('/', '_')}-{log.eval.run_id[:6]}",
        "created_at": log.eval.created,
        "git_sha": rev.commit if rev else None,
        "git_dirty": rev.dirty if rev else None,
        "n_results": log.results.completed_samples,
        "system": {
            "task": log.eval.task, "task_version": log.eval.task_version,
            "dataset_fingerprint": dataset_fingerprint(info),
            "model": log.eval.model, "generate_config": log.eval.model_generate_config.model_dump(exclude_none=True),
            "prompt_sha": sha16(template),
            "scorers": [s.name for s in log.eval.scorers],
            "epochs": log.eval.config.epochs, "inspect_ai": log.eval.packages.get("inspect_ai"),
        },
        "metrics": {f"{s.name}/{k}": round(m.value, 4) for s in log.results.scores
                    for k, m in s.metrics.items()},
        "inspect_log": info.name.rsplit("/", 1)[-1],
    }
    # Per-case rows from the reductions: the exact values the metrics were computed from.
    rows = [{"case_id": str(x.sample_id), "scorer": r.scorer, "value": round(x.value, 4)}
            for r in log.reductions for x in r.samples]
    return manifest, rows


logs = lab_logs()
m1, rows1 = manifest_from_log(logs["v1"])
m2, _ = manifest_from_log(logs["v2"])
print(json.dumps(m1, indent=1, default=str))
print("rows:", len(rows1), "| first:", rows1[0])
print("same dataset fingerprint v1/v2:", m1["system"]["dataset_fingerprint"] == m2["system"]["dataset_fingerprint"])
try:
    manifest_from_log(logs["v3"])
except AssertionError as e:
    print("v3:", e)
bash
uv run python l14_manifest.py
Output31 lines
{
 "run": "triage-mockllm_triage-v1-CL8Lux",
 "created_at": "2026-11-24T18:01:46+00:00",
 "git_sha": "fada17f",
 "git_dirty": false,
 "n_results": 24,
 "system": {
  "task": "triage",
  "task_version": 1,
  "dataset_fingerprint": "a786f866887141c6",
  "model": "mockllm/triage-v1",
  "generate_config": {},
  "prompt_sha": "abdc05fd886877ea",
  "scorers": [
   "triage_format",
   "triage_labels"
  ],
  "epochs": 2,
  "inspect_ai": "0.3.292"
 },
 "metrics": {
  "triage_format/accuracy": 0.9167,
  "triage_format/stderr": 0.0833,
  "triage_labels/mean": 0.8889,
  "triage_labels/stderr": 0.0749
 },
 "inspect_log": "2026-11-24T18-01-46-00-00_triage_6WUDzisSyNAKhNn7oATbjw.eval"
}
rows: 24 | first: {'case_id': 'T01', 'scorer': 'triage_format', 'value': 1.0}
same dataset fingerprint v1/v2: True
v3: refusing to record a run with status 'error'
  • The dataset fingerprint hashes every (id, input, target) the run saw, read from the summaries (no transcripts needed). v1 and v2 share it, so they saw identical data; an edited target behind an unchanged id would change it, which dataset.sample_ids cannot detect (3.3).
  • The prompt hash comes from the prompt_template step of the plan; two runs with the same hash used the same prompt text.
  • The per-case rows come from the reductions: the exact values the metrics used, one per sample and scorer, ready for evalkit.compare's paired functions or for save_run()'s results.jsonl.
  • The record links back to the log file (inspect_log), so the record is an index into the evidence, not a copy of it.

What this means for you as an engineer: you do not need a tracking platform to have tracking. Write this manifest next to every log you keep (or push it to the tool of your choice from a hook, 10.5), and you have 10A.8's audit trail with Inspect's transcripts behind it.

9.7 Statistics: the hand-off#

Everything above is descriptive. Whether v2 is better than v1, given 12 tickets and a flaky one, is a statistical question, and Inspect does not answer it: it reports a standard error per run, not a paired comparison between runs. 10B.10, 8.3 to 8.8 does that on Inspect logs with evalkit/compare.py: paired bootstrap intervals on the reduced per-sample values, cluster bootstraps for grouped samples, multiple-comparison corrections for slices, the minimum detectable effect, and the gate rules. Feed it log.reductions (or the per-case rows of 9.6) after the comparability check of 9.1 has passed.

9.8 Inspect Viz and Inspect Scout, in brief#

Inspect Viz (inspect-viz 0.4.2, released 19 October 2026 by Meridian Labs, MIT, as of November 2026) is the official companion for plotting the dataframes of this part. It reads evals_df(), samples_df() and the other frames (also Parquet, Polars and PyArrow data), provides pre-built views for the common questions (scores by task and model, scores against model release date, score timelines) and composable marks (dots, bars, cells, text, images, arrows) for custom plots, with tooltips and interactive filtering that link back to the underlying transcripts, and publishes to notebooks, Quarto, websites, dashboards or static images. It was not installed for this lesson, so no output is shown; its gallery at meridianlabs-ai.github.io/inspect_viz is the place to start. Inspect Scout analyses transcripts at scale with scanners (including model-based ones) over the same logs; it is the tool for "how often does the agent do X?" across thousands of samples, and 10B.16 covers it. The docs also list CJE, a community package for calibrating model-graded scores against oracle labels, among the log analysis tools; calibration itself is 10A.5's subject.


Part 10: Extending Inspect#

Deep-dive

10.1 The extension points#

Inspect is built to be extended without forking: the same registry that makes @task, @solver and @scorer addressable by name also loads model providers, hooks, approvers and sandbox environments from installed packages. One entry point in a package's pyproject.toml makes all of them available to every Inspect user who installs the package.

flowchart LR
    PKG["Your package<br/>pyproject.toml entry point<br/>inspect_ai = pkg._registry"] --> REG["_registry.py<br/>imports register names"]
    REG --> T["@task, @solver,<br/>@scorer, @tool<br/>pkg/name"]
    REG --> M["@modelapi<br/>--model name/model"]
    REG --> HK["@hooks<br/>lifecycle events"]
    REG --> AP["@approver<br/>approval policies"]
    REG --> SB["@sandboxenv<br/>sandbox providers"]
    FS["fsspec.specs entry point"] --> FSX["Custom filesystem<br/>myfs:// for logs and datasets"]
    T --> RUN["inspect eval pkg/task<br/>--solver pkg/solver<br/>inspect score --scorer pkg/scorer"]
    M --> RUN
    HK --> RUN
Extension point Decorator or mechanism What it adds Covered in
Components @task, @solver, @scorer, @tool in a package Shareable evals and building blocks, addressed as package/name 10.2 here; 10B.9, 8.8
Model providers @modelapi on a function returning a ModelAPI subclass A new --model provider/name 10.3 here; 10B.12 for running a keyless provider
Hooks @hooks on a Hooks subclass Code at run, task, sample and model-call events: tracking, monitoring, request rewriting, key management 10.5 to 10.8
Approvers @approver Custom policies for approving tool calls 10B.15
Sandboxes @sandboxenv on a SandboxEnvironment subclass A new place to run untrusted code 10B.15
Filesystems An fsspec implementation under the fsspec.specs entry point A new URI scheme for logs, datasets and templates 10.9
Scanners Inspect Scout Transcript analysis 10B.16

10.2 The registry and entry points: a small package#

This is not the acme-evals package of 10B.9, 8.8: that lesson owns the basics of packaging tasks (the TOML, the registry module, the package/name rule), and this one repeats them only so the new parts (a provider and a hook, returned lazily from the registry module) make sense. The two use the same names, so keep them in separate project folders and environments.

The running example is acme-evals, a package a platform team might publish for every product team that evaluates support tooling. It ships a task and a scorer, a model provider and a tracking hook:

text
acme-evals/
├── pyproject.toml
└── src/acme_evals/
    ├── __init__.py          (empty)
    ├── _registry.py         everything Inspect should register
    ├── tasks.py             @task ticket_priority, @scorer priority_match
    ├── bridge.py            AcmeRulesAPI: the model provider
    └── tracking.py          JsonlTracker: the hook

The entry point tells Inspect which module to import at startup:

toml
[project]
name = "acme-evals"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["inspect-ai"]

# Inspect imports this module at startup, which registers everything it imports.
[project.entry-points.inspect_ai]
acme_evals = "acme_evals._registry"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

The registry module imports the components (importing a decorated object registers it) and declares the provider and the hook through small functions that return the class instead of importing it at the top:

python
# acme_evals/_registry.py: everything imported here is registered with Inspect (lesson 10B.13)
from inspect_ai.hooks import hooks
from inspect_ai.model import modelapi

from .tasks import priority_match, ticket_priority  # noqa: F401  (registration by import)


@modelapi(name="acme")
def acme_rules():
    from .bridge import AcmeRulesAPI    # imported only when an acme/... model is used
    return AcmeRulesAPI


@hooks(name="jsonl_tracker", description="Append sample scores to $ACME_TRACK_FILE")
def jsonl_tracker():
    from .tracking import JsonlTracker
    return JsonlTracker

That indirection is the docs' recommended pattern for providers and hooks: Inspect imports _registry.py in every process, so anything heavy (a provider SDK, a tracking client) should be imported only when its provider or hook is actually used. Inspect's own providers work this way, which is why uv add inspect-ai does not pull in every provider SDK.

The task and scorer are ordinary Inspect code; nothing in them knows it will be packaged:

python
# acme_evals/tasks.py: a task and a scorer, shipped in a package (lesson 10B.13)
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Target, accuracy, scorer, stderr
from inspect_ai.solver import TaskState, generate, system_message

TICKETS = [
    ("P01", "Dashboard shows a 500 error for the whole team since 9am.", "P1"),
    ("P02", "Please change the billing email on our account.", "P3"),
    ("P03", "The CSV export has been timing out all week.", "P2"),
    ("P04", "Someone logged in to my account from another country.", "P1"),
]


@scorer(metrics=[accuracy(), stderr()])
def priority_match():
    """C when the first P1/P2/P3 token in the reply equals the target."""
    async def score(state: TaskState, target: Target) -> Score:
        words = state.output.completion.replace(".", " ").split()
        found = next((w for w in words if w in {"P1", "P2", "P3"}), None)
        return Score(value=CORRECT if found == target.text else INCORRECT,
                     answer=found, explanation=f"reply: {state.output.completion!r}")
    return score


@task
def ticket_priority(system: str = "Reply with the ticket priority only: P1, P2 or P3."):
    return Task(
        dataset=[Sample(id=i, input=t, target=p, metadata={"team": "support"})
                 for i, t, p in TICKETS],
        solver=[system_message(system), generate()],
        scorer=priority_match(),
        version=1,
    )

Names. Components defined in an installed package are namespaced with the package name: acme_evals/ticket_priority, acme_evals/priority_match, and (10.7) the hook acme_evals/jsonl_tracker. Model providers are addressed by the name given to @modelapi: acme/<model>. Components in your own project folder keep their bare names or file.py@name.

10.3 A model provider that wraps any call_model function#

evalkit's whole model interface is CallModel = Callable[[str], str] (10A.1, Part 6): a string in, a string out. Teams accumulate such functions: a wrapper around an in-house gateway, a fine-tuned model behind a private endpoint, a rules engine the LLM is meant to replace. A ModelAPI subclass turns any of them into an Inspect model, so every task, solver, scorer and log in this track works with it unchanged. The bridge here wraps a keyword-rules "model" so it runs keyless; replace call_model with yours.

python
# acme_evals/bridge.py: run any `call_model(prompt) -> str` function as an Inspect model (lesson 10B.13)
"""The bridge from evalkit's world (a plain callable) to Inspect's (a model provider).

Here the callable is a keyword-rule "model" so the sample runs keyless; in a real
project it would be evalkit's call_model, an in-house HTTP endpoint, or a
fine-tuned model behind your own gateway.
"""
from typing import Any

from inspect_ai.model import ChatMessage, GenerateConfig, ModelAPI, ModelCall, ModelOutput
from inspect_ai.tool import ToolChoice, ToolInfo

RULES = {"rules-v1": [("500", "P1"), ("logged in", "P1"), ("timing out", "P2")]}


def call_model(prompt: str, version: str) -> str:
    """An evalkit-style CallModel: str in, str out."""
    for needle, label in RULES[version]:
        if needle in prompt:
            return label
    return "P3"


class AcmeRulesAPI(ModelAPI):
    def __init__(self, model_name: str, base_url: str | None = None,
                 api_key: str | None = None, config: GenerateConfig = GenerateConfig(),
                 **model_args: Any) -> None:
        super().__init__(model_name, base_url, api_key, [], config)
        self.suffix = str(model_args.get("suffix", ""))       # set with -M suffix=...

    async def generate(self, input: list[ChatMessage], tools: list[ToolInfo],
                       tool_choice: ToolChoice,
                       config: GenerateConfig) -> tuple[ModelOutput, ModelCall]:
        prompt = "\n".join(m.text for m in input)              # flatten the chat to one string
        text = call_model(prompt, self.model_name) + self.suffix
        call = ModelCall.create(request={"prompt": prompt, "version": self.model_name},
                                response={"text": text})
        return ModelOutput.from_content(model=self.model_name, content=text), call

The contract, piece by piece:

  • __init__ must call super().__init__(model_name, base_url, api_key, api_key_vars, config). model_name is everything after acme/ in the model string (rules-v1). api_key_vars lists the environment variables to read a key from (none here; a real gateway would name its key variable, and Inspect would pick it up from .env). Extra **model_args receive whatever the user passes with -M key=value, --model-config or model_args= (the suffix here, used in 10.4).
  • generate(input, tools, tool_choice, config) receives Inspect's provider-neutral messages, tool definitions and generation config, and returns a ModelOutput. This bridge flattens the conversation into one string, which is right for a str -> str function and wrong for a chat model; a chat endpoint should map Inspect's ChatMessage roles onto its own message format, and an endpoint with tools should map tools and return tool calls (10B.14).
  • Returning (ModelOutput, ModelCall) records the raw request and response in the transcript's model event (4.3). ModelCall.create(request, response, filter=...) converts dicts, dataclasses or Pydantic models to JSON, and the optional filter(key, value) lets you redact before anything is stored (the docs' example replaces base64 image data with a placeholder; redact credentials and personal data the same way). Pass response=None when the call failed before a response.
  • ModelOutput.from_content(model, content) builds a plain text output. For real endpoints, also fill usage so token accounting works, and set a stop reason.

The optional overrides adapt Inspect's machinery to your endpoint:

Override Default Override it to
should_retry(ex) False Retry your gateway's rate-limit and transient errors with Inspect's backoff
connection_key() "default" Scope max_connections per account or key, so two keys get separate limits
max_connections() Built-in default Set a sensible concurrency for your endpoint
max_tokens() None Supply a default max_tokens
is_auth_failure(ex), refresh_credentials() False; close and re-initialize Refresh expiring tokens during long runs
collapse_user_messages(), collapse_assistant_messages() False Merge consecutive messages for endpoints that require alternation
tools_required(), tool_result_images() False Declare tool-format requirements

There are more for token counting (count_text_tokens(), count_media_tokens(), tokenize()), reasoning history and provider-side compaction; the ModelAPI source is the reference for those. If your provider makes its own HTTP calls, record_response_headers(response.headers) lets Inspect read headers set by a proxy in front of the model.

10.4 Running the package from the CLI and from Python#

Install the package into the project (uv add --editable ./acme-evals), and its names resolve everywhere, with no import in your code. The tracking hook is enabled by an environment variable (10.5). Three runs: one with tracking on, then the two INSPECT_REQUIRED_HOOKS cases of 10.7:

bash
uv add --editable ./acme-evals
ACME_TRACK_FILE=track.jsonl uv run inspect eval acme_evals/ticket_priority --model acme/rules-v1 --log-dir logs-ext --display plain
cat track.jsonl
INSPECT_REQUIRED_HOOKS=acme_evals/jsonl_tracker uv run inspect eval acme_evals/ticket_priority --model acme/rules-v1 --log-dir logs-ext --display none
INSPECT_REQUIRED_HOOKS=jsonl_tracker uv run inspect eval acme_evals/ticket_priority --model acme/rules-v1 --log-dir logs-ext --display none

The capture below echoed each command (as $ ...) and printed its exit code with echo "exit $?"; trailing spaces from the progress display were removed.

Output49 lines
$ ACME_TRACK_FILE=track.jsonl inspect eval acme_evals/ticket_priority --model acme/rules-v1 --log-dir logs-ext --display plain
inspect_ai v0.3.292
- hooks enabled: 1
  acme_evals/jsonl_tracker: Append sample scores to $ACME_TRACK_FILE

Monitor from another shell: inspect ctl task list   (inspect ctl --help)
Running 1 tasks...
---------------------------------------------------------
ticket_priority (4 samples): acme/rules-v1
dataset: (samples)
---------------------------------------------------------

generate     | Steps:   4/4 100% | Samples:   4/  4 | accuracy:  n/a | acme:  0/20 | HTTP retries: 0

---------------------------------------------------------
ticket_priority (4 samples): acme/rules-v1
dataset: (samples)

total time:                                   0:00:00
priority_match
accuracy        1.000
stderr          0.000
Log:
logs-ext/2026-11-24T18-02-06-00-00_ticket-priority_My85ZpnDrYw5btSAhWNGDN.eval
---------------------------------------------------------

exit 0
$ cat track.jsonl
{"event": "run_start", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "tasks": ["acme_evals/ticket_priority"]}
{"event": "sample", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "id": "P01", "epoch": 1, "scores": {"priority_match": "C"}}
{"event": "sample", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "id": "P02", "epoch": 1, "scores": {"priority_match": "C"}}
{"event": "sample", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "id": "P03", "epoch": 1, "scores": {"priority_match": "C"}}
{"event": "sample", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "id": "P04", "epoch": 1, "scores": {"priority_match": "C"}}
{"event": "task_end", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "status": "success", "model": "acme/rules-v1", "metrics": {"priority_match/accuracy": 1.0, "priority_match/stderr": 0.0}}
{"event": "run_end", "run_id": "gz7awxoxUtRb6K3t7rxjvt", "logs": 1, "exception": "None"}
$ INSPECT_REQUIRED_HOOKS=acme_evals/jsonl_tracker inspect eval ...
inspect_ai v0.3.292
- hooks enabled: 0


exit 0
$ INSPECT_REQUIRED_HOOKS=jsonl_tracker inspect eval ...

Required hook(s) missing: {'jsonl_tracker'}.
INSPECT_REQUIRED_HOOKS is set to 'jsonl_tracker'.
Installed hooks: {'acme_evals/jsonl_tracker'}.
Please ensure required hooks are installed in your virtual environment.

exit 1

Read the first block from the top: Inspect printed its version and the hooks banner (one hook enabled, with its description), which it prints whenever any hook is registered (from an installed package or a script), enabled or not; the task ran as acme_evals/ticket_priority against acme/rules-v1, with the acme connection counter in the progress line. The JSONL lines are the hook's output (10.5). The last two runs are 10.7's subject.

The same from Python, with model and task arguments:

python
# l11_packaged.py: use the installed acme_evals package from Python (lesson 10B.13)
from inspect_ai import eval
from inspect_ai.event import ModelEvent

# No import of acme_evals: the entry point registers it, and names resolve.
log = eval("acme_evals/ticket_priority", model="acme/rules-v1",
           model_args={"suffix": " (rules engine)"},      # reaches AcmeRulesAPI.__init__ as **model_args
           task_args={"system": "Priority only."},
           log_dir="logs-ext", display="none")[0]
print("task:", log.eval.task, "| registry name:", log.eval.task_registry_name)
print("model:", log.eval.model, "| model_args:", log.eval.model_args, "| task_args:", log.eval.task_args)
print("scorers:", [s.name for s in log.eval.scorers], "| accuracy:",
      log.results.scores[0].metrics["accuracy"].value)

sample = next(s for s in log.samples if s.id == "P03")
event = next(e for e in sample.events if isinstance(e, ModelEvent))
print("P03 output:", sample.output.completion)
print("raw call recorded:", event.call.request["version"], "|", event.call.response)
Output9 lines
inspect_ai v0.3.292
- hooks enabled: 0


task: acme_evals/ticket_priority | registry name: acme_evals/ticket_priority
model: acme/rules-v1 | model_args: {'suffix': ' (rules engine)'} | task_args: {'system': 'Priority only.'}
scorers: ['priority_match'] | accuracy: 1.0
P03 output: P2 (rules engine)
raw call recorded: rules-v1 | {'text': 'P2 (rules engine)'}

model_args reached the provider (the reply carries the suffix) and were recorded in eval.model_args; the task argument changed the system message and was recorded in eval.task_args; and the model event holds the raw call the bridge recorded. The banner appears again because the hook is installed, even though it is disabled in this run (hooks enabled: 0): its presence tells you which extensions were loaded, which is useful when a colleague's numbers differ from yours.

10.5 Hooks: code that runs at every lifecycle event#

A hook is a Hooks subclass whose async methods Inspect calls at lifecycle events. Each method receives one frozen data object and returns None:

Level Method Called Data includes
Eval set on_eval_set_start, on_eval_set_end Around an eval_set() eval_set_id (stable across re-invocations on the same directory)
Run on_run_start, on_run_end Around one eval() or eval_retry() call run_id, task_names; at the end logs and exception
Task on_task_start, on_task_end Around each task execution, including each retry attempt spec (EvalSpec) and plan at the start; the final log at the end
Sample on_sample_init, on_sample_start Once per sample and epoch, before and as it starts sample_id (the uuid of the sample execution, not the dataset id)
Attempt on_sample_attempt_start, on_sample_attempt_end Every attempt, including retries attempt (1-based); at the end error and will_retry
Events on_sample_event Every transcript event as it is logged The event; fires many times per sample
Scoring on_sample_scoring After the solver, before scoring
Sample end on_sample_end Once per sample and epoch The full EvalSample (or a reduced one, see needs_full_sample())
Model on_before_model_generate Before every model call, once per retry attempt input, tools, config: mutable, and changes affect the cache key and the call (10.8)
Model on_model_usage, on_model_cache_usage, on_model_retry After a call that missed / hit the local cache; before a retry backoff usage, call_duration, retries; the retry cause (exception_type, status_code) and wait_time

Plus three non-event methods: enabled() (consulted before every call, so keep it cheap, and keep its answer stable during a sample: Inspect uses it, with needs_full_sample(), to decide whether to rebuild the full sample for on_sample_end; read the environment once, not per call), needs_full_sample() (return False if on_sample_end needs only scores and summary fields, which saves rebuilding long histories) and override_api_key() (10.8).

acme_evals/tracking.py is a complete experiment-tracking hook that writes to a JSONL file instead of a tracking server, following 10A.8, 7.2's "files first, platforms second":

python
# acme_evals/tracking.py: a hook that appends one JSON line per finished sample (lesson 10B.13)
import json
import os

from inspect_ai.hooks import Hooks, RunEnd, RunStart, SampleEnd, TaskEnd


class JsonlTracker(Hooks):
    """Experiment tracking without a tracking server: a JSONL file per project."""

    def enabled(self) -> bool:                       # consulted before every call: keep it cheap
        return "ACME_TRACK_FILE" in os.environ

    def needs_full_sample(self) -> bool:             # scores and usage are enough
        return False

    async def on_run_start(self, data: RunStart) -> None:
        self._write({"event": "run_start", "run_id": data.run_id, "tasks": data.task_names})

    async def on_sample_end(self, data: SampleEnd) -> None:
        s = data.sample
        self._write({"event": "sample", "run_id": data.run_id, "id": s.id, "epoch": s.epoch,
                     "scores": {k: v.value for k, v in (s.scores or {}).items()}})

    async def on_task_end(self, data: TaskEnd) -> None:
        log = data.log
        metrics = {f"{sc.name}/{m.name}": m.value
                   for sc in (log.results.scores if log.results else []) for m in sc.metrics.values()}
        self._write({"event": "task_end", "run_id": data.run_id, "status": log.status,
                     "model": log.eval.model, "metrics": metrics})

    async def on_run_end(self, data: RunEnd) -> None:
        self._write({"event": "run_end", "run_id": data.run_id,
                     "logs": len(data.logs or []), "exception": repr(data.exception)})

    def _write(self, record: dict) -> None:
        with open(os.environ["ACME_TRACK_FILE"], "a") as f:
            f.write(json.dumps(record) + "\n")

Its output is in 10.4: a run_start record, one sample record per sample with its scores, a task_end record with the status and every metric, and a run_end record. Swap _write() for MLflow, Weights & Biases or your warehouse and you have automatic tracking for every Inspect run on every machine that installs the package; the official examples for Weights & Biases Weave and MLflow are linked from the hooks page.

The rules hooks must follow (docs, hooks page and reference):

  • One instance per process. @hooks instantiates the class once and reuses it for every eval set, run, task, sample and epoch, with calls for concurrent samples interleaving at every await. Keep per-sample state in a dict keyed by data.sample_id and delete it in on_sample_end, or it grows for the life of the process. Do not create event-loop-bound resources (async clients) in __init__; create them in on_run_start. There is no teardown event: clean up in on_run_end or on_eval_set_end.
  • Do not mutate the data you receive. The event classes are frozen, but the objects inside them (the sample, the events) are the ones Inspect writes to the log. Read and deep-copy; the only supported mutation is of the inputs in on_before_model_generate.
  • Hook exceptions do not fail the run. They are caught and logged as warnings (except LimitExceededError, which propagates so a hook can enforce a limit). That makes a broken tracking hook silent: test it, and check the warnings.
  • Keep hooks fast. They run inside the eval, concurrently with samples; a slow network call in on_sample_event slows every sample. Buffer and flush in on_task_end when you can.

10.6 Hooks in a script: watching retries and usage#

A hook does not need a package: decorating a class with @hooks in a script registers it for that process. This one watches the flaky v3 provider with one retry allowed and errors tolerated:

python
# l12_hooks_inline.py: hooks defined in a script, watching attempts, errors and usage (lesson 10B.13)
from collections import Counter

from inspect_ai import eval
from inspect_ai.hooks import (Hooks, ModelUsageData, SampleAttemptEnd, SampleEnd, TaskEnd,
                              hooks)

from lab_models import model_v3
from triage import triage

seen: Counter = Counter()


@hooks(name="run_monitor", description="Count attempts, retries, errors and tokens")
class RunMonitor(Hooks):
    def needs_full_sample(self) -> bool:
        return False

    async def on_sample_attempt_end(self, data: SampleAttemptEnd) -> None:
        seen["attempts"] += 1
        if data.error is not None:
            seen[f"failed attempt {data.attempt} (will_retry={data.will_retry})"] += 1

    async def on_model_usage(self, data: ModelUsageData) -> None:
        seen["model calls"] += 1
        seen["tokens"] += data.usage.total_tokens

    async def on_sample_end(self, data: SampleEnd) -> None:
        seen["samples ended"] += 1
        if data.sample.error is not None:
            seen["samples ended in error"] += 1

    async def on_task_end(self, data: TaskEnd) -> None:
        print("task end:", data.log.status, "| scored:",
              data.log.results.scores[0].scored_samples if data.log.results else None)


# The flaky provider of the lab: T09 always fails. Retry once, and keep going on errors.
log = eval(triage(), model=model_v3(), retry_on_error=1, fail_on_error=False,
           log_dir="logs-hooks", display="none")[0]
for key, value in sorted(seen.items()):
    print(f"{key:40} {value}")
Output12 lines
inspect_ai v0.3.292
- hooks enabled: 1
  run_monitor: Count attempts, retries, errors and tokens

task end: success | scored: 11
attempts                                 13
failed attempt 1 (will_retry=True)       1
failed attempt 2 (will_retry=False)      1
model calls                              11
samples ended                            12
samples ended in error                   1
tokens                                   4011

The hook saw what the results panel does not show: 13 attempts for 12 samples (T09 was tried twice: the first failure had will_retry=True, the second False), 11 model calls that completed, and one sample that ended in error. And on_task_end reports the uncomfortable part: the task status is success with 11 scored samples, because fail_on_error=False let the run finish without T09. A run table that shows only status and accuracy would call this a clean run. A monitoring hook like this one, or the coverage column of 9.2, is how you notice. (The on_model_usage counter counts only calls that returned; the failed attempts raised before any usage was recorded.)

10.7 Requiring hooks, and turning them off#

Two controls decide whether a hook runs:

  • enabled() turns an installed hook off in environments where it does not apply. JsonlTracker is enabled only when ACME_TRACK_FILE is set; in 10.4's second and third runs it was not, and the banner said hooks enabled: 0. The docs' Weights & Biases example enables itself only when WANDB_API_KEY is set. A hook that received on_task_start always gets the matching on_task_end, even if enabled() turns False in between.
  • INSPECT_REQUIRED_HOOKS makes startup fail unless the named hooks are installed. Set it in a shared environment or CI image to guarantee that nobody runs evals without, say, the audit or tracking hook. 10.4's last two runs show the two details the docs do not spell out: the name must be the package-qualified registry name (acme_evals/jsonl_tracker passed; the bare jsonl_tracker failed with Required hook(s) missing and exit code 1), and the check is about installation, not enablement (the first of the two runs passed with hooks enabled: 0). If the requirement is "tracking must actually happen", also require the variable that enables the hook, or make the hook's enabled() return True in CI.

10.8 Rewriting requests and API keys (illustrative)#

Two hook methods change what Inspect does, not just observe it, and deserve care:

python
# key_and_request_hooks.py: two hooks that change behaviour (lesson 10B.13; illustrative: fetch_secret() is a stub, EvalMarker is run below)
import os

from inspect_ai.hooks import ApiKeyOverride, BeforeModelGenerate, Hooks, hooks


def fetch_secret(reference: str) -> str:
    """Resolve a secret-manager reference to the key (your secret manager's SDK goes here)."""
    raise NotImplementedError


@hooks(name="secret_keys", description="Resolve API keys from the secret manager")
class SecretKeys(Hooks):
    def override_api_key(self, data: ApiKeyOverride) -> str | None:
        # Called at model initialization and after authentication failures.
        if data.value.startswith("secret://"):          # .env holds a reference, not the key
            return fetch_secret(data.value)
        return None                                     # None: keep the original value


@hooks(name="eval_marker", description="Tag every request as evaluation traffic")
class EvalMarker(Hooks):
    def enabled(self) -> bool:
        return os.environ.get("ACME_MARK_EVAL_TRAFFIC") == "1"

    async def on_before_model_generate(self, data: BeforeModelGenerate) -> None:
        # Mutating data.input, data.tools or data.config changes the real call AND the cache key.
        data.config.extra_headers = {**(data.config.extra_headers or {}), "x-traffic": "eval"}
  • override_api_key() lets .env hold a reference instead of a secret, refreshes keys during long runs (it is called again on authentication failures), or supports a reverse proxy that holds the real keys. It is the cleanest answer to "no API keys in files".
  • on_before_model_generate() can rewrite inputs, tools and config on every call. Use it for operational changes (headers, routing) and be very wary of anything that changes what the model sees: a hook that edits prompts makes the log's plan a lie about what was sent. If you must, record what the hook did in the sample metadata or a log message, so the transcript stays honest. The check below runs EvalMarker keyless against the lab's v1 model and shows that the mutated config is what the model event records. (extra_headers is a GenerateConfig field; whether a provider forwards it depends on the provider, so check the models page for yours.)
python
# l18_marker.py: run EvalMarker against the lab's v1 model and read the model event (lesson 10B.13)
import os
os.environ["ACME_MARK_EVAL_TRAFFIC"] = "1"

from inspect_ai import eval
from inspect_ai.log import read_eval_log

import key_and_request_hooks  # noqa: F401  (registers the hooks)
from lab_models import model_v1
from triage import triage

log = eval(triage(), model=model_v1(), limit=1, log_dir="logs-marker", display="none")[0]
sample = read_eval_log(log.location).samples[0]
model_event = next(e for e in sample.events if e.event == "model")
print("extra_headers on the recorded model call:", model_event.config.extra_headers)
bash
uv run python l18_marker.py
Output6 lines
inspect_ai v0.3.292
- hooks enabled: 2
  secret_keys: Resolve API keys from the secret manager
  eval_marker: Tag every request as evaluation traffic

extra_headers on the recorded model call: {'x-traffic': 'eval'}

The banner shows both hooks registered (the secret_keys hook is inert here: no key starts with secret://), and the model event's config.extra_headers is the header the hook added.

  • Approvers (@approver) decide whether a model's tool call may run: approve, reject, modify, escalate to another approver or to a human. Packaged approvers are referenced by package/name in approval policy files. The concepts and policies are 10B.15's.
  • Sandbox environments (@sandboxenv on a SandboxEnvironment subclass) add new places to run model-written code (Inspect ships local and Docker; packages add Kubernetes, Modal, Proxmox, Daytona and others). 10B.15 covers them.
  • Filesystems. Logs, datasets and prompt templates are read and written through fsspec (resource(), csv_dataset(), json_dataset(), list_eval_logs(), read_eval_log(), write_eval_log(), retryable_eval_logs()). To store logs somewhere new, implement the subset of the fsspec API Inspect uses (sep, open(), makedirs(), info(), created(), exists(), ls(), walk(), unstrip_protocol(), invalidate_cache()) and register it under the fsspec.specs entry point (not inspect_ai): myfs = "evaltools:MyFs". An optional _pinned_range_reader() lets Inspect stream large log members in 8 MiB pieces from a single version of the file.
  • The extensions gallery at inspect.aisi.org.uk/extensions lists community and official packages: sandboxes, tracking integrations (Weights & Biases, MLflow), transcript analysis (Docent), judge calibration and drift tools, export formats. Listed is not the same as endorsed; read a package's code before you install it into an environment that holds keys, because entry points mean installed packages run code at Inspect startup.

10.10 Choosing an extension point#

You want to Use Not
Share tasks, scorers or solvers across teams A package with components and an entry point Copying task files between repos
Evaluate an in-house or fine-tuned model, or wrap evalkit's call_model @modelapi provider A scripted mockllm (not reproducible from the log or CLI)
Send every run to a tracking system A hook (on_task_end, on_sample_end) shipped in a package, required with INSPECT_REQUIRED_HOOKS A wrapper script people may forget to use
Post-hoc analysis of existing logs The log API and dataframes (Parts 5, 8, 9) A hook (it only sees runs that happen after it is installed)
Watch retries, rate limits and cost live A hook on on_model_retry, on_model_usage, on_sample_attempt_end Reading logs after the fact (retries leave less trace there)
Resolve API keys from a secret manager override_api_key() Writing keys into .env on CI machines
Add headers or route requests on_before_model_generate() (operational changes only) Editing prompts in a hook
Store logs in a new backend An fsspec filesystem Post-run copy scripts that lose live viewing
Control tool execution Approvers (10B.15) Checks inside each tool

Part 11: Methodology: defending a number that came out of a log#

Deep-dive

11.1 A checklist before you quote a number from Inspect logs#

  1. Name the log. The exact file (or bundle link) every number came from, in the report, next to the number.
  2. Status is success, not "not error" (cancelled and started runs exist). For failed runs, report the failure and its cause, not partial metrics.
  3. Coverage: completed_samples of total_samples, and scored_samples with unscored_samples per scorer. Errored samples with fail_on_error=False leave the denominator silently (10.6 showed a "successful" run with 11 of 12 scored).
  4. Comparability of every pair you compare: task and task version, sample ids and content fingerprint, epochs and reducers, scorers, solver plan and prompt, limits and selection (9.1, 9.6).
  5. Provenance: revision.commit with dirty=False, the Inspect version, your lock file; dated model ids where available (3.10).
  6. Per-sample evidence: which samples changed between runs, which are flaky across epochs, and the transcripts of the ones that drive the decision (9.3).
  7. Slices with their sizes, decided before the run for anything that gates (10B.10, 8.6).
  8. Paired statistics on the reduced values for any "better or worse" claim (10B.10, 8.3).
  9. Edits on the record: any edited, excluded or zeroed sample is counted and explained from history, reason and provenance (Part 6); any tag or metadata change appears in log_updates.
  10. Extensions declared: which hooks and providers were loaded (the banner, eval.model, eval.model_args), and whether any hook rewrote requests (10.8).
Symptom Cause Fix
Analysis script crashes on log.results.scores A failed run's results is None Check status == "success" first; report failures separately (3.9)
The "latest" log is a colleague's run list_eval_logs()[0] in a shared directory Select logs by header fields with filter= (5.2)
Dashboard fails to parse a log NaN in the JSON Export from Python with NaN → null, or JSON5 (2.3)
Converted directory counted twice .eval and .json copies listed together formats=["eval"], separate output directory (2.2)
Mean over samples_df() disagrees with the results panel One row per epoch; raw C/I strings; NaN treated as 0 Reduce per id with the task's reducer; score_to_float(); keep NaN out (8.3)
Join of two runs gives an empty or wrong frame Joined on sample_id Join on id and epoch (8.3)
messages_df(filter=["assistant"]) returns user messages too A list filter is ignored in 0.3.292 A callable: filter=lambda m: m.role == "assistant" (8.4)
Score columns renamed after adding a reducer Going from one reducer to several: score_<scorer>_<metric> becomes score_<scorer>_<reducer>_<metric>. Swapping one reducer for another changes nothing Select by prefix or read EvalScores (8.2)
Model event input is attachment://... Content de-duplicated into attachments resolve_sample_attachments() per sample (4.4)
Streaming a failed log raises RuntimeError read_eval_log_samples() guards incomplete logs all_samples_required=False only in error-analysis code (5.4)
Re-scoring needs data that is not there Run with log_samples=False Keep samples for anything you may act on (2.4)
A quoted number changed after "just adding a tag" The log was rewritten in place, or a score edit slipped in Edit copies; audit log_updates and score history (6.1, 6.2)
Zeroing refused Integer ids, sample not in the empty attempt, unscored verdicts String ids; run the empty attempt with the same settings and samples (6.4)
Published bundle reveals the repository URL eval.revision in every log Scrub a copy and verify by search (7.5)
Bundle "does not load" when tested locally python -m http.server lacks range requests Test with a server that supports them (7.4)
Reviewer clicks a deceptive link in model output Rich rendering of untrusted content ViewerConfig(trust_content=False) (7.2)
Tracking hook silently records nothing enabled() is False, or the hook raises and Inspect logs a warning Check the banner's hooks enabled count and the warnings; test the hook (10.5)
INSPECT_REQUIRED_HOOKS fails although the package is installed Bare hook name Use the package-qualified name (10.7)
A run cannot be reproduced from its log A Python object (scripted model) passed at run time A registered @modelapi provider (10.3)
Per-sample state in a hook grows without bound One hook instance per process Key by sample_id, delete in on_sample_end (10.5)

11.3 Decision table#

Question Use
One run's results for a report read_eval_log(header_only=True) or evals_df()
Many runs side by side evals_df() over a filtered list_eval_logs()
Which samples failed, by slice samples_df() with metadata columns, reduced per id
Why one sample failed read_eval_log_sample() or Inspect View with a task view sorted worst first
Process questions (latency, retries, tools) events_df() with EventTiming + ModelEventColumns / ToolEventColumns, or a hook
Is B better than A? Comparability check, then log.reductions into 10B.10, Part 8
A run record for tracking manifest_from_log() (9.6), or a tracking hook
A non-Python consumer inspect log dump, or a Python export step that handles NaN
Sharing with people outside the team A scrubbed copy, bundled, on an access-controlled host
Sharing within the team A shared log directory (bucket) with --log-shared for live runs, and task views
Plots Inspect Viz over the dataframes (9.8)
Transcript analysis at scale Inspect Scout (10B.16)

Part 12: evalkit ↔ Inspect for logs, analysis and extension#

Deep-dive

12.1 The mapping#

evalkit Inspect What differs
EvalReport.to_jsonl() rows, save_run()'s results.jsonl (10A.8, Part 4) The .eval log's samples and reductions The log holds full transcripts and events, not just rows
run.json manifest (10A.8, 7.1) The log header (EvalSpec, EvalPlan, EvalResults, EvalStats) No dataset content fingerprint or prompt hash: compute them (9.6)
load_run() read_eval_log(), read_eval_log_sample_summaries() A cost ladder of partial reads (Part 5)
runs/index.jsonl catalogue list_eval_logs() with filter=, inspect log list --json Filters run on headers
EvalReport.per_example(), failing_examples() samples_df() filtered on score columns; the summaries; Inspect View One row per epoch; reduce yourself
slice_breakdown() samples_df() metadata_* columns + groupby, or the in-run grouped() metric Slice after the fact by any metadata
report.py render_report() (10A.10, 7.1) Inspect View, bundles, task views; your own report from the dataframes The viewer is interactive; a written report is still yours
Run comparison in compare.py None built in Comparability check plus 10A.8's statistics on reductions
CallModel callable A @modelapi provider (10.3) Registered, reproducible from the log and usable from the CLI
Experiment tracking by files (10A.8, Part 7) Logs themselves, plus hooks that push to a tracker Hooks see every run automatically
Shared code as files in a repo Packages with inspect_ai entry points Names like package/task resolve everywhere
Manual annotations in a spreadsheet edit_eval_log() tags and metadata, edit_score(), exclusion and zeroing with provenance The audit trail lives in the log

12.2 What 10A.10 now gets wrong, for this lesson's scope#

Checked against inspect-ai 0.3.292 on 24 November 2026 (the full list across the track is in 10B.8, 8.3):

10A.10 says As of 0.3.292
Report: ".eval log + inspect view" Add the log API (Part 5) and the dataframes (evals_df(), samples_df(), messages_df(), events_df()), which need pandas and pyarrow installed separately
Slices are "dataset metadata columns" Metadata becomes metadata_* columns in samples_df(), which you group yourself, or you declare a grouped() metric; metadata alone slices nothing
"Inspect gives you per-sample transcripts, token/cost accounting" Transcripts and tokens yes; total_cost only with model prices configured (3.6)
Setup note: "a plain install may give you a newer release" Still true; add that inspect_ai.analysis needs pandas and pyarrow and that installed extension packages run code at startup (10.9)

Part 13: Older code and tutorials#

Reference
You may see Replaced by, and when
from inspect_ai.analysis.beta import evals_df, samples_df from inspect_ai.analysis import ...; the analysis functions left beta in 0.3.119 (August 2025) and inspect_ai.analysis.beta is deprecated
.json logs as the default, --log-format json everywhere .eval is the default since 0.3.46; convert old logs with inspect log convert --to eval
Large logs from before 0.3.206 Message de-duplication and zstd compression arrived in 0.3.206; converting re-writes old logs in the new form. Inspect Scout needs 0.4.22 or later to read the condensed format
Old logs missing metadata, model_usage, total_time, working_time or retries in summaries and samples_df() Added to summaries in 0.3.93 (May 2025); round-trip old logs through inspect log convert to add them
Hooks whose on_sample_end reads only summary fields Since 0.3.113 on_sample_end receives the full EvalSample; implement needs_full_sample() returning False if you only need summary fields
Tag and metadata changes made by rewriting log.eval.tags and writing the log edit_eval_log() with TagsEdit, MetadataEdit and ProvenanceData (0.3.195), which keeps an audit trail
evals_df() score columns always named score_<scorer>_<metric> Since 0.3.221 the reducer appears in the column name when a task has several reducers
Reading many samples one at a time in a loop read_eval_log_samples_by_id() (0.3.242) reads a batch concurrently; exclude_fields (0.3.241) skips heavy fields
exclude_samples() / zero_samples() returning a result object They return None as of 0.3.292 (10B.11, Part 14)

When a tutorial's log code fails on your version, the CHANGELOG entries tagged "Eval Log", "Analysis" and "Hooks" are where the change will be; read the Breaking Changes section of every release between the tutorial's version and yours.


Common misconceptions#

Misconception Reality
"The log is a debug artefact; the metrics are the result." The log is the result: configuration, transcripts, scores and provenance. Metrics are one derived view of it, and re-scoring, slicing and auditing all need the rest.
"A .eval file is just zipped JSON I can parse myself." It is zstd-compressed, de-duplicated into attachments, and its layout changes between releases. Use the log API or inspect log dump.
".json logs are more portable." They are larger, slower and still contain NaN, which strict JSON parsers reject. Convert or export deliberately.
"A failed run has no useful data." Its log usually holds most samples, the error and the traceback; only results is missing.
"status != 'error' means the run is good." cancelled and started exist, and a success run with fail_on_error=False can have unscored or errored samples. Check status and coverage.
"The same sample ids mean the same dataset." Ids say nothing about content. Bump task_version on data changes and fingerprint content.
"samples_df() gives one row per sample." One row per sample per epoch, with raw score values. Reduce per id first.
"sample_id is the dataset id." sample_id is a generated global id; the dataset id is id.
"messages_df(filter=['assistant']) keeps assistant messages." In 0.3.292 a list is silently ignored; pass a callable.
"Editing tags or metadata changes the run's configuration." Current values change; the eval-time originals stay in eval.tags and eval.metadata, and every change is in log_updates.
"Excluding a contaminated sample is the honest fix." Exclusion removes it from the denominator and raises the metric; zeroing keeps it as a failure. Choose deliberately and record why.
"Publishing a bundle only shares the scores." It shares every prompt, input, output, the git remote and more. Scrub a copy, verify, then publish.
"Hooks are for plugins other people write." A twenty-line hook gives you automatic experiment tracking and live run monitoring for every run on every machine.
"A hook that fails will stop the eval, so I will notice." Hook exceptions are caught and logged as warnings; a broken tracking hook fails silently.
"Scripted mocks and custom providers are the same." A scripted mockllm is a Python object the log cannot rebuild; a @modelapi provider is a name the CLI, run configs and eval sets can use.

Key takeaways#

  • Logs are the product. Every decision about an Inspect run is read out of its log, so the analysis loop is: logs in a directory you govern, read by code and viewed by people, checked for comparability and coverage, analysed per sample, tested with paired statistics, and annotated back with provenance.
  • .eval is the format (zip, zstd, de-duplicated attachments, partial reads; 5.3 times smaller than .json even on a tiny log). Convert with an output directory, never parse the files yourself, and handle NaN before any strict JSON consumer sees it.
  • Logging options are trade-offs: log_samples=False keeps metrics and loses everything you analyse with; image, model-API, refusal, buffer, shared and transcript-level options tune size, debuggability and live viewing. Logs can live on any fsspec store, which makes them a data store with your customers' data in it.
  • The schema answers "what exactly ran?": EvalSpec (task, version, plan, model, config, dataset ids, git revision, Inspect version), EvalResults (one EvalScore per scorer and reducer, reducer=None for the default), EvalStats, samples with scores, errors and edit histories, and reductions. A failed run has results=None but keeps its samples and traceback.
  • What a log cannot pin: model sampling, aliases, built-in grader prompts across Inspect versions, remote datasets, your other packages, uncommitted code. Pin what you can (lock file, dated model ids, clean tree) and fingerprint the data.
  • Events are the transcript: spans attribute everything to a solver or scorer; model events hold provider-neutral input and the raw provider call; state events are JSON-patch diffs; large content sits in attachments.
  • Read the least you need: headers and reductions, then summaries, then single samples or batches by id, and stream only when you must. list_eval_logs(filter=...) selects logs by header fields; never pick "the newest file" in a shared directory.
  • Edit on the record: write copies, use edit_eval_log() for tags and metadata, the score-editing family for verdicts, and the empty-attempt workflow with zero_samples() to count a sample as a failure. Only trust_log, eval-retry and inspect score run code a log names.
  • Share safely: task views ship the review layout, trust_content=False protects reviewers from model-controlled content, the viewer must never be exposed without authentication, and published bundles come from scrubbed, verified copies.
  • Dataframes turn logs into tables: evals_df per log, samples_df per sample-epoch (join on id and epoch), messages_df and events_df for process questions, column groups and custom columns for the rest, prepare() for conversions and viewer links, and DuckDB for SQL.
  • Analyse in order: comparability, coverage, slices with sizes, per-sample changes and flakiness, failures, then statistics with 10B.10's paired tools. v2's higher mean hid a deterministic regression and a flaky answer.
  • Extend through one entry point: a package's _registry.py registers tasks, scorers, @modelapi providers (the right way to wrap evalkit's call_model or an in-house endpoint) and @hooks (automatic tracking and monitoring; INSPECT_REQUIRED_HOOKS with package-qualified names); approvers, sandboxes and filesystems plug in the same way.

Terms introduced in this lesson#

Term One-line definition
.eval log Inspect's default log format: a zip archive of zstd-compressed JSON members (header, summaries, reductions, one file per sample and epoch)
EvalLog The Python object for a whole log: status, eval, plan, results, stats, error, samples, reductions, tags, metadata and edit history
EvalSpec The part of a log that says what ran: task, version, model, configuration, dataset ids, revision and packages
EvalSample One sample's record for one epoch: input, target, messages, output, scores, events, usage, errors
Reductions (Inspect) The per-sample values after epoch reduction, from which metrics are computed; stored with the log header
Event (Inspect) One entry in a sample's transcript (span, model call, tool call, state change, score, error, log message)
Span (Inspect) A begin/end pair of events that groups everything one solver, scorer, tool or step produced
Attachment (Inspect) Large or repeated content stored once in a sample and referenced as attachment://<hash>
ModelCall The raw provider request and response recorded in a model event
Sample summary A thin per-sample record (ids, scores' values, metadata scalars, usage, errors) read without loading transcripts
log_updates The append-only list of post-run tag and metadata edits in a log, each with provenance
Provenance (Inspect) ProvenanceData(author, reason, timestamp) attached to log and score edits
Zeroing Counting a sample as a failure by copying the verdicts of an empty attempt into the log (zero_samples())
Empty attempt A run of a sample with the do-nothing empty_attempt() solver, scored by the task's own scorers
Task view A ViewerConfig stored with a task that sets the viewer's default sample columns, sort and score panel
Untrusted content (viewer) trust_content=False: the viewer shows model-controlled content as literal text and media as placeholders
Log dataframes evals_df, samples_df, messages_df, events_df: pandas tables extracted from logs by inspect_ai.analysis
Column group A predefined list of dataframe column definitions (for example SampleSummary, EvalModel) combined with +
Dataset fingerprint A hash of every sample's id, input and target, used to prove two runs saw identical data
Entry point (inspect_ai) Package metadata that makes Inspect import a module at startup, registering its components and extensions
@modelapi The decorator that registers a custom model provider class, usable as --model <name>/<model>
Hook (Inspect) A Hooks subclass registered with @hooks whose async methods run at run, task, sample and model-call events
INSPECT_REQUIRED_HOOKS An environment variable that makes Inspect fail at startup unless the named (package-qualified) hooks are installed
Inspect Viz Meridian Labs' companion package that plots Inspect log dataframes interactively

Exercises#

All exercises run keyless with the files from this lesson (and triage.py and fake_triage.py from 10B.8).

  1. The size of an agentic log (2.2). Change l01_make_lab.py to add a third epoch and a v4 model whose replies are ten times longer (repeat the summary). Predict whether the .json/.eval ratio goes up or down, then measure it with l02_formats.py.
  2. A comparability failure (9.1). Run v2 again with limit=6 into logs-lab. Which check in comparable() catches it? Add a check for eval.config.limit and eval.config.sample_id and explain why dataset.sample_ids may or may not catch it on its own.
  3. Content drift (9.6). Copy triage.py, change T06's target to P2|account, keep version=1, and run v1 against it into a new directory. Which of comparable() and dataset_fingerprint() notices? What should the author have done?
  4. The flaky ticket (9.3). Run v2 with epochs=Epochs(5, ["mean", "mode"]) (two reducers, 10B.10, 7.3). How do the evals_df() score column names change, and what do the two reductions say about T05?
  5. Error analysis by reason (8.6). Using SampleScores, count samples by score_triage_format_reason per model across the lab. Which model's format failures have which reason?
  6. A review workflow (6.2). Write review.py that tags every successful lab log whose labels mean is below 0.9 with needs_qa, records the reviewer and reason, and then lists logs still tagged needs_qa using only list_eval_logs(filter=...).
  7. Exclude versus zero (6.3, 6.4). On copies of the v2 log, exclude T06 in one and zero T06 in the other. Predict both new labels means before running, and say which you would use if T06's ticket text turned out to be ambiguous, and which if v2's prompt had contained T06's answer.
  8. Publish safely (7.5). Extend l07_publish.py so the scrub also removes task_file and replaces every sample's input with "[redacted]". Verify with a search for a phrase from T01. What does a reader of the bundle lose, and is it still useful?
  9. A cost hook (10.5). Add an on_model_usage method to JsonlTracker that accumulates tokens per model and writes them in task_end. Run the packaged task and check the totals against stats.model_usage in the log.
  10. Wrap your own callable (10.3). Replace call_model in bridge.py with 10A.1's FakeTriageModel logic (or any str -> str function you have), run the triage task with --model acme/<name>, and confirm with inspect log export-config that the run can be reproduced by name.
Hints and what you should see
  1. Longer replies grow both formats, but .eval compresses repeated text well, so the ratio usually rises. On single-turn logs there is no message de-duplication to gain from, so the effect is smaller than on agent logs.
  2. In 0.3.292 dataset.sample_ids records the six ids actually run, so the sample ids check catches it, and config.limit is 6. A check on limit and sample_id states the intent explicitly, gives a clearer message, and does not depend on how a future version records selected ids.
  3. Only the fingerprint notices: the ids, version, plan and scorers are identical. The author should have bumped version (10B.8, 4.5).
  4. With two reducers every column gains the reducer segment: score_triage_format_mean_accuracy, score_triage_format_mode_accuracy, score_triage_labels_mean_mean, score_triage_labels_mode_mean and their stderr twins (checked on 0.3.292). T05 alternates, so three of five epochs are right: its labels mean is 0.867 and its mode 1.0. The mode hides the flakiness completely, which is why reducers must be chosen on purpose.
  5. v1 and v3 each have two invalid_response_format rows (T11, both epochs); v2 has none. columns=EvalModel + SampleScores is what adds the model and _reason columns.
  6. filter=lambda log: "needs_qa" in log.tags reads current tags, so the logs you tagged appear and nothing else.
  7. Excluding T06 removes a 0.667 from the mean of 12 (labels mean rises to about 0.985); zeroing replaces it with 0.0 (falls to about 0.903). Ambiguous ticket: exclude (it measures nothing). Leaked answer: zero (the sample should count as a failure).
  8. The bundle keeps scores, explanations and outputs, but a reviewer can no longer see what the model was asked, so it is useful for metrics and audits of scoring, not for error analysis of inputs. Remember that outputs can quote inputs; search for phrases from inputs in the outputs too.
  9. The hook's totals match stats.model_usage for calls that completed; failed calls report no usage.
  10. export-config shows model: acme/<name> and any -M arguments, so the config re-runs the same provider, unlike the scripted mock in 10B.8, 6.5.

Check yourself#

  1. Name the four kinds of member in a .eval archive and say which one makes partial reads of samples cheap.
  2. Why does the .json/.eval size ratio grow for agent logs?
  3. A dashboard in JavaScript fails to parse a log exported with inspect log dump. What is the likely cause, and what are two fixes?
  4. What is in the log of a run that ended with status == "error", and what is missing?
  5. Name three things a log records that let you check two runs are comparable, and one comparability problem none of them can detect.
  6. What is reducer=None on an EvalScore, and how does it affect evals_df() column names?
  7. In a model event, what is the difference between input and call.request, and why is input sometimes an attachment:// string?
  8. Put these reads in order of cost and say when to use each: full read, summaries, header-only, single sample.
  9. What does read_eval_log_samples() do on a log whose status is error, and why?
  10. After edit_eval_log() adds a tag, where can you find the original tags, and where is the record of who changed them?
  11. When should you zero a sample rather than exclude it, and what does zeroing need first?
  12. Which operations on a log can run code the log names, and how do you protect yourself?
  13. In samples_df(), what is the difference between id and sample_id, and how many rows does a 12-sample, 3-epoch log produce?
  14. What does trust_content=False change, and where must it be set for a bundled viewer to honour it?
  15. A team sets INSPECT_REQUIRED_HOOKS=jsonl_tracker and every run fails at startup although the package is installed. Why, and what else should they check if the requirement is "tracking must happen"?

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):

Code and packages:

Within this course: 10A.8, Part 7 for experiment tracking without a platform, 10B.10, Part 8 for statistics on Inspect logs, 10B.11, Part 10 for score edits and exclusions in grader validation, 10B.12 for eval sets, retries and CI gates, 10B.16 for Inspect Scout and the ecosystem, 10B.17 for combining Inspect logs with DeepEval and evalkit, and 10B.18 for a reading plan through the official docs.


← 10B.12: Running Inspect Evals for Real: Models, Configuration, Concurrency, Caching, Errors and Eval Sets (optional) | Module 10B overview | 10B.14: Tools and Agents in Inspect: Custom Tools, MCP, react() and Multi-Agent Systems (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