10B.9 Inspect Datasets, Solvers and Task Configuration (optional)

ProductionLesson 9 of 1821,080 wordsOptional12 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

Lesson 10B.8 ran a first Inspect task and ported 10A.1's triage eval into it: a list of Samples, a prompt_template() solver and generate(), two scorers, a log. That is enough to see the shape. It is not enough to build an eval you can defend, because almost every number Inspect reports is decided before the scorer runs: by which samples were loaded, which ids they carry, what was shuffled and with which seed, which prompt text actually reached the model, which solver produced the answer and which configuration layer won when three of them disagreed. This lesson opens up those three parts of a task. Datasets: every Sample field and its default, every loader and its edge cases, field mapping, typed metadata, ids, filtering, shuffling, multiple-choice data and datasets that grow while the eval runs. Solvers: the protocol, TaskState, every built-in solver with the exact text it sends, the template rules (including two that silently corrupt prompts), writing your own solvers, the sample store, setup and cleanup. Task configuration: every Task parameter, task arguments, task_with(), the four override layers and which settings each one can reach, the configuration files, packaging and versioning. Every sample in the lesson ran on a laptop with no API key, using Inspect's mockllm/model provider and scripted outputs, and the real output is shown.

Versions (current at time of writing, verified 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT licence, Python 3.11 or newer), run here on Python 3.13. Inspect is still 0.x and ships a release every few days; releases that look minor can carry a "Breaking Changes" section in the changelog. When a name or a behaviour in this lesson does not match what you see, run python -c "import inspect_ai; print(inspect_ai.__version__)", then check the datasets, solvers and tasks pages and the installed source. Several facts below come from the installed source because the docs disagree with it; each one says so.

What you'll learn

  • What happens to one sample from the moment it is loaded to the moment it is logged, and which part of a task owns each step
  • Every Sample field and its default, including the empty-string target that makes text scorers pass anything, and the list target
  • How sample ids are assigned (at load time, at run time, or never), why positional ids silently point at different questions after a shuffle, and how to make ids stable
  • Metadata as slice axes and template variables, and typed metadata with a frozen Pydantic model
  • Chat-message inputs (system prompts, few-shot turns, prefilled assistant turns) and where multimodal inputs fit
  • Every loader: MemoryDataset, csv_dataset, json_dataset (JSON and JSON Lines), file_dataset, hf_dataset and example_dataset, with their encodings, delimiters, remote paths and failure messages
  • FieldSpec versus a record_to_sample function, one record becoming several samples, and what limit really counts in each loader
  • The csv_dataset name bug in 0.3.292 (an explicit name= does not fix it) and a workaround that does
  • Filtering, slicing, sorting and shuffling datasets; run-time selection with --limit, --sample-id (including globs) and --sample-shuffle; and why the CLI and Python spell ranges differently
  • Multiple-choice datasets, shuffle_choices, the exact prompts multiple_choice() sends, and how shuffled letters appear in the log
  • Datasets that grow while the task runs (SampleSource), and why accuracy over an adaptive dataset is not an accuracy
  • The Solver protocol, TaskState member by member, Generate and its tool-call modes
  • Every built-in solver (generate, system_message, user_message, assistant_message, prompt_template, chain_of_thought, multiple_choice, self_critique, chain, fork) with the text each one sends
  • The template rules: metadata, store and parameters (and which wins), file paths read as templates, unknown placeholders left in place, JSON braces rewritten into broken text, and a missing template file sent to the model as its own file name
  • Writing solvers: the factory pattern, the async rule, models and model roles inside solvers, early termination, the sample Store and StoreModel, setup and cleanup, and how to test a solver with a scripted model
  • Every Task parameter, @task attributes and task arguments (-T, --task-config), solver-agnostic tasks (--solver, -S), and task_with(), which mutates the task you pass it
  • The four configuration layers, which settings each layer can reach, the surprise that INSPECT_EVAL_* variables do not reach the Python eval() function, and the configuration files --generate-config, --run-config and inspect log export-config
  • Task identity (name, version, metadata, tags), packaging tasks as an installable Python package, and Hugging Face eval.yaml tasks
  • The methodology that makes the numbers defensible: control solvers, reading what was actually sent, elicitation fairness across models, and a failure gallery
  • How all of this maps onto the evalkit code of 10A.1 and 10A.2, and what lesson 10A.10 Part 4.4 needs corrected

What you don't need

  • An API key. Every sample runs keyless with mockllm/model and shows real output, except the Hugging Face loader, the multimodal input and the provider model strings, which are labelled illustrative.
  • Scoring depth. This lesson uses includes(), match(), choice() and one small custom scorer only as far as it must; how scorers, metrics, epochs and reducers work is 10B.10, and model-graded scoring is 10B.11.
  • Agents, tools and sandboxes. use_tools(), react(), the sample sandbox, files and setup fields are previewed and sent on to 10B.14 and 10B.15.
  • Running at scale (providers, concurrency, caching, errors, eval sets, CI gates). That is 10B.12.
  • Dataset design itself: what makes a good case, labelling, splits, sample sizes and contamination are 10A.2. This lesson maps those ideas onto Inspect and does not re-teach them.

Setup

Python 3.11 or newer and uv. If you followed 10B.8 you already have a project; otherwise create one (or follow lesson 03.1, Part 4):

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

pydantic is already a dependency of inspect-ai; it is listed because Part 2.5 and Part 7 import it directly. The Hugging Face loader in 3.7 also needs uv add datasets (illustrative here, because it downloads). Nothing in this lesson needs a .env file or a key. To try a sample against a real model later, put your key in .env as in 10B.8 and swap mockllm/model for a provider model string; 10B.12 covers providers.

Every sample was run from a working directory laid out like this (the files are printed where they are first used):

text
inspect-lab/
├── data/
│   ├── tickets.jsonl          # 8 support tickets (Part 2.3)
│   ├── qa.csv                 # 3 quiz questions (Part 2.4)
│   └── ...                    # small edge-case files, created in Part 3
├── prompts/
│   └── system.txt             # a template file (Part 6.2)
├── s01_samples.py ... s19_solver_patterns.py, test_solvers.py
├── cfg/                       # the configuration probes of Part 8
├── pkg/acme_evals/            # the packaging example of 8.8
└── triage/                    # the worked example of Part 9

Run each sample with uv run python <file>.py from the project directory. The outputs shown were produced with uv run --no-project --with inspect-ai python -I <file>.py in a scratch directory; the -I flag isolates the interpreter from stray modules in the current directory, so drop it for the two scripts that import a sibling file (cfg/env_py.py in 8.5 and triage/run_triage.py in Part 9). Inspect writes a log for every run into ./logs (the samples pass log_dir="logs" explicitly); inspect view opens them, as 10B.8 showed.


What you must be able to do after this lesson#

  • Build a Sample with the right target, id and metadata
  • Load a dataset with json_dataset, csv_dataset or hf_dataset and set limit and shuffle correctly
  • Explain the solver protocol and TaskState
  • Chain built-in solvers such as system_message and generate in the right order
  • Write your own solver with the decorated-factory pattern
  • Rebuild the triage task properly with a dataset, solvers and task configuration

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The eval passed 100% on the new cases. Suspicious." 2.2 The empty target
"Sample 17 got worse between runs." (It is a different question now.) 2.4 Sample ids
"Let's break the results down by plan and intent." 2.5 Metadata and typed metadata
"Load the CSV from the labelling tool." 3.2 csv_dataset
"One source row should become three test cases." 3.6 record_to_sample
"Just run the first 50 to check it works." 4.3 Run-time selection
"Shuffle the options so the model can't learn the position." 4.4 Multiple-choice data and choice shuffling
"Keep adding harder questions until it fails." 3.10 Datasets that grow
"What exactly did we send the model?" 6.5 Template rules and 10.2
"Our JSON instructions arrived with doubled braces." 6.5 Template rules
"Add a self-critique step and see if it helps." 6.8 self_critique
"Write a solver that retries when the JSON is invalid." Part 7 and Part 9
"Run the same task with a different prompt version." 8.2 Task arguments
"Use the package's task, but with our agent." 8.4 task_with()
"I set it in .env but the notebook ignores it." 8.5 The four layers
"Reproduce the paper's run exactly." 8.6 Configuration files
"Is 87.5% good? Did the eval even work?" 10.1 Control solvers

Part 1: The life of one sample#

1.1 Three components, one data structure#

10B.8 introduced the formula Task = Dataset + Solver + Scorer. It hides the structure that connects the three: the TaskState. Inspect builds one TaskState per sample per epoch, every solver receives it and returns it, the scorer reads it, and the log stores what is left of it. Once you can picture what is in the state at each step, most of Inspect's behaviour stops being surprising.

flowchart TD
    S["Sample: input, target, id, metadata, choices"] --> TS["TaskState built: messages = input as chat messages"]
    TS --> SU["setup solver(s): always run"]
    SU --> SO["solver chain: system_message, prompt_template, generate, your solvers"]
    SO -->|"state.completed = True"| SC
    SO --> SC["scorer(s) read state.output and target"]
    SC --> CL["cleanup(state): runs even after an exception"]
    CL --> LOG["EvalSample in the log: messages, output, scores, store, events"]

In words, for each sample and each epoch:

  1. Inspect builds a TaskState from the Sample. A string input becomes one user message; a list of chat messages is copied as it is. target, metadata, choices and the id are carried along.
  2. The task's setup solvers run, if there are any. They run even when the main solver has been replaced at run time (Part 7.8).
  3. The solver runs. A list of solvers is a chain: each one gets the state the previous one returned. A solver that calls the model appends the assistant message and sets state.output. If any solver sets state.completed = True, or a limit is hit, the rest are skipped.
  4. Every scorer reads the state (usually state.output.completion) and the target, and returns a Score.
  5. The task's cleanup function runs, whatever happened before.
  6. The finished sample is written to the log: its messages, output, scores, the store, metadata and a full event transcript.

1.2 Who owns what#

Decision Owned by Lesson
Which cases exist, their labels, splits, size The dataset you load This lesson (Parts 2 to 4); design in 10A.2
What text and turns the model sees The solvers This lesson (Parts 5 to 7)
How an answer becomes a verdict The scorer 10B.10, 10B.11
How verdicts become one number with an interval Metrics, epochs, reducers 10B.10
Which model, which limits, how many epochs, which samples run Task configuration and the run This lesson (Part 8); running at scale in 10B.12
What is recorded and how to analyse it The log 10B.13

1.3 What this lesson adds to 10B.8, and what 10A.10 got wrong#

10B.8 used an in-memory list of samples and the simplest solvers, sketched the override layers (10B.8, 2.5), and reproduced the first-day pitfalls (the brace rule, the empty target, every task in a file running; 10B.8, Part 9). This lesson goes underneath each of those: everything else in the dataset and solver components, the full template rules behind the pitfalls, and the whole configuration machinery. Along the way it corrects three statements in 10A.10, Part 4.4: the system prompt in that example is silently altered by system_message() before it reaches the model (6.5), Inspect has no Parquet loader (3.9), and the concept map's "sample-level epochs" do not exist (epochs are set per task or per run; 10B.10). Part 11 lists them all.


Part 2: Samples#

2.1 Every field of a Sample#

A Sample (from inspect_ai.dataset) is one eval case. It is a Pydantic model, so it validates its fields when you create it. The installed signature in 0.3.292 is:

text
Sample(input: str | list[ChatMessage], choices: list[str] | None = None,
       target: str | list[str] = "", id: int | str | None = None,
       metadata: dict[str, Any] | None = None, sandbox: ... = None,
       files: dict[str, str] | None = None, setup: str | None = None,
       checkpoint: ... = None, *, description: str | None = None)
Field Type and default What it is for Where it matters
input str or list[ChatMessage], required What the model receives. A string becomes one user message; a list can carry a system prompt, few-shot turns or images 2.6
target str or list[str], default "" The ideal answer, a list of acceptable answers, a letter for multiple choice, or grading guidance for a model grader 2.2, 2.3
id int, str or None, default None Stable identity across runs, retries and comparisons 2.4
metadata dict or None Slice axes for analysis, values for prompt templates, anything a solver or scorer needs 2.5
choices list[str] or None Options for multiple choice, without letters (Inspect adds them) 4.4
description str or None (keyword-only) A short statement of what the sample asks; logged, and a column in samples_df() Read from a file only when FieldSpec(description=...) names the field
sandbox sandbox spec or None A per-sample sandbox environment 10B.15
files dict[str, str] or None Files copied into the sandbox: sandbox path to local path, URL, inline text or base64 data URL 10B.15
setup str or None A bash script (path or inline) run in the default sandbox before the sample, with a 5-minute timeout 10B.15
checkpoint checkpoint config or None Per-sample agent checkpointing 10B.15

Sample also has one method you will use: metadata_as(Model), which returns the metadata validated as a Pydantic model (2.5).

2.2 The empty-target trap#

10B.8, 9.3 showed this with includes(). Here is the full picture: every default of a sample built with only the required field, the same check with match(), and the list target:

python
# s01_samples.py: Sample defaults, the empty-target trap, list targets.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes, match

s = Sample(input="Classify: my invoice is wrong")
print("defaults:", {k: getattr(s, k) for k in
      ["input", "choices", "target", "id", "metadata", "description", "sandbox", "files", "setup"]})

# The trap: a sample with no target still "passes" includes() and match(),
# because the empty string is contained in (and matches the end of) any output.
log = eval(
    Task(dataset=[Sample(id="no-target", input="Anything at all")],
         scorer=[includes(), match()]),
    model="mockllm/model", log_dir="logs", display="none",
)[0]
sample = log.samples[0]
print("output:", repr(sample.output.completion))
print("scores:", {name: sc.value for name, sc in sample.scores.items()})

# A list target means "any of these is acceptable" for the text scorers.
log = eval(
    Task(dataset=[Sample(id="alt", input="x", target=["nothing", "mockllm"])],
         scorer=includes()),
    model="mockllm/model", log_dir="logs", display="none",
)[0]
print("list target:", log.samples[0].target, "->", log.samples[0].scores["includes"].value)
Output · real4 lines
defaults: {'input': 'Classify: my invoice is wrong', 'choices': None, 'target': '', 'id': None, 'metadata': None, 'description': None, 'sandbox': None, 'files': None, 'setup': None}
output: 'Default output from mockllm/model'
scores: {'includes': 'C', 'match': 'C'}
list target: ['nothing', 'mockllm'] -> C

Read the second line carefully. A sample with no target scored C (correct) under both includes() and match(), for an answer that has nothing to do with anything. The reason is plain string logic: the empty string is contained in every string, and every string ends with it. So a dataset in which a column was misnamed, a label was left blank, or a loader mapped the wrong field to target does not fail: it passes, loudly, at 100%.

2.3 What a target can be#

The target is deliberately loose, because different scorers want different things from it:

Target Example Used by
A literal answer "Lima" match(), includes(), exact(), f1(), pattern(), answer()
Several acceptable answers ["30 days", "thirty days"] The same scorers: any element may match (the last line of the output above)
A letter (or letters) "C", ["B", "D"] choice() with multiple_choice() (4.4)
Canonical JSON text '{"category": "billing", "priority": "P2"}' Your own scorer that parses it (Part 9)
Grading guidance "Says refunds are possible within 30 days and does not promise a refund" model_graded_fact() / model_graded_qa() (10B.11)

Inside a scorer the target arrives as a Target object: iterate it for the list, or use .text for one string (with a list, .text concatenates the elements, which is rarely what you want). 10B.10 has the details.

2.4 Sample ids: when they are assigned, and why it matters#

The docs say samples without an id field "will automatically be assigned ids based on an auto-incrementing integer starting with 1". That is true by the end of a run, but when the number is assigned decides whether "sample 2" means the same question in two runs. This sample uses a three-row CSV, data/qa.csv:

text
question,answer,difficulty
What is 2+2?,4,easy
Capital of Peru?,Lima,medium
What is 3*3?,9,easy
python
# s02_ids.py: when ids are assigned, and why positional ids are fragile.
from inspect_ai import Task, eval
from inspect_ai.dataset import FieldSpec, csv_dataset

spec = FieldSpec(input="question", target="answer")

def ids_in_log(dataset, **eval_args):
    log = eval(Task(dataset=dataset), model="mockllm/model",
               log_dir="logs", display="none", **eval_args)[0]
    return sorted((s.id, s.input) for s in log.samples)

# 1. Loaders leave id=None unless the data has an id field or you ask for auto_id.
print("load, no id column:", [s.id for s in csv_dataset("data/qa.csv", spec)])
print("load, auto_id=True:", [s.id for s in csv_dataset("data/qa.csv", spec, auto_id=True)])

# 2. eval() numbers id-less samples by position when the run starts.
print("plain run:      ", ids_in_log(csv_dataset("data/qa.csv", spec)))

# 3. Shuffle at load time WITHOUT auto_id: positions (and so ids) now point at other rows.
print("shuffle=2 load: ", ids_in_log(csv_dataset("data/qa.csv", spec, shuffle=2)))

# 4. auto_id=True numbers rows BEFORE the loader shuffles, so ids stay with their content.
print("auto_id+shuffle:", ids_in_log(csv_dataset("data/qa.csv", spec, auto_id=True, shuffle=2)))

# 5. Run-time --sample-shuffle: are ids given before or after the shuffle?
print("sample_shuffle: ", ids_in_log(csv_dataset("data/qa.csv", spec), sample_shuffle=2))
Output · real6 lines
load, no id column: [None, None, None]
load, auto_id=True: [1, 2, 3]
plain run:       [(1, 'What is 2+2?'), (2, 'Capital of Peru?'), (3, 'What is 3*3?')]
shuffle=2 load:  [(1, 'Capital of Peru?'), (2, 'What is 3*3?'), (3, 'What is 2+2?')]
auto_id+shuffle: [(1, 'What is 2+2?'), (2, 'Capital of Peru?'), (3, 'What is 3*3?')]
sample_shuffle:  [(1, 'Capital of Peru?'), (2, 'What is 3*3?'), (3, 'What is 2+2?')]

Four facts come out of this:

  1. Loaders do not number samples. Without an id column and without auto_id=True, every loaded sample has id=None.
  2. The run numbers them by position. When eval() starts, samples still without an id get 1, 2, 3 in the order they are in at that moment.
  3. A shuffle before that moment changes which question gets which number. With shuffle=2 at load time, id 1 is "Capital of Peru?". With sample_shuffle=2 at run time, the same thing happens. Compare two such runs by id and you are comparing different questions.
  4. auto_id=True numbers rows before the loader shuffles, so the ids stay with their content even with shuffle=2. A run-time sample_shuffle cannot move them either, because they are already set.

Ids matter far beyond display. They are the key that --sample-id selects on (4.3), the key that eval_retry() and eval sets use to reuse completed samples instead of re-running them (10B.12), the key samples_df() joins on when you compare two runs (10B.13), and the key a paired statistical test needs (10A.8).

2.5 Metadata and typed metadata#

metadata is a dict that travels with the sample. Three things read it:

  • Analysis: every key can become a slice axis, exactly as evalkit's Example.metadata did in 10A.1 and the tags of 10A.2, 3.2. In Inspect, slices are computed with grouped metrics (10B.10) or after the run with samples_df() (10B.13).
  • Templates: system_message(), user_message(), assistant_message() and prompt_template() substitute {key} placeholders from metadata (6.5).
  • Your solvers and scorers: state.metadata["plan"].

The working dataset for most of this lesson is eight support tickets, data/tickets.jsonl, in the same family as 10A.1's triage set:

text
{"ticket_id": "T01", "text": "Hi, I was charged twice for my pro plan this month and nobody has responded to my emails for days. I want my money back.", "priority": "P2", "category": "billing", "intent": "billing", "edge": "multi-intent", "plan": "pro"}
{"ticket_id": "T02", "text": "Our whole team can't log in since this morning. Dashboard shows a 500 error on every page.", "priority": "P1", "category": "technical", "intent": "technical", "edge": "outage", "plan": "team"}
{"ticket_id": "T03", "text": "How do I add a second admin to our Team plan? The docs mention it but I can't find the button.", "priority": "P3", "category": "account", "intent": "account", "edge": "how-to", "plan": "team"}
{"ticket_id": "T04", "text": "I think someone hacked my account. I got a password-reset email I didn't request.", "priority": "P1", "category": "account", "intent": "account", "edge": "security", "plan": "pro"}
{"ticket_id": "T05", "text": "When will my order ship? I ordered the standing desks two weeks ago and tracking hasn't updated.", "priority": "P2", "category": "shipping", "intent": "shipping", "edge": "stale-tracking", "plan": "free"}
{"ticket_id": "T06", "text": "Your mobile app crashes every time I open the reports tab on Android 15.", "priority": "P2", "category": "technical", "intent": "technical", "edge": "bug-report", "plan": "pro"}
{"ticket_id": "T07", "text": "Thanks for the quick fix last week, everything works now.", "priority": "P3", "category": "other", "intent": "other", "edge": "no-request", "plan": "free"}
{"ticket_id": "T08", "text": "I want to downgrade from Team to Pro at the end of this billing cycle. Will I lose my historical data?", "priority": "P3", "category": "billing", "intent": "billing", "edge": "downgrade", "plan": "team"}

A plain dict is easy to misuse: a typo in a key (state.metadata["pln"]) raises KeyError mid-run, and a missing value turns up only when a solver reads it. Typed metadata moves that check to load time. You declare a Pydantic model with frozen=True, pass it to FieldSpec(metadata=...), and read it with metadata_as():

python
# s04_metadata.py: typed metadata with a frozen Pydantic model, read inside a solver.
from pydantic import BaseModel, ValidationError

from inspect_ai import Task, eval
from inspect_ai.dataset import FieldSpec, json_dataset
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver


class TicketMeta(BaseModel, frozen=True):   # frozen=True is required: metadata is read-only
    intent: str
    edge: str
    plan: str


spec = FieldSpec(input="text", target="category", id="ticket_id", metadata=TicketMeta)
ds = json_dataset("data/tickets.jsonl", spec)
print("sample metadata is a dict:", ds[0].metadata)
print("typed view:", ds[0].metadata_as(TicketMeta))


@solver
def show_meta() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        meta = state.metadata_as(TicketMeta)          # validated, typed, read-only
        try:
            meta.plan = "enterprise"                  # writing is refused
        except ValidationError as e:
            print(f"  {state.sample_id}: plan={meta.plan!r}; write ->", e.errors()[0]["type"])
        return state
    return solve


eval(Task(dataset=ds[0:2], solver=[show_meta(), generate()]),
     model="mockllm/model", log_dir="logs", display="none")


# A non-frozen model is rejected when the dataset loads.
class Loose(BaseModel):
    intent: str

try:
    json_dataset("data/tickets.jsonl", FieldSpec(input="text", metadata=Loose))
except Exception as e:
    print("non-frozen model ->", type(e).__name__ + ":", str(e)[:110])

# A missing field fails the load too: validation happens up front, not mid-run.
class NeedsRegion(BaseModel, frozen=True):
    region: str

try:
    json_dataset("data/tickets.jsonl", FieldSpec(input="text", metadata=NeedsRegion))
except Exception as e:
    print("missing field ->", type(e).__name__ + ":", str(e).splitlines()[0][:110])
Output · real6 lines
sample metadata is a dict: {'intent': 'billing', 'edge': 'multi-intent', 'plan': 'pro'}
typed view: intent='billing' edge='multi-intent' plan='pro'
  T01: plan='pro'; write -> frozen_instance
  T02: plan='team'; write -> frozen_instance
non-frozen model -> ValueError: Metadata model Loose must have frozen=True
missing field -> ValueError: Could not parse metadata into NeedsRegion: 1 validation error for NeedsRegion

What this shows:

  • The model's fields decide which columns are copied: intent, edge and plan were kept, priority and category were not.
  • The sample still stores a plain dict (it is serialized to the log as one). metadata_as() validates and returns a typed, read-only view.
  • Writing to the view fails. The docs say this raises a "FrozenInstanceError"; what you actually get in 0.3.292 is a Pydantic ValidationError whose error type is frozen_instance. Catch ValidationError.
  • A model without frozen=True, or a row that does not validate, fails when the dataset loads, before any model is called. That is the point.

For per-sample data that must change during a run (attempt counters, intermediate results), metadata is the wrong place: use the store (7.5).

2.6 Chat-message inputs#

A string input is the common case. A list of chat messages (ChatMessageSystem, ChatMessageUser, ChatMessageAssistant, ChatMessageTool from inspect_ai.model) is for when the case itself is a conversation:

  • a case-specific system prompt (each sample tests a different persona or policy),
  • few-shot examples written as user and assistant turns (04.2 owns when they help),
  • a multi-turn case where the earlier turns are fixed and only the last reply is evaluated (the conversational cases of 10A.12),
  • a prefilled assistant turn.
python
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageAssistant, ChatMessageSystem, ChatMessageUser

case = Sample(
    id="refund-followup-03",
    input=[
        ChatMessageSystem(content="You are Acme Cloud's billing assistant. Policy v3 applies."),
        ChatMessageUser(content="I was charged twice this month."),
        ChatMessageAssistant(content="Sorry about that. Can you share the invoice number?"),
        ChatMessageUser(content="INV-2291. Can I get the duplicate refunded today?"),
    ],
    target="Offers a refund of the duplicate charge and gives the 5-10 working day timeline",
)

In a JSON or JSONL file the same input is a list of {"role": ..., "content": ...} objects, which json_dataset turns into message objects. Three things to know:

  • state.input_text returns the text of the last user message of a list input (and [image]-style placeholders for a message that has only media), and state.user_prompt is that last user message as an object. Solvers that rewrite "the prompt" (prompt_template(), chain_of_thought()) rewrite only that last user message.
  • system_message() inserts after any system messages already in the input, so a task-wide system prompt and a case-specific one coexist. Part 6.2 shows it.
  • Fixed earlier assistant turns are written by you, not the model under test. A case like the one above measures "given this history, is the next reply right?", not "can the model hold this conversation". For the second question you need a solver that plays the user (7.2) or a simulator (10A.12).

2.7 Multimodal inputs#

Content can also be a list of parts: ContentText, ContentImage, ContentAudio, ContentVideo, ContentDocument (and ContentReasoning and ContentData, which models produce rather than receive). An image case looks like this (illustrative: it needs a vision-capable model and an image file):

python
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageUser, ContentImage, ContentText

receipt_case = Sample(
    id="receipt-017",
    input=[ChatMessageUser(content=[
        ContentText(text="What is the total amount on this receipt? Reply with the number only."),
        ContentImage(image="images/receipt-017.png"),   # a local path, URL or base64 data URL
    ])],
    target="42.80",
)

Which providers accept which media, size limits and the --no-log-images option are on the multimodal page; sending media to the providers themselves is 03.6, and what to measure on multimodal outputs is 10A.7, Part 9. Logs embed images by default, which makes them large; that trade-off is 10B.13's.


Part 3: Loading datasets#

inspect_ai.dataset exports exactly these names in 0.3.292: Dataset, FieldSpec, MemoryDataset, RecordToSample, Sample, csv_dataset, example_dataset, file_dataset, hf_dataset and json_dataset. Everything in this part is one of them.

Whatever the loader, a sample passes through the same steps between the file and the run, and the order of those steps explains most of the surprises in this part and the next:

flowchart LR
    F["File or Hub: CSV, JSON, JSONL, HF split"] --> R["records (dicts)"]
    R -->|"FieldSpec or record_to_sample"| SM["Samples (one or more per record)"]
    SM -->|"auto_id=True numbers here"| SH["loader shuffle (seed)"]
    SH --> CH["shuffle_choices (rewrites target letters)"]
    CH --> LIM["loader limit"]
    LIM --> DS["Dataset in the Task"]
    DS -->|"eval / CLI: sample_shuffle, limit, sample_id"| RUN["samples that run"]
    RUN -->|"samples still without id: numbered by position"| IDS["ids in the log"]

(hf_dataset differs in one step: it applies limit to records before conversion; 3.6 explains.)

3.1 In memory: a list, MemoryDataset and example_dataset#

Task(dataset=...) accepts a plain list of Sample objects, which is what 10B.8 used. MemoryDataset wraps a list and adds a name, a location and the dataset methods of Part 4:

python
from inspect_ai.dataset import MemoryDataset, Sample

dataset = MemoryDataset(
    samples=[Sample(id="T01", input="Charged twice this month", target="billing")],
    name="tickets-smoke",          # shown in the log header and in inspect view
    location="generated in code",  # free text: where these samples came from
)

MemoryDataset(samples, name=None, location=None, shuffled=False) is also the escape hatch for any source Inspect does not read itself: a database query, an API, a Parquet file (3.9). Every loader below returns one.

example_dataset(name, sample_fields=None) loads the small datasets bundled with Inspect that its documentation uses (for example example_dataset("security_guide")). Use it to reproduce a docs example, not for your own evals.

3.2 csv_dataset#

text
csv_dataset(csv_file, sample_fields=None, auto_id=False, shuffle=False, seed=None,
            shuffle_choices=None, limit=None, dialect="unix", encoding="utf-8-sig",
            name=None, fs_options=None, fieldnames=None, delimiter=None) -> Dataset
Argument Meaning
csv_file Local path, s3://... URL or HTTPS URL (3.8)
sample_fields None (columns are already named input, target, ...), a FieldSpec (3.5) or a function (3.6)
auto_id Number samples 1, 2, 3 at load time, before shuffling (2.4)
shuffle, seed Shuffle after loading. An int is the seed (so shuffle=0 does shuffle); seed= goes with shuffle=True; combining it with an integer shuffle raises ValueError, with shuffle=False it is ignored, and a negative integer seed raises
shuffle_choices Shuffle multiple-choice options and rewrite the target letters (4.4)
limit Keep the first N samples, counted after conversion and shuffling (the docstring says "records"; 3.6)
dialect "unix" (default), "excel" or "excel-tab"
encoding "utf-8-sig" by default, which reads UTF-8 with or without the byte-order mark that Excel writes
fieldnames Column names for a file with no header row
delimiter Override the dialect's delimiter (";" for many European exports)
name Dataset name for the log. Intended default (per the source, Path(csv_file).stem; the datasets page states none): the file stem. Broken in 0.3.292, see below
fs_options Passed to the filesystem (for S3, {"anon": True} for a public bucket)

The loaders have more edge cases than their signatures suggest, so here is one script that exercises them all. It uses data/qa.csv from 2.4, the two-line JSON files data/qa.jsonl and data/qa_array.json (the same two records, {"input": "Say hi", "target": "hi", "id": "a"} and a "bye" twin, as JSON Lines and as a JSON array), a tab-separated data/planets.tsv, a data/bom.csv saved with a byte-order mark, and data/ragged.csv, whose second data row has an unquoted comma inside the question:

text
question,answer
What is 2+2?,4
Capital of Peru, the city?,Lima
python
# s03_loaders.py: the file loaders, FieldSpec, record_to_sample and their edge cases.
from inspect_ai import Task, eval
from inspect_ai.dataset import (FieldSpec, Sample, csv_dataset, file_dataset,
                                json_dataset)

spec = FieldSpec(input="question", target="answer", metadata=["difficulty"])

d = csv_dataset("data/qa.csv", spec)
print("csv:", [(s.input, s.target, s.metadata) for s in d])
print("csv name (default):", d.name, "| location:", d.location.split("/")[-1])
print("csv name (explicit):", csv_dataset("data/qa.csv", spec, name="qa").name)
# Workaround: filter() keeps every sample but takes a name, and returns a new MemoryDataset.
named = csv_dataset("data/qa.csv", spec).filter(lambda s: True, name="qa")
print("csv name (after filter workaround):", named.name)

# JSON Lines and a JSON array both load with json_dataset; default field names need no FieldSpec.
print("jsonl:", [(s.id, s.input, s.target) for s in json_dataset("data/qa.jsonl")])
print("json array:", [(s.id, s.input) for s in json_dataset("data/qa_array.json")], "| name:", json_dataset("data/qa_array.json").name)

# file_dataset dispatches on the extension (.tsv uses a tab delimiter).
print("file_dataset tsv:", [(s.input, s.target) for s in file_dataset("data/planets.tsv", FieldSpec(input="question", target="answer"))])

# utf-8-sig (the csv default encoding) strips a byte-order mark from Excel exports.
print("BOM csv:", [(s.input, s.target) for s in csv_dataset("data/bom.csv", FieldSpec(input="question", target="answer"))])

# No FieldSpec and no 'input' column: the loader refuses.
try:
    csv_dataset("data/qa.csv")
except Exception as e:
    print("no input column ->", type(e).__name__ + ":", e)

# record_to_sample may return several samples per record; limit counts SAMPLES, after conversion.
def two_phrasings(record: dict) -> list[Sample]:
    q = record["question"]
    return [Sample(id=f"{record['difficulty']}-{i}", input=text, target=record["answer"])
            for i, text in enumerate([q, q.lower()])]
print("one row -> two samples, limit=3:", [s.id for s in csv_dataset("data/qa.csv", two_phrasings, limit=3)])

# A record_to_sample that raises on a bad row stops the load: fail loudly, early.
def strict(record: dict) -> Sample:
    if record["difficulty"] not in {"easy", "medium", "hard"}:
        raise ValueError(f"bad difficulty {record['difficulty']!r}")
    return Sample(input=record["question"], target=record["answer"])
print("strict loader:", len(csv_dataset("data/qa.csv", strict)), "samples")

# What the log records as the dataset name, before and after the workaround.
for ds in (csv_dataset("data/qa.csv", spec), named):
    log = eval(Task(dataset=ds), model="mockllm/model", log_dir="logs", display="none")[0]
    print("logged dataset:", log.eval.dataset.name, "| samples:", log.eval.dataset.samples)

# An unquoted comma inside a field makes a ragged row: the loader names the line.
try:
    csv_dataset("data/ragged.csv", FieldSpec(input="question", target="answer"))
except ValueError as e:
    print("ragged csv ->", str(e).split("/")[-1])

The output below is real; the absolute path in the last line is trimmed to the file name by the script.

Output · real14 lines
csv: [('What is 2+2?', '4', {'difficulty': 'easy'}), ('Capital of Peru?', 'Lima', {'difficulty': 'medium'}), ('What is 3*3?', '9', {'difficulty': 'easy'})]
csv name (default): difficulty | location: qa.csv
csv name (explicit): difficulty
csv name (after filter workaround): qa
jsonl: [('a', 'Say hi', 'hi'), ('b', 'Say bye', 'bye')]
json array: [('a', 'Say hi'), ('b', 'Say bye')] | name: qa_array
file_dataset tsv: [('Largest planet?', 'Jupiter')]
BOM csv: [('What colour is the sky?', 'blue')]
no input column -> ValueError: No input in dataset
one row -> two samples, limit=3: ['easy-0', 'easy-1', 'medium-0']
strict loader: 3 samples
logged dataset: difficulty | samples: 3
logged dataset: qa | samples: 3
ragged csv -> ragged.csv line 3 has 3 fields, the header has 2. Unexpected values: ['Lima'].

Line by line:

  • Field mapping works as expected: question became input, answer became target, difficulty went into metadata.
  • The dataset name is wrong. It should be qa (the file stem). It is difficulty, the last column header, and passing name="qa" explicitly gives difficulty too. The cause is in the installed source: the duplicate-column check loops for name in reader.fieldnames:, reusing the variable that holds your name argument. The name is only a label (scores are unaffected), but it is the label in every log header, in evals_df() and in inspect view, so a run on qa.csv shows up as a run on "difficulty". Workaround: filter() accepts a name and returns a new dataset, so csv_dataset(...).filter(lambda s: True, name="qa") fixes it, and the last two lines of output show the log recording difficulty before and qa after. json_dataset is not affected (its JSON array loaded as qa_array). This is a bug in 0.3.292; check the changelog before relying on the workaround in later versions.
  • No input column and no FieldSpec, or a row whose input is empty, gives ValueError: No input in dataset. The default mapping expects columns literally named input and target. The same check rejects an empty input in the default JSON, FieldSpec and CSV loaders, while Sample(input="") and a record_to_sample function accept it (10B.17, 5.2).
  • A byte-order mark is stripped by the default utf-8-sig encoding, so the first column is question, not question. If you pass encoding="utf-8" yourself, a file from Excel gains an invisible character in its first header and the FieldSpec lookup fails.
  • A ragged row is refused with the line number and the unexpected values. Quote fields that contain commas ("Capital of Peru, the city?"), which every CSV writer does if you let it.

Two more source-level behaviours: duplicate column names are refused with ValueError: Duplicate column names in ... (the CSV reader would otherwise silently keep only the last), and rows whose values are all empty are dropped without a message. If your labelling tool exports blank separator rows, they disappear; if it exports a row with only an id filled in, the default, FieldSpec and CSV loaders raise ValueError: No input in dataset for it (only a record_to_sample function keeps a row with an empty input, 10B.17, 5.2).

3.3 json_dataset and file_dataset#

text
json_dataset(json_file, sample_fields=None, auto_id=False, shuffle=False, seed=None,
             shuffle_choices=None, limit=None, encoding="utf-8", name=None,
             fs_options=None, **reader_kwargs) -> Dataset

One function reads both a JSON array of objects and JSON Lines (one object per line), as the output above shows. JSONL is the better format for eval data: one case per line diffs cleanly in git, appends safely, and a bad line is easy to locate (10A.2, 1.4). Field values can be nested objects, which is how a chat-message input (2.6) or a list target is stored. Note the default encoding here is plain utf-8.

file_dataset (exported, though missing from the reference page) dispatches on the extension: .json and .jsonl to the JSON reader, .csv, .tsv and .tab to the CSV reader with the right delimiter. Its signature is the union of the two, with dialect, fieldnames and encoding="utf-8". Use it when a task should accept whatever file the user passes as a task argument.

3.4 Where the default mapping comes from#

With sample_fields=None, every loader reads fields named exactly like the Sample attributes: input, target, id, choices, metadata, sandbox, files, setup and checkpoint. Anything else in the record is ignored. That convention is convenient for files you write yourself and almost never matches data exported from somewhere else, which is what FieldSpec and record_to_sample are for.

3.5 FieldSpec in full#

text
FieldSpec(input="input", target="target", choices="choices", id="id",
          metadata: list[str] | type[BaseModel] | None = None,
          sandbox="sandbox", files="files", setup="setup",
          *, checkpoint: str | None = "checkpoint", description: str | None = None)

Each argument names the source field that fills the Sample field of the same name:

Argument Notes
input, target, id The three you set most often
choices A field holding a list of options
metadata A list of field names to copy into metadata, or a frozen Pydantic model whose fields are copied and validated (2.5)
sandbox, files, setup Agent and sandbox fields (10B.15)
checkpoint Read by default from a field called checkpoint. If your data has an unrelated column with that name, pass checkpoint=None
description Only read when you name the field, so an existing description column in your data is not picked up by accident

The docs' own example is the shape you will write most:

python
from inspect_ai.dataset import FieldSpec, json_dataset

dataset = json_dataset(
    "popularity.jsonl",
    FieldSpec(input="question", target="answer_matching_behavior",
              id="question_id", metadata=["label_confidence"]),
)

FieldSpec only renames. As soon as you need to transform a value (strip whitespace, join two columns, turn an integer label into a letter, build a chat-message input, validate), write a function instead.

3.6 record_to_sample: custom mapping and one-to-many#

RecordToSample is Callable[[dict], Sample | list[Sample]]. Pass a function in place of the FieldSpec; it receives each record as a dict and returns a sample, or a list of samples. The relevant lines of the run above:

text
one row -> two samples, limit=3: ['easy-0', 'easy-1', 'medium-0']
strict loader: 3 samples

Two lessons are in those lines.

One record can become several samples. two_phrasings produced an original and a lower-cased variant of each question. The same pattern turns one source document into several questions, one support thread into one case per turn, or one prompt into a set of paraphrases for a robustness check (10A.10, 6.3). Give every derived sample an id that encodes its parent (easy-0, easy-1), and keep the parent id in metadata, because derived samples are not independent: they share a source, so they must stay in the same split (10A.2, 6.7) and their standard error needs clustering (10B.10).

limit counts samples, not records in csv_dataset and json_dataset. The docstring says "Limit the number of records to read"; the source reads and converts every record, shuffles if asked, and then returns dataset[0:limit]. With limit=3 and two samples per record, you get both samples of the first record and one of the second, an unbalanced subset. hf_dataset is different: its source applies limit to records (it selects records from the Hub dataset, then converts), so there limit=3 with two samples per record gives six samples. If you use limit with a one-to-many function, either check which loader you are in or filter by parent id instead.

Validate in the function and raise. The strict function refuses unknown difficulty labels. A ValueError raised there stops the load with your message, before any model is called. This is the cheapest place in the whole pipeline to catch a bad label, the empty target of 2.2 or a missing field, and it is the Inspect equivalent of the schema validation that 10A.2's loader does (10A.2, 8.4). Part 9's record_to_sample shows a complete version.

3.7 hf_dataset (illustrative: downloads from the Hugging Face Hub)#

text
hf_dataset(path, split, name=None, data_dir=None, revision=None, sample_fields=None,
           auto_id=False, shuffle=False, seed=None, shuffle_choices=None, limit=None,
           trust=False, cached=True, retry=True, **kwargs) -> Dataset

It needs the datasets package (uv add datasets) and calls Hugging Face's load_dataset(); any extra keyword arguments are passed through to it (for example cache_dir=).

python
from inspect_ai.dataset import FieldSpec, hf_dataset

humaneval = hf_dataset(
    "openai_humaneval",
    split="test",                         # Hub datasets have splits; you must pick one
    revision="<commit sha>",              # pin the exact version you evaluated (placeholder)
    sample_fields=FieldSpec(id="task_id", input="prompt", target="canonical_solution",
                            metadata=["test", "entry_point"]),
)
Argument Why it matters
split Required. Evaluate on test (or whatever the dataset card calls its held-out split), not train
name The Hub "configuration" (subset) when a dataset has several
revision A branch, tag or commit. Pin it: Hub datasets change in place, and an unpinned eval is not reproducible
trust Default False. Some Hub datasets run Python code to build themselves; trust=True runs that code on your machine. Only set it for repositories whose code you have read
cached Default True: reuse the local copy instead of downloading again
retry Default True: retry rate limits, timeouts and unreachable-Hub cache misses with exponential backoff
limit Counts records, unlike the file loaders (3.6)

Hugging Face datasets can also ship whole Inspect task definitions in an eval.yaml file; Part 8.9 covers running those.

3.8 Remote files: S3 and HTTPS#

Every file loader accepts an s3://bucket/key URL or an HTTPS URL instead of a local path. Authentication uses the standard AWS configuration of your machine; fs_options passes options to the filesystem ({"anon": True} for a public bucket). Inspect turns on a read-ahead cache for S3 by default. Use a shared bucket when several people or CI jobs must evaluate exactly the same file, and record the object version (or keep the file immutable and versioned by name), because a dataset that changes under a fixed URL breaks every comparison you make later (10A.2, 6.3).

3.9 No Parquet loader: pandas and MemoryDataset#

10A.10's concept map lists "parquet" as an Inspect dataset format. There is no Parquet reader in inspect_ai.dataset (the exports are listed at the top of this part). For Parquet, or any format pandas reads, build the samples yourself:

python
# s18_parquet.py: Inspect has no Parquet loader; read with pandas, build a MemoryDataset.
import pandas as pd

from inspect_ai.dataset import MemoryDataset, Sample

# Make a Parquet file to read (in real life it comes from your warehouse or labelling tool).
pd.read_json("data/tickets.jsonl", lines=True).to_parquet("data/tickets.parquet", index=False)

frame = pd.read_parquet("data/tickets.parquet")
dataset = MemoryDataset(
    samples=[
        Sample(id=row.ticket_id, input=row.text, target=row.category,
               metadata={"intent": row.intent, "plan": row.plan})
        for row in frame.itertuples(index=False)
    ],
    name="tickets",                       # MemoryDataset has no file stem to guess a name from
    location="data/tickets.parquet",      # recorded in the log as the dataset location
)
print(dataset.name, len(dataset), [(s.id, s.target) for s in dataset[:3]])

The output below is real; run with pandas and pyarrow added, which inspect-ai does not install.

Output · real1 line
tickets 8 [('T01', 'billing'), ('T02', 'technical'), ('T03', 'account')]

If your cases live in the evalkit format of 10A.2 (EvalExample rows with example_id, inputs, expected, split, tags, difficulty and an optional rubric), a record_to_sample function maps them directly, keeping evalkit's ids and splits:

python
# s13_evalkit_adapter.py: load a 10A.2-format JSONL (EvalExample rows) as Inspect Samples.
import json
from pathlib import Path

from inspect_ai.dataset import MemoryDataset, Sample, json_dataset


def evalkit_record_to_sample(record: dict) -> Sample:
    """Map one EvalExample row (lesson 10A.2's schema) onto an Inspect Sample.

    example_id      -> Sample.id         (stable, content-independent: safe for retries and diffs)
    inputs.ticket   -> Sample.input      (what the system under test receives)
    expected        -> Sample.target     (canonical JSON text; "" only when there is no reference)
    tags, split,
    difficulty      -> Sample.metadata   (slice axes and the split guard)
    rubric          -> Sample.metadata["rubric"] (for a model-graded scorer, lesson 10B.11)
    """
    expected = record.get("expected")
    if expected is None and not record.get("rubric"):
        raise ValueError(f"{record['example_id']}: no expected output and no rubric")
    metadata = dict(record.get("tags", {}))
    metadata["split"] = record.get("split", "dev")
    if record.get("difficulty"):
        metadata["difficulty"] = record["difficulty"]
    if record.get("rubric"):
        metadata["rubric"] = record["rubric"]
    return Sample(
        id=record["example_id"],
        input=record["inputs"]["ticket"] or "(empty ticket)",   # explicit: some provider APIs reject an empty user message
        target=json.dumps(expected, sort_keys=True) if expected is not None else "",
        metadata=metadata,
    )


def triage_split(split: str) -> MemoryDataset:
    ds = json_dataset("data/triage_evalkit.jsonl", evalkit_record_to_sample)
    return ds.filter(lambda s: s.metadata["split"] == split, name=f"triage-{split}")


for split in ("dev", "test"):
    ds = triage_split(split)
    print(f"{ds.name}: {[(s.id, s.target, s.metadata.get('edge')) for s in ds]}")
print("T10 input as loaded:", repr(triage_split("test")[1].input))
print("source file sha256 prefix:",
      __import__("hashlib").sha256(Path("data/triage_evalkit.jsonl").read_bytes()).hexdigest()[:12])

The JSONL file has four rows in 10A.2's schema (one dev, three test; T10 has an empty ticket and T13 has a rubric but no expected output). Output (real):

text
triage-dev: [('T01', '{"category": "billing", "priority": "P2"}', 'multi-intent')]
triage-test: [('T02', '{"category": "technical", "priority": "P1"}', 'outage'), ('T10', '{"category": "other", "priority": "P3"}', 'empty'), ('T13', '', 'rubric-only')]
T10 input as loaded: '(empty ticket)'
source file sha256 prefix: fda9315aca62

Three design decisions are worth copying:

  • The split lives in metadata and is filtered in code, so a task argument can choose dev or test (8.2) and a run on the test split is a deliberate act (10A.2, 6.1).
  • The target is canonical JSON (sort_keys=True), so two dicts with the same content always produce the same string and a scorer can parse it back.
  • The empty input is made explicit. Inspect itself accepts an empty-string input (a separate run, s13b_empty_input.py, sent ('user', '') to the mock and finished with status success), but some provider APIs reject an empty user message, so the adapter turns it into a visible placeholder that the model under test can still treat as "nothing to triage".

Record the file's hash (the last line) next to the run, in the task's metadata for example. It is the cheapest way to prove later which version of the labels a number came from.

3.10 Datasets that grow while the task runs: SampleSource#

Every dataset so far is fixed before the run starts. A SampleSource (exported from inspect_ai, passed as Task(dataset=...)) produces samples while the task runs, in response to results: escalate difficulty until the model fails, run an open-ended generator until an external condition stops it, or drive a curriculum. It has four optional methods: initial_samples() (synchronous: the seed samples), async next_samples() (called when nothing is in flight; return None to finish), async sample_complete(sample) (sees each finished EvalSample and may return follow-ups) and async sample_abandoned(sample, epoch) (for samples cancelled before anything was logged). Here is the escalation pattern, keyless:

python
# s12_sample_source.py: a dataset that grows while the task runs (adaptive difficulty).
from inspect_ai import SampleSource, Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.log import EvalSample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import match


def arithmetic(level: int) -> Sample:
    """Level n asks for the sum of the numbers 1..n+1 (the answer grows with the level)."""
    n = level + 1
    return Sample(id=f"sum-{level}", input=f"What is the sum of the integers 1 to {n}?",
                  target=str(n * (n + 1) // 2), metadata={"level": level})


class Escalate(SampleSource):
    """Start at level 1; after each correct answer add the next level, stop at the first miss."""

    def initial_samples(self) -> list[Sample]:
        return [arithmetic(1)]

    async def sample_complete(self, sample: EvalSample) -> list[Sample] | None:
        passed = sample.scores["match"].value == "C"
        level = sample.metadata["level"]
        print(f"  completed {sample.id}: {'pass' if passed else 'fail'}")
        return [arithmetic(level + 1)] if passed and level < 10 else None


def weak_at_big_sums(input, tools, tool_choice, config):
    """A scripted 'model' that adds correctly only while the numbers stay small."""
    n = int(input[-1].text.rstrip("?").split()[-1])
    answer = n * (n + 1) // 2 if n <= 4 else n * n
    return ModelOutput.from_content(model="mockllm", content=f"The answer is {answer}")


model = get_model("mockllm/model", custom_outputs=weak_at_big_sums, memoize=False)
log = eval(Task(dataset=Escalate(), scorer=match()), model=model, log_dir="logs", display="none")[0]
print("samples run:", [(s.id, s.scores["match"].value) for s in log.samples])
print("highest level passed:",
      max(s.metadata["level"] for s in log.samples if s.scores["match"].value == "C"))
Output · real6 lines
  completed sum-1: pass
  completed sum-2: pass
  completed sum-3: pass
  completed sum-4: fail
samples run: [('sum-1', 'C'), ('sum-2', 'C'), ('sum-3', 'C'), ('sum-4', 'I')]
highest level passed: 3

All four samples ran inside one task and one log. Read the result carefully, because this is where adaptive data breaks the usual statistics: the log's accuracy for this run is 3 of 4, but the denominator was chosen by the model's own answers. A stronger model gets a longer run and a different denominator. The meaningful number is the one the design was built to produce ("highest level passed: 3"), and comparing two models means comparing that quantity, not accuracy. Standard errors computed by the metrics assume a fixed set of independent samples, which an adaptive source is not.

Details that bite (from the Sample Sources page): with epochs > 1, sample_complete fires once per epoch and each follow-up runs every epoch, so follow-ups multiply unless you de-duplicate on sample.epoch; generated samples without an id get ids such as dyn-t4ab9c-0003, so do not give your own samples ids in that form, and they re-run on a task retry (only samples with explicit ids are reused from the prior attempt), so give dynamic samples explicit ids (2.4). Two lighter entry points: enqueue_sample(samples, epoch=None) (exported from inspect_ai) adds samples to the running task from inside a running sample, and SampleSource.from_samples(initial_samples, next_samples=..., sample_complete=..., sample_abandoned=...) builds a source from callbacks instead of a subclass. A bare SampleSource with no samples runs nothing. TaskSource is the same idea one level up, generating whole tasks across a run, and works only with eval() (not eval_set(), eval_retry() or score()).


Part 4: Selecting, shuffling and multiple-choice data#

Deep-dive

4.1 Dataset methods#

A Dataset (every loader returns a MemoryDataset) supports:

Member Returns In place?
len(ds) (also ds.count) number of samples
ds[i], ds[a:b] a Sample; a new dataset with the same name no
ds.filter(predicate, name=None) a new MemoryDataset no
ds.shuffle(seed=None) None yes
ds.shuffle_choices(seed=None) None yes
ds.sort(reverse=False, key=...) None (default key: input length) yes
ds.name, ds.location, ds.shuffled metadata recorded in the log
python
# s06_selection.py: dataset methods, and run-time sample selection with eval().
from inspect_ai import Task, eval
from inspect_ai.dataset import FieldSpec, json_dataset

spec = FieldSpec(input="text", target="category", id="ticket_id",
                 metadata=["intent", "edge", "plan"])
ds = json_dataset("data/tickets.jsonl", spec)
print("all:", [s.id for s in ds], "| count:", len(ds))

# filter() returns a NEW dataset; slicing too. shuffle()/sort() work IN PLACE.
billing = ds.filter(lambda s: s.metadata["intent"] == "billing", name="tickets-billing")
print("filter:", [s.id for s in billing], "| name:", billing.name, "| original untouched:", len(ds))
print("slice [2:5]:", [s.id for s in ds[2:5]])
ds.sort()                                   # default key: input length, shortest first
print("sort (by input length):", [s.id for s in ds])
ds.shuffle(seed=7)
print("shuffle(seed=7):", [s.id for s in ds], "| shuffled flag:", ds.shuffled)

# Run-time selection: limit, a range, explicit ids, a glob and a shuffle.
def selected(**kwargs) -> list:
    fresh = json_dataset("data/tickets.jsonl", spec)
    log = eval(Task(dataset=fresh), model="mockllm/model", log_dir="logs",
               display="none", **kwargs)[0]
    return [s.id for s in log.samples]

print("limit=3:", selected(limit=3))
print("limit=(2, 5):", selected(limit=(2, 5)))
print("sample_id=['T07','T02']:", selected(sample_id=["T07", "T02"]))
print("sample_id='T0[1-3]':", selected(sample_id="T0[1-3]"))
print("sample_shuffle=3, limit=3:", selected(sample_shuffle=3, limit=3))
print("sample_shuffle=4, limit=3:", selected(sample_shuffle=4, limit=3))
Output · real11 lines
all: ['T01', 'T02', 'T03', 'T04', 'T05', 'T06', 'T07', 'T08'] | count: 8
filter: ['T01', 'T08'] | name: tickets-billing | original untouched: 8
slice [2:5]: ['T03', 'T04', 'T05']
sort (by input length): ['T07', 'T06', 'T04', 'T02', 'T03', 'T05', 'T08', 'T01']
shuffle(seed=7): ['T08', 'T01', 'T04', 'T03', 'T07', 'T02', 'T06', 'T05'] | shuffled flag: True
limit=3: ['T01', 'T02', 'T03']
limit=(2, 5): ['T03', 'T04', 'T05']
sample_id=['T07','T02']: ['T02', 'T07']
sample_id='T0[1-3]': ['T01', 'T02', 'T03']
sample_shuffle=3, limit=3: ['T01', 'T06', 'T08']
sample_shuffle=4, limit=3: ['T02', 'T06', 'T07']

The first half of the output is the methods. filter() and slicing leave the original alone; sort() and shuffle() reorder it in place, and shuffled becomes True (the log records that flag). The sort() default is input length, shortest first, which is occasionally useful for smoke tests ("run the five shortest cases") and dangerous for anything else, because short inputs are rarely representative.

4.2 Shuffling at load time#

All loaders take shuffle and seed. An integer shuffle is the seed (shuffle=0 shuffles with seed 0; it does not mean "off"); shuffle=True with no seed gives a different order every run. Shuffling and limit together are how you take a random subset rather than the first N rows. A load-time shuffle happens before ids are assigned at run time, which is exactly the trap in 2.4 (unless you use auto_id=True or explicit ids).

When should you shuffle at all? Not for the result: a full run's accuracy does not depend on order. You shuffle when you will look at a subset (with limit), when order could matter to the system under test (a stateful solver, a cache, a rate limiter that slows the second half), and when you want the first samples a viewer sees to be representative rather than "the first 20 rows the labeller wrote, all about billing".

4.3 Run-time selection: --limit, --sample-id and --sample-shuffle#

The second half of the output above is selection at run time, without touching the task:

Python eval() CLI What it selects
limit=3 --limit 3 The first 3 samples
limit=(2, 5) --limit 3-5 A range. Python takes a 0-based slice ((2, 5) is positions 2, 3, 4: T03 to T05); the CLI takes 1-based inclusive numbers (3-5 is the same three samples). Part 8.3's run of --limit 2-3 is recorded in the log as limit=(1, 3)
sample_id=["T07", "T02"] --sample-id T07,T02 Those ids (the log lists samples in id order)
sample_id="T0[1-3]" --sample-id 'T0[1-3]' A glob over the ids' visible string form
sample_shuffle=3 --sample-shuffle 3 Shuffle with seed 3 before limit applies
sample_shuffle=True --sample-shuffle Shuffle with a fresh random seed

Glob rules (from the datasets page): patterns match the visible string form of ids, so for ids 1, 2, 10 and 11, '1*' selects 1, 10 and 11; exact numeric selectors normalize (5, "5" and "05" select the same sample); an id that equals the selector literally is matched before the selector is treated as a glob, so ids containing [ or ? can still be selected directly. Quote globs in the shell, or the shell expands them against file names first.

These options live only on eval() and the CLI, never on the Task: a task describes what the eval is, and "just the first 50 today" is a property of one run. The log records them (eval.config.limit, sample_id, sample_shuffle), so a reader can tell a partial run from a full one. 10B.12 uses them with eval sets; the VS Code extension's "Debug Task" button adds --limit 1 for you.

4.4 Multiple-choice data and choice shuffling#

A multiple-choice sample has choices (option texts, no letters) and a target letter or list of letters. The multiple_choice() solver formats the question, calls the model and parses the answer; the choice() scorer checks it (the solver is covered in 6.7, the scorer in 10B.10). Here is the whole flow with a scripted model that always picks the option reading "30 days", wherever it sits:

python
# s07_multiple_choice.py: multiple_choice() prompts, choice shuffling and what gets logged.
from inspect_ai import Task, eval
from inspect_ai.dataset import MemoryDataset, Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import choice
from inspect_ai.solver import multiple_choice

SENT: list[str] = []

def pick_refund_window(input, tools, tool_choice, config):
    """A 'model' that always picks the option whose text is '30 days', wherever it sits."""
    prompt = input[-1].text
    SENT.append(prompt)
    for line in prompt.splitlines():
        if line.endswith(") 30 days"):
            return ModelOutput.from_content(model="mockllm", content=f"ANSWER: {line[0]}")
    return ModelOutput.from_content(model="mockllm", content="ANSWER: A")

def question() -> Sample:
    return Sample(id="refund-window", input="How long do customers have to request a refund?",
                  choices=["7 days", "14 days", "30 days", "90 days"], target="C")

def run(dataset, **solver_args):
    model = get_model("mockllm/model", custom_outputs=pick_refund_window, memoize=False)
    log = eval(Task(dataset=dataset, solver=multiple_choice(**solver_args), scorer=choice()),
               model=model, log_dir="logs", display="none")[0]
    s = log.samples[0]
    sc = s.scores["choice"]
    return s, sc

# 1. The default single-answer prompt, exactly as sent.
s, sc = run([question()])
print("=== prompt sent (default template)\n" + SENT[-1])
print("=== verdict:", sc.value, "| answer:", sc.answer)

# 2. Shuffle the choices with a seed: the target letter is rewritten to follow '30 days'.
ds = MemoryDataset([question()])
ds.shuffle_choices(seed=5)
print("\n=== after shuffle_choices(seed=5): choices", ds[0].choices, "target", ds[0].target)
s, sc = run(ds)
print("logged choices:", s.choices, "| logged target:", s.target, "| verdict:", sc.value, "| answer:", sc.answer)

# 3. cot=True and multiple_correct=True switch to the other built-in templates.
run([question()], cot=True)
print("\n=== prompt sent (cot=True)\n" + SENT[-1])
multi = Sample(input="Which plans include SSO?", choices=["Free", "Pro", "Team", "Enterprise"],
               target=["C", "D"])
run([multi], multiple_correct=True)
print("\n=== prompt sent (multiple_correct=True)\n" + SENT[-1])
Output · real33 lines
=== prompt sent (default template)
Answer the following multiple choice question. The entire content of your response should be of the following format: 'ANSWER: $LETTER' (without quotes) where LETTER is one of A,B,C,D.

How long do customers have to request a refund?

A) 7 days
B) 14 days
C) 30 days
D) 90 days
=== verdict: C | answer: C

=== after shuffle_choices(seed=5): choices ['7 days', '14 days', '90 days', '30 days'] target D
logged choices: ['7 days', '14 days', '90 days', '30 days'] | logged target: D | verdict: C | answer: D

=== prompt sent (cot=True)
Answer the following multiple choice question. The last line of your response should be of the following format: 'ANSWER: $LETTER' (without quotes) where LETTER is one of A,B,C,D. Think step by step before answering.

How long do customers have to request a refund?

A) 7 days
B) 14 days
C) 30 days
D) 90 days

=== prompt sent (multiple_correct=True)
Answer the following multiple choice question where multiple answers may be correct. The entire content of your response should be of the following format: 'ANSWER: $LETTERS' (without quotes) where LETTERS is one or more of A,B,C,D.

Which plans include SSO?

A) Free
B) Pro
C) Team
D) Enterprise

What happened in the second block, the one that matters:

  1. shuffle_choices(seed=5) reordered the options to ['7 days', '14 days', '90 days', '30 days'] and rewrote the target from C to D, because "30 days" is now the fourth option.
  2. The scripted model answered D (the letter of "30 days" in the shuffled prompt) and scored C (correct). The answer recorded is D.
  3. The log stores the shuffled choices and the shuffled target. Every letter in that log refers to the shuffled order.

Why shuffle at all: models have position biases (a preference for the first option, or for "C"), and a dataset written by people often has an uneven distribution of correct letters. Shuffling with a fixed seed breaks the correlation between position and correctness while keeping the run reproducible. Shuffling with a different seed per epoch, or per model, adds variance; with a fixed seed every model sees the same order. Two cautions:

  • Shuffle once, at load time (json_dataset(..., shuffle_choices=42) or dataset.shuffle_choices(seed=42)). shuffle_choices=True (and shuffle_choices() with no seed) is unseeded: every run, and every eval_retry() or eval-set re-run that re-imports the task, gets a different letter order and different targets, so always pass an integer. The old multiple_choice(shuffle=True) argument is deprecated (Part 12).
  • Options that refer to other options ("All of the above", "Both A and B", "None of these") stop making sense when moved. Fix the data (rewrite them, or keep such items out of the shuffled set) before shuffling.

When comparing letters across runs or models, compare the option text each letter pointed to, or use the same seed everywhere; a letter-level diff between two differently shuffled logs is meaningless.


Part 5: The solver protocol and TaskState#

5.1 What a solver is, exactly#

text
class Solver(Protocol):
    async def __call__(self, state: TaskState, generate: Generate) -> TaskState: ...

A solver is an async function that takes the current TaskState and a generate function, does something, and returns the state. In practice you never write the bare function: you write a solver factory, a normal def decorated with @solver, which takes configuration arguments and returns the async solve function:

python
from inspect_ai.solver import Generate, Solver, TaskState, solver

@solver
def prefix(text: str = "Answer briefly.") -> Solver:          # the factory: plain def, takes config
    async def solve(state: TaskState, generate: Generate) -> TaskState:   # the solver: async
        state.user_prompt.text = f"{text}\n\n{state.user_prompt.text}"
        return state
    return solve

The @solver decorator does three jobs:

  1. Registers the factory by name, so --solver prefix -S text=... can rebuild it from the command line, and eval_retry() and inspect score can rebuild the task later (10B.12).
  2. Records the arguments the factory was called with. They appear in the log as plan.steps[].params (Part 6.8 prints them), which is how a log tells you which prompt template or which max_attempts produced a number.
  3. Checks that the factory returned an async callable, and raises TypeError if not.

The third check is the one you will hit. From s09_custom_solvers.py (Part 7.1), a factory whose inner function is a plain def:

text
sync solve -> TypeError: is not declared as an async callable.

5.2 TaskState, member by member#

Here is what a solver sees at the start of a sample, printed by the first section of s09_custom_solvers.py:

text
sample_id: T03 | epoch: 1 | model: mockllm/model
input: 'How do I add a second admin?' | input_text: 'How do I add a second admin?'
messages: [('user', 'How do I add a second admin?')]
user_prompt: 'How do I add a second admin?' | target: account
metadata: {'plan': 'team'} | choices: []
output before generate: '' | completed: False
limits: 10 None | tools: []
Member Read/write What it is
messages read/write list The conversation so far. Starts as the sample input; generate() appends to it; prompt solvers insert into it. This is what the model receives
user_prompt read/write The last user message (raises if there is none). user_prompt.text handles both string and multimodal content
output read/write A ModelOutput: the "final" answer. generate() sets it; scorers usually read state.output.completion. Empty before the first generate
input read only (by convention) The original sample input, untouched by solvers ("should be considered immutable")
input_text read only The original input as text (for a message list: the last user message)
target read only The sample's Target
choices read/write The multiple-choice options; multiple_choice() marks the ones the model picked
metadata, metadata_as() read (by convention) The sample metadata (2.5)
store, store_as() read/write Per-sample scratch space that is logged (7.5)
scores read/write Scores a solver may set; merged with the scorers' results (7.6)
completed read/write Set True to skip the remaining solvers (7.4)
sample_id, epoch, uuid read only Identity of this run of this sample
model read only The ModelName of the model under test
tools, tool_choice read/write Tools offered to the model (10B.14)
message_limit, token_limit, token_limit_type, token_usage, cost_limit, cost_usage read/write Limits and usage for this sample (10B.15)

The distinction between input and messages is the one to internalize. input is the case; messages is what you are about to send. A solver chain can rewrite the prompt, add a system message, add few-shot turns or drop messages; input keeps the original so that a scorer or a later solver can still see what the user actually asked. 6.8 shows self_critique() relying on exactly that.

output is a ModelOutput with fields including model, choices, completion (the text), usage, stop_reason and error. Solvers can build one without calling a model: ModelOutput.from_content(model="rule", content="..."), which is how the early-exit solver in 7.4 and the control solvers in 10.1 work.

5.3 generate and the tool-call modes#

text
class Generate(Protocol):
    async def __call__(self, state: TaskState,
                       tool_calls: Literal["loop", "single", "none"] = "loop",
                       **kwargs: Unpack[GenerateConfigArgs]) -> TaskState: ...

The generate passed to your solver calls the model under test with state.messages, appends the assistant message, sets state.output and returns the state. tool_calls only matters when tools are offered: "loop" (default) runs tool calls and generates again until the model stops calling tools or a limit is hit; "single" resolves one round; "none" resolves none and leaves them to you. Any GenerateConfig field can be passed per call: await generate(state, max_tokens=200) or generate(cache=True) as a solver. 10B.14 covers the tool loop and 10B.12 the config fields.

Always await it. An un-awaited generate(state) returns a coroutine, the model is never called, and Python warns about a coroutine that was never awaited while your solver returns a state with no answer.


Part 6: The built-in solvers#

inspect_ai.solver exports 25 names in 0.3.292. The non-agent solvers are covered here: generate, system_message, user_message, assistant_message, prompt_template, chain_of_thought, multiple_choice, self_critique, chain and fork. use_tools, basic_agent, human_agent, bridge and the agent API are 10B.14's; plan/Plan are legacy (Part 12); empty_attempt is a no-op solver used when zeroing samples in a log (10B.13).

6.1 generate()#

generate(tool_calls="loop", **GenerateConfigArgs) is the whole solver body return await generate(state, ...), and it is the default: a Task with no solver sends each sample to the model once. Pass config per step when one step needs different settings, for example generate(max_tokens=50) for a classification step after a long reasoning step.

6.2 system_message(), user_message(), assistant_message()#

Solver What it does
system_message(template, **params) Inserts a system message after the last existing system message, or at the start if there is none
user_message(template, **params) Appends a user message at the end
assistant_message(template, **params) Appends an assistant message at the end (a prefill or a scripted turn)

All three render template with the substitution rules of 6.5, and template can be a literal string, a file path or a URL (read with resource()). The prompt-solver demo captures exactly what a scripted model receives:

python
# s05_templates.py: what the template solvers actually send, captured from a mock model.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageSystem, ChatMessageUser, ModelOutput, get_model
from inspect_ai.solver import (Generate, Solver, TaskState, assistant_message,
                               chain_of_thought, generate, prompt_template, solver,
                               system_message, user_message)

SENT: list[list[tuple[str, str]]] = []

def capture(input, tools, tool_choice, config):
    SENT.append([(m.role, m.text) for m in input])        # what the provider would receive
    return ModelOutput.from_content(model="mockllm", content="ok")

def run(sample: Sample, solvers: list, title: str) -> None:
    model = get_model("mockllm/model", custom_outputs=capture, memoize=False)
    eval(Task(dataset=[sample], solver=[*solvers, generate()]),
         model=model, log_dir="logs", display="none")
    print(f"--- {title}")
    for role, text in SENT[-1]:
        print(f"  {role:9} | {text!r}")

meta = {"company": "Acme Cloud", "plan": "pro", "tone": None}

# 1. Placement: system_message goes AFTER existing system messages, BEFORE the user turn.
run(Sample(input=[ChatMessageSystem(content="Policy v3 applies."),
                  ChatMessageUser(content="My invoice is wrong")], metadata=meta),
    [system_message("prompts/system.txt")],                # a file path is read with resource()
    "system_message after an existing system message")

# 2. user_message / assistant_message append; prompt_template rewrites the LAST user message.
run(Sample(input="refund please", metadata=meta),
    [prompt_template("Ticket for {company}:\n{prompt}"),
     assistant_message("Understood. One question first:"),
     user_message("Reply in a {tone} tone. Unknown: {nope}")],
    "prompt_template, assistant_message, user_message")

# 3. Precedence: solver params beat store values, which beat sample metadata.
@solver
def remember_plan() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state.store.set("plan", "team (from store)")
        return state
    return solve

run(Sample(input="hi", metadata=meta),
    [remember_plan(), system_message("plan={plan} company={company}", company="Param Co")],
    "metadata < store < params")

# 4. JSON braces in a template are parsed as placeholders.
run(Sample(input="refund please", metadata=meta),
    [system_message('Reply with JSON only: {"category": "billing"}')],
    "single-level JSON braces")
run(Sample(input="refund please", metadata=meta),
    [system_message('Reply with JSON only: {{"category": "billing"}}')],
    "doubled braces")
try:
    run(Sample(input="refund please", metadata=meta),
        [system_message('Schema: {"ticket": {"category": "billing"}}')],
        "nested JSON braces")
except Exception as e:
    print("--- nested JSON braces\n  ->", type(e).__name__ + ":", e)

# 5. chain_of_thought substitutes only {prompt}; metadata placeholders stay as written.
run(Sample(input="Which plan am I on?", metadata=meta),
    [chain_of_thought("{prompt}\nCustomer plan: {plan}. Think step by step.")],
    "chain_of_thought custom template")

The template file prompts/system.txt contains one line: You are the triage assistant for {company}. Tickets come from the {plan} plan. Output (real):

text
--- system_message after an existing system message
  system    | 'Policy v3 applies.'
  system    | 'You are the triage assistant for Acme Cloud. Tickets come from the pro plan.\n'
  user      | 'My invoice is wrong'
--- prompt_template, assistant_message, user_message
  user      | 'Ticket for Acme Cloud:\nrefund please'
  assistant | 'Understood. One question first:'
  user      | 'Reply in a {tone} tone. Unknown: {nope}'
--- metadata < store < params
  system    | 'plan=team (from store) company=Param Co'
  user      | 'hi'
--- single-level JSON braces
  system    | 'Reply with JSON only: {{"category"}: "billing"}'
  user      | 'refund please'
--- doubled braces
  system    | 'Reply with JSON only: {"category": "billing"}'
  user      | 'refund please'
--- nested JSON braces
  system    | 'Schema: {{"ticket"}: {{"category"}: "billing"}}'
  user      | 'refund please'
--- chain_of_thought custom template
  user      | 'Which plan am I on?\nCustomer plan: {plan}. Think step by step.'

The first block shows placement. The sample's own system message ("Policy v3 applies.") stays first; the task's system message goes after it and before the user turn. Two system messages in one request are legal in Inspect; how they reach each provider is the provider adapter's business (Anthropic's Messages API, for one, has a single top-level system field, so several system messages have to be combined; 03.2 has the per-provider rules). If the exact system prompt matters to the result, write one combined system prompt yourself.

6.3 assistant_message() and prefill#

The second block shows assistant_message() appending an assistant turn. Used before generate(), a trailing assistant message is a prefill: the model continues from it. Prefill is useful (forcing the reply to start with { for JSON, for example) and provider-dependent: some APIs continue a trailing assistant message, others reject a request that ends with one or treat it as a finished turn. Check the provider before relying on it (04.4 covers prefilling as a prompt technique). Followed by a user_message(), as in the demo, it is simply a scripted earlier turn.

6.4 prompt_template()#

prompt_template(template, **params) rewrites the last user message: {prompt} is replaced by its current text, and other placeholders by metadata, store and parameters. In the demo "Ticket for {company}:\n{prompt}" turned refund please into Ticket for Acme Cloud:\nrefund please. Two details from the source: metadata cannot shadow {prompt} (a metadata key called prompt is dropped before substitution), and it edits the last user message wherever it is, so with a multi-turn input it rewrites the final turn only.

6.5 The template rules, and the two silent corruptions#

10B.8, 9.2 showed the brace rule and the misspelt placeholder on a first-day task. Here is the complete rule set. All four template solvers render with Inspect's format_template() in skip-unknown mode. That gives these rules, each visible in the output above:

  1. Sources, in increasing precedence: sample metadata, then the store, then the solver's own **params. In block three, metadata said plan=pro and company=Acme Cloud, the store said plan=team (from store), and the parameter said company=Param Co: the store beat metadata for plan, and the parameter beat metadata for company. (The source merges metadata | store | params, so parameters also beat the store.) (For prompt_template(), {prompt} is the current prompt text.)
  2. A template that names a file is read from the file. system_message("prompts/system.txt") sent the file's contents, rendered.
  3. Unknown placeholders are left in place, silently. {nope} reached the model as {nope}. So did {tone}, because a metadata value of None counts as unknown. A typo in a placeholder name does not raise; it ships literal braces to the model.
  4. chain_of_thought() substitutes only {prompt}. Its template ignores metadata, so {plan} was sent as written (block five).

And the two corruptions, which are worth a separate warning because both pass every test that does not read the prompt:

This is not hypothetical. 10A.10, Part 4.4 passes this system prompt to system_message():

python
# s05b_1010_instructions.py: the system prompt from 10A.10 Part 4.4, as system_message() sends it.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.solver import generate, system_message

INSTRUCTIONS = """Classify this support ticket. Reply with JSON only:
{"category": one of billing|technical|account|shipping|other,
 "priority": one of P1|P2|P3}"""

SENT = []
def capture(input, tools, tool_choice, config):
    SENT.append(input[0].text)
    return ModelOutput.from_content(model="mockllm", content="{}")

model = get_model("mockllm/model", custom_outputs=capture, memoize=False)
eval(Task(dataset=[Sample(input="charged twice, please refund")],
          solver=[system_message(INSTRUCTIONS), generate()]),
     model=model, log_dir="logs", display="none")
print("as written:\n" + INSTRUCTIONS)
print("as sent:\n" + SENT[0])
print("identical:", SENT[0] == INSTRUCTIONS)
Output · real9 lines
as written:
Classify this support ticket. Reply with JSON only:
{"category": one of billing|technical|account|shipping|other,
 "priority": one of P1|P2|P3}
as sent:
Classify this support ticket. Reply with JSON only:
{{"category"}: one of billing|technical|account|shipping|other,
 "priority": one of P1|P2|P3}
identical: False

Every model evaluated with that task was told to reply in a format with a stray brace pair around "category". A model that copies the format literally is penalized for doing what it was told; one that ignores it scores better. That is a measurement artefact, not a capability difference.

python
# s15_resource_typo.py: a template argument that names a missing file is used as literal text.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.solver import generate, system_message

for template in ("prompts/system.txt", "prompts/sytem.txt"):       # the second has a typo
    log = eval(Task(dataset=[Sample(input="hi", metadata={"company": "Acme", "plan": "pro"})],
                    solver=[system_message(template), generate()]),
               model="mockllm/model", log_dir="logs", display="none")[0]
    print(f"{template!r:24} -> system message sent: {log.samples[0].messages[0].text!r}")
Output · real2 lines
'prompts/system.txt'     -> system message sent: 'You are the triage assistant for Acme. Tickets come from the pro plan.\n'
'prompts/sytem.txt'      -> system message sent: 'prompts/sytem.txt'

The model under test received prompts/sytem.txt as its entire system prompt, the run succeeded, and in a real eval the score would drop for a reason no metric will tell you. When a template must come from a file, load it yourself and fail loudly (Path("prompts/system.txt").read_text() raises FileNotFoundError), or call resource(path, type="file") from inspect_ai.util, which refuses to fall back to literal text (a run of s15b_resource_file.py with the misspelt path raised FileNotFoundError: [Errno 2] No such file or directory). Relative paths resolve against the current working directory; when you run inspect eval path/to/task.py, Inspect changes into the task file's directory first, so paths relative to the task file work from the CLI (Part 9 relies on this).

The defence for all of these is the same and is Part 10.2's subject: read the prompt that was actually sent, in the log or in inspect view, for at least one sample of every new task and every prompt change.

6.6 chain_of_thought()#

chain_of_thought(template=DEFAULT_COT_TEMPLATE) rewrites the user prompt. The default template, exactly as sent (from s08_cot_critique.py, Part 6.8):

text
Can I get a refund on the Pro plan?

Before answering, reason in a step-by-step manner as to get the right answer. Provide your answer at the end on its own line in the form "ANSWER: $ANSWER" (without quotes) where $ANSWER is the answer to the question.

It changes the output format as well as the reasoning: the answer now ends with an ANSWER: line after free text. Pair it with a scorer that extracts that line (answer("line") or pattern(), 10B.10); with match() or exact() it usually breaks scoring. That is also why 10A.10's triage task left it out: a strict-JSON task and a reasoning preamble conflict.

Whether explicit chain-of-thought helps is model-dependent. Current reasoning models think by default and gain little or nothing from "think step by step"; some providers advise against it (02.8, 04.3). In an eval, treat it as an elicitation choice you test, not a default you add.

6.7 multiple_choice()#

text
multiple_choice(*, template=None, cot=False, multiple_correct=False, max_tokens=None) -> Solver

It formats the question and the lettered choices with a template, calls generate() itself (do not add another generate() after it), parses the letters from the reply and marks the chosen options in state.choices. Pair it with the choice() scorer, which scores the choices multiple_choice() marked, not the completion text: a solver that writes "ANSWER: A" into state.output without marking a choice scores incorrect on every sample. The three prompts in the output of 4.4 are the built-in templates, available as MultipleChoiceTemplate.SINGLE_ANSWER, SINGLE_ANSWER_COT (cot=True), MULTIPLE_ANSWER (multiple_correct=True) and MULTIPLE_ANSWER_COT (both). A custom template must contain {question}, {choices} and (usually) {letters}; with a custom template, cot and multiple_correct have no effect on the wording, so your template must ask for the right format itself. max_tokens caps the reply (not shown on the solvers page of the docs, but in the installed signature).

The docs page says to "pair this solver with the choices() scorer"; the scorer is choice().

6.8 self_critique()#

text
self_critique(critique_template=None, completion_template=None, model=None) -> Solver

After a first answer it makes two more model calls: one asks a model (the model under test unless you pass model=) to critique the answer, and one asks the model under test to improve its answer given the critique. The demo scripts all three replies and prints what each call received:

python
# s08_cot_critique.py: chain_of_thought() and self_critique() as the model sees them.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.solver import chain_of_thought, generate, self_critique

CALLS: list[list[tuple[str, str]]] = []

def scripted(input, tools, tool_choice, config):
    CALLS.append([(m.role, m.text) for m in input])
    last = input[-1].text
    if "please critique the answer" in last:
        reply = "The answer ignores the 30-day refund window."
    elif "generate an improved answer" in last:
        reply = "Pro plan refunds are allowed within 30 days.\nANSWER: yes, within 30 days"
    else:
        reply = "Refunds are possible.\nANSWER: yes"
    return ModelOutput.from_content(model="mockllm", content=reply)

model = get_model("mockllm/model", custom_outputs=scripted, memoize=False)
sample = Sample(input="Can I get a refund on the Pro plan?", target="within 30 days")

log = eval(Task(dataset=[sample], solver=[chain_of_thought(), generate(), self_critique()]),
           model=model, log_dir="logs", display="none")[0]

for i, call in enumerate(CALLS, 1):
    print(f"===== model call {i}: last message ({call[-1][0]}), {len(call)} message(s) in context")
    print(call[-1][1].strip())
print("===== final output:", repr(log.samples[0].output.completion))
print("===== message roles in the final state:", [m.role for m in log.samples[0].messages])
print("===== plan steps logged:", [(st.solver, st.params) for st in log.plan.steps])
Output · real35 lines
===== model call 1: last message (user), 1 message(s) in context
Can I get a refund on the Pro plan?

Before answering, reason in a step-by-step manner as to get the right answer. Provide your answer at the end on its own line in the form "ANSWER: $ANSWER" (without quotes) where $ANSWER is the answer to the question.
===== model call 2: last message (user), 1 message(s) in context
Given the following question and answer, please critique the answer. A good answer comprehensively answers the question and NEVER refuses to answer. If the answer is already correct do not provide critique - simply respond 'The original answer is fully correct'.

[BEGIN DATA]
***
[Question]: Can I get a refund on the Pro plan?
***
[Answer]: Refunds are possible.
ANSWER: yes
***
[END DATA]

Critique:
===== model call 3: last message (user), 3 message(s) in context
Given the following question, initial answer and critique please generate an improved answer to the question:

[BEGIN DATA]
***
[Question]: Can I get a refund on the Pro plan?
***
[Answer]: Refunds are possible.
ANSWER: yes
***
[Critique]: The answer ignores the 30-day refund window.
***
[END DATA]

If the original answer is already correct, just repeat the original answer exactly. Provide your answer at the end on its own line in the form "ANSWER: $ANSWER" (without quotes) where $ANSWER is the answer to the question.
===== final output: 'Pro plan refunds are allowed within 30 days.\nANSWER: yes, within 30 days'
===== message roles in the final state: ['user', 'assistant', 'user', 'assistant']
===== plan steps logged: [('chain_of_thought', {'template': '\n{prompt}\n\nBefore answering, reason in a step-by-step manner as to get the right answer. Provide your answer at the end on its own line in the form "ANSWER: $ANSWER" (without quotes) where $ANSWER is the answer to the question.\n'}), ('generate', {'tool_calls': 'loop'}), ('self_critique', {'critique_template': None, 'completion_template': None, 'model': None})]

Things to notice:

  • The critique call is a fresh one-message conversation ("1 message(s) in context"). The critic does not see the system prompt or the chain-of-thought wording.
  • The critique shows [Question] as the original input (state.input_text), not the CoT-rewritten prompt. This is the input versus messages distinction of 5.2 at work.
  • The completion request is appended to the main conversation (3 messages: the CoT prompt, the first answer, the improvement request), and the final generate() overwrites state.output.
  • The installed completion template differs from the docs. The solvers page shows it ending with "You should just provide your answer to the question in exactly this format: Answer: ". The installed 0.3.292 template ends with the ANSWER: $ANSWER instruction shown above, consistent with chain_of_thought(). Trust the log, not the page.
  • The plan records every step and its parameters, including the full CoT template text and self_critique's None defaults, which is what makes the run reproducible from the log alone.

Methodology: self-critique triples the calls per sample and can make answers worse (a confident wrong critique talks the model out of a right answer). The fair test is an A/B on the same dataset and seed with and without it, paired by sample id (10A.8). Note also that the default critique template asks for answers that "NEVER refuse": on a task where refusing is the correct behaviour, that pushes in the wrong direction. Supply your own critique_template when that matters.

6.9 chain() and solver lists#

Task(solver=[a, b, c]) chains the list automatically. chain(a, b, c) (or chain([a, b, c])) does the same and returns a single solver, which you need when a solver factory should return a composite:

python
from inspect_ai.solver import Solver, chain, generate, prompt_template, solver, system_message

@solver
def triage_prompting(system: str = "prompts/system.txt") -> Solver:
    return chain(
        system_message(system),
        prompt_template("Ticket:\n{prompt}"),
        generate(),
    )

A registered composite like this can be swapped in as one unit with --solver triage_prompting (8.3), and it appears in the log as its constituent steps. A chain stops early when a solver sets state.completed = True.

6.10 fork()#

fork(state, solvers) (an async function, not a solver) deep-copies the state and runs each solver on its own copy, in parallel, each in its own subtask with an independent store and transcript. It returns one TaskState per solver (or one state for a single solver). From s10_setup_cleanup_fork.py (Part 7.8):

text
branch system prompts: ['Be formal.', 'Be casual.'] | branch roles: ['system', 'user', 'assistant'] | parent messages untouched: ['user']
fork outside a running task -> Called fork() outside of a running task.

Use it for best-of-n strategies, comparing elicitation variants within one sample, or running sub-strategies in parallel. You decide what to do with the branches (pick one by a rule or a grader, merge their outputs); the parent state is untouched until you copy something into it. It must be awaited inside a running sample, otherwise it raises the RuntimeError shown.

6.11 The built-in solvers at a glance#

Solver Calls the model? Changes Pairs with
generate() yes appends the reply, sets output any scorer
system_message() no inserts a system message after existing ones
user_message() no appends a user message
assistant_message() no appends an assistant message (prefill or scripted turn)
prompt_template() no rewrites the last user message ({prompt})
chain_of_thought() no rewrites the last user message, asks for an ANSWER: line answer("line"), pattern()
multiple_choice() yes, itself formats choices, parses letters, marks choices choice()
self_critique() yes, twice appends critique request and new answer same scorer as before
chain() depends composes solvers
fork() (function) depends runs solvers on copies your own selection logic

Part 7: Writing your own solvers#

7.1 A tour in one file#

The built-ins cover prompting; anything specific to your system (retrieval, a repair loop, a scripted user, a policy check before the model is called) is a custom solver. This file exercises the main mechanics: the TaskState tour already shown in 5.2, the async rule from 5.1, early termination, the store and model roles.

python
# s09_custom_solvers.py: the Solver protocol, TaskState, early termination, Store and roles.
from pydantic import Field

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver
from inspect_ai.util import StoreModel, store_as

# --- 1. What a solver receives: a tour of TaskState at the start of a sample.
@solver
def inspect_state() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        print("sample_id:", state.sample_id, "| epoch:", state.epoch, "| model:", state.model)
        print("input:", repr(state.input), "| input_text:", repr(state.input_text))
        print("messages:", [(m.role, m.text) for m in state.messages])
        print("user_prompt:", repr(state.user_prompt.text), "| target:", state.target.text)
        print("metadata:", state.metadata, "| choices:", list(state.choices))
        print("output before generate:", repr(state.output.completion), "| completed:", state.completed)
        print("limits:", state.message_limit, state.token_limit, "| tools:", state.tools)
        return state
    return solve

eval(Task(dataset=[Sample(id="T03", input="How do I add a second admin?", target="account",
                          metadata={"plan": "team"})],
          solver=[inspect_state(), generate()], message_limit=10),
     model="mockllm/model", log_dir="logs", display="none")

# --- 2. The factory must return an ASYNC function.
@solver
def sync_by_mistake() -> Solver:
    def solve(state, generate):
        return state
    return solve

try:
    sync_by_mistake()
except TypeError as e:
    print("\nsync solve -> TypeError:", str(e).split("'")[-1].strip())

# --- 3. state.completed = True skips the remaining solvers (including generate()).
@solver
def skip_empty() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        if not state.input_text.strip():
            state.output = ModelOutput.from_content(model="rule", content='{"category": "other"}')
            state.completed = True
        return state
    return solve

log = eval(Task(dataset=[Sample(id="empty", input=" "), Sample(id="real", input="refund")],
                solver=[skip_empty(), generate()]),
           model="mockllm/model", log_dir="logs", display="none")[0]
print("\nearly exit:", [(s.id, s.output.completion, [m.role for m in s.messages]) for s in log.samples])

# --- 4. Store and StoreModel: per-sample state that is logged with the sample.
class Attempts(StoreModel):
    tries: int = Field(default=0)
    reasons: list[str] = Field(default_factory=list)

@solver
def count_attempts() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        attempts = store_as(Attempts)
        for reason in ("first draft", "retry: invalid JSON"):
            attempts.tries += 1
            attempts.reasons.append(reason)
            state = await generate(state)
        return state
    return solve

log = eval(Task(dataset=[Sample(id="s1", input="x")], solver=count_attempts()),
           model="mockllm/model", log_dir="logs", display="none")[0]
print("\nstore logged with the sample:", log.samples[0].store)

# --- 5. Model roles resolve when solve() runs, not when the task is built.
def as_role(text: str):
    return get_model("mockllm/model", memoize=False,
                     custom_outputs=lambda i, t, tc, c: ModelOutput.from_content(model="m", content=text))

@solver
def ask_rewriter() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        rewriter = get_model(role="rewriter")         # resolved inside the running sample
        out = await rewriter.generate(f"Rewrite politely: {state.input_text}")
        state.user_prompt.text = out.completion
        return await generate(state)
    return solve

log = eval(Task(dataset=[Sample(input="where is my refund")], solver=ask_rewriter()),
           model="mockllm/model", model_roles={"rewriter": as_role("Could you check my refund?")},
           log_dir="logs", display="none")[0]
print("\nrole-bound rewrite sent to the model under test:", [m.text for m in log.samples[0].messages][0])
print("role usage logged:", list(log.stats.role_usage))
Output · real16 lines
sample_id: T03 | epoch: 1 | model: mockllm/model
input: 'How do I add a second admin?' | input_text: 'How do I add a second admin?'
messages: [('user', 'How do I add a second admin?')]
user_prompt: 'How do I add a second admin?' | target: account
metadata: {'plan': 'team'} | choices: []
output before generate: '' | completed: False
limits: 10 None | tools: []

sync solve -> TypeError: is not declared as an async callable.

early exit: [('empty', '{"category": "other"}', ['user']), ('real', 'Default output from mockllm/model', ['user', 'assistant'])]

store logged with the sample: {'Attempts:instance': None, 'Attempts:tries': 2, 'Attempts:reasons': ['first draft', 'retry: invalid JSON']}

role-bound rewrite sent to the model under test: Could you check my refund?
role usage logged: ['rewriter']

The sections below take the pieces one at a time.

7.2 Three solver patterns you will actually write#

Most custom solvers in product evals fall into three shapes:

Pattern What it does Example
Context builder Puts something into the conversation before generate(): retrieved passages, a customer record, few-shot examples chosen per sample with_context() below; the RAG evals of 10A.6
Validate and repair Calls the model, checks the reply, and asks again with feedback, within a budget generate_with_repair() in Part 9
Scripted interaction Plays the other side of a conversation from data, so a multi-turn behaviour can be measured follow_up_turns() below; simulators in 10A.12
python
# s19_solver_patterns.py: two solver patterns, a RAG context injector and a scripted follow-up turn.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageUser, ModelOutput, get_model
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver, system_message

# A stand-in for docs_qa's retriever (Module 07). In a real eval this calls your search index,
# or the dataset carries pre-retrieved passages so retrieval is held fixed.
DOCS = {
    "refund": "Refunds: Pro and Team plans can be refunded within 30 days of purchase.",
    "sso": "SSO: available on the Enterprise plan only.",
}

def retrieve(question: str, k: int = 2) -> list[str]:
    return [text for key, text in DOCS.items() if key in question.lower()][:k]


@solver
def with_context(k: int = 2) -> Solver:
    """Retrieve passages for the question and put them in front of it, numbered for citation."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        passages = state.metadata.get("contexts") or retrieve(state.input_text, k)
        state.store.set("contexts", passages)                 # logged: what the model was given
        numbered = "\n".join(f"[{i}] {p}" for i, p in enumerate(passages, 1)) or "(no passages found)"
        state.user_prompt.text = f"Passages:\n{numbered}\n\nQuestion: {state.input_text}"
        return state
    return solve


@solver
def follow_up_turns() -> Solver:
    """Play scripted customer follow-ups from metadata; the model answers each one."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state = await generate(state)
        for turn in state.metadata.get("follow_ups", []):
            state.messages.append(ChatMessageUser(content=turn))
            state = await generate(state)
        return state
    return solve


def scripted(input, tools, tool_choice, config):
    last = input[-1].text
    reply = ("Yes, within 30 days [1]." if "Passages" in last
             else "It is under Billing > Invoices." if "invoice" in last
             else "Happy to help.")
    return ModelOutput.from_content(model="mockllm", content=reply)

model = get_model("mockllm/model", custom_outputs=scripted, memoize=False)

log = eval(Task(dataset=[Sample(id="q1", input="Can I get a refund on Pro?")],
                solver=[system_message("Answer only from the passages. Cite them as [n]."),
                        with_context(), generate()]),
           model=model, log_dir="logs", display="none")[0]
s = log.samples[0]
print("RAG prompt sent:", repr(s.messages[1].text))
print("contexts in store:", s.store["contexts"], "| answer:", s.output.completion)

log = eval(Task(dataset=[Sample(id="c1", input="Hi, quick question about billing.",
                                metadata={"follow_ups": ["Where do I find my invoice?", "Thanks!"]})],
                solver=follow_up_turns()),
           model=model, log_dir="logs", display="none")[0]
print("conversation:", [(m.role, m.text) for m in log.samples[0].messages])
Output · real3 lines
RAG prompt sent: 'Passages:\n[1] Refunds: Pro and Team plans can be refunded within 30 days of purchase.\n\nQuestion: Can I get a refund on Pro?'
contexts in store: ['Refunds: Pro and Team plans can be refunded within 30 days of purchase.'] | answer: Yes, within 30 days [1].
conversation: [('user', 'Hi, quick question about billing.'), ('assistant', 'Happy to help.'), ('user', 'Where do I find my invoice?'), ('assistant', 'It is under Billing > Invoices.'), ('user', 'Thanks!'), ('assistant', 'Happy to help.')]

Points of method in that code:

  • The retriever result is written to the store, so the log shows which passages the model saw. When a RAG answer is wrong, the first question is always "was the evidence there?", and a log without the contexts cannot answer it (10A.6 separates retrieval and generation failures this way).
  • state.metadata.get("contexts") or retrieve(...): a dataset can carry pre-retrieved passages, which holds retrieval fixed so that you measure the generator alone, or omit them, so that the eval measures the whole pipeline. Decide which question your eval answers and make it a task argument.
  • The scripted user turns come from metadata, so each case defines its own conversation. The model's replies are generated; the user's are not. That is a fixed script, not a simulated user: it cannot react to what the model said. Use it for "does the assistant handle this follow-up", and a simulator when the user's next turn should depend on the assistant's last one.

7.3 Models inside solvers#

Inside solve(), get_model() returns:

Call Returns
get_model() The model under test
get_model("provider/model") A specific model (a critic, a rewriter, a user simulator)
get_model(role="rewriter") The model bound to that role for this run, else the run's default model, or the default= you pass; required=True raises if unbound
get_model(..., config=GenerateConfig(...)) The same, with its own generation settings

Section 5 of the tour bound a role with eval(model_roles={"rewriter": ...}) and the solver resolved it at run time; the log recorded the role's usage separately (role usage logged: ['rewriter']). Three rules follow from how roles are resolved:

  1. Call get_model(role=...) inside solve(), not in the factory. The factory runs when the task is built, before eval() has bound any roles. This probe looks the role up in both places:
python
# s09b_role_in_factory.py: a role looked up in the factory versus inside solve().
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.solver import Generate, Solver, TaskState, solver

@solver
def who_is_rewriter() -> Solver:
    early = get_model(role="rewriter")                  # factory: runs when the task is built
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        late = get_model(role="rewriter")               # solve: runs inside the sample
        print("factory-time lookup:", early.name, "| solve-time lookup:", late.name)
        return state
    return solve

rewriter = get_model("mockllm/rewriter", memoize=False,
                     custom_outputs=lambda i, t, tc, c: ModelOutput.from_content(model="r", content="x"))
try:
    task = Task(dataset=[Sample(input="hi")], solver=who_is_rewriter())
    eval(task, model="mockllm/model", model_roles={"rewriter": rewriter},
         log_dir="logs", display="none")
except Exception as e:
    print("factory-time lookup ->", type(e).__name__ + ":", str(e)[:100])
Output · real; the second run sets INSPECT_EVAL_MODEL in the shell3 lines
factory-time lookup -> ValueError: No model specified (and no model environment variable defined)
--- with INSPECT_EVAL_MODEL=mockllm/model set in the environment:
factory-time lookup: model | solve-time lookup: rewriter

With no default model configured, the factory-time lookup raises. Worse, with INSPECT_EVAL_MODEL set (as it often is in a .env file), it silently returns the default model (model) instead of the role (rewriter), while the lookup inside solve() gets the role right. (The docs' own source listing of self_critique() resolves its model in the factory; the installed solver resolves it inside solve(), which is the version to copy.) 2. await every model call (await model.generate(...)), so the call joins Inspect's scheduler and its concurrency limits. 3. get_model() is memoized: identical arguments return the same Model object for real providers. (mockllm models are never memoized in inspect-ai 0.3.292, so the memoize=False in the keyless samples is harmless but unneeded; see 10B.12, 2.4.)

Calls made by other models are part of the sample's transcript and token accounting, so a solver that calls a big critic model on every sample shows up in the cost of the run. Model roles, GenerateConfig and provider strings in depth are 10B.12.

7.4 Ending a sample early: state.completed#

Section 3 of the tour: skip_empty() answers empty tickets with a fixed rule, sets state.output itself and sets state.completed = True. The generate() that follows in the chain is skipped for that sample (its messages contain only the user turn) and runs normally for the other. Scorers still run on the completed sample. Use it when a case can be decided without the model (a guard rule you are evaluating), when an agent has finished, or when a sample has become pointless. Limits (message_limit and friends) end samples the same way, recording which limit was hit (10B.15).

7.5 Per-sample state: Store and StoreModel#

Every sample gets its own store (from inspect_ai.util), a key-value scratchpad that solvers, tools and scorers share for that sample and that is written to the log (EvalSample.store), with each change recorded as a store event in the transcript.

API Use
state.store.get(key, default), .set(key, value), .delete(key), .keys(), .items() Untyped access from a solver
store() The current sample's store from anywhere (a tool, a helper function)
StoreModel subclass + store_as(Model) or state.store_as(Model) Typed, validated access; give every field a default (Field(default=...) or default_factory)
store_as(Model, instance="red_team") A separate namespace, so two agents or two uses of one model do not collide

Section 4 of the tour shows the typed form: the log stores the fields under Attempts:tries and Attempts:reasons (class name, colon, field), plus Attempts:instance. Two more facts from Part 6: the template solvers substitute store values, and the store beats metadata when both have the key.

Store versus metadata versus a module-level variable:

Data Put it in
Facts about the case, fixed before the run metadata
Values produced during this sample (attempts, retrieved contexts, intermediate answers) the store
Anything shared across samples nothing mutable: samples run concurrently (7.7)

7.6 Scores from solvers#

A solver may set state.scores = {"name": Score(...)}; those scores are merged with the task's scorers' results. A solver may also call the in-solver score(state) function (imported from inspect_ai.scorer) to run the task's scorers on the current state, for example to decide whether to try again. Both are covered in 10B.10; the rule for this lesson is that a solver that peeks at the target or the scorer to choose its answer is measuring something other than the model. If your solver must, report the result as pass@k or as "with oracle feedback", never as plain accuracy.

7.7 Concurrency rules#

Inspect runs many samples at once on one event loop. A solver that blocks the loop stalls every sample:

  • Never do blocking work in solve(): no time.sleep(), no requests.get(), no long CPU loops. Use await anyio.sleep(), an async HTTP client (httpx.AsyncClient), and for external processes subprocess() from inspect_ai.util, which is async and respects max_subprocesses. Inspect's parallelism page covers the details.
  • Never share mutable state across samples: a module-level list that solvers append to, a shared iterator, a counter. Sample order is not fixed under concurrency, so results depend on scheduling. (The keyless samples in this lesson append to module-level lists only to print what was sent, in single-sample runs.)
  • Scripted mocks should be keyed on the input, as every mock in this lesson is: a callable that looks at the prompt, not an iterator handed out in scheduling order.

7.8 setup and cleanup#

Task(setup=...) takes a solver (or list) that always runs before the main solver, even when the main solver is replaced at run time. Task(cleanup=...) takes an async def cleanup(state) that runs after the solvers and scorers of each sample, including when the sample raised.

python
# s10_setup_cleanup_fork.py: setup survives a solver swap, cleanup runs on errors, fork() branches.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.solver import (Generate, Solver, TaskState, fork, generate, solver,
                               system_message)

EVENTS: list[str] = []

@solver
def load_policy() -> Solver:
    """Setup step every solver needs: put the refund policy into the store."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state.store.set("policy", "Refunds within 30 days.")
        EVENTS.append(f"setup {state.sample_id}")
        return state
    return solve

@solver
def terse() -> Solver:
    return system_message("Answer in one line. Policy: {policy}")

@solver
def explode_on(sample_id: str) -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        if state.sample_id == sample_id:
            raise RuntimeError("tool backend unavailable")
        return await generate(state)
    return solve

async def release(state: TaskState) -> None:          # cleanup must be async
    EVENTS.append(f"cleanup {state.sample_id}")

def task() -> Task:
    return Task(dataset=[Sample(id="a", input="refund?"), Sample(id="b", input="refund now")],
                setup=load_policy(), solver=[terse(), explode_on("b")], cleanup=release)

# 1. Default solver chain; sample b raises. fail_on_error=False keeps the run going.
log = eval(task(), model="mockllm/model", log_dir="logs", display="none", fail_on_error=False)[0]
print("status:", log.status, "| errors:", [(s.id, str(s.error.message) if s.error else None) for s in log.samples])
print("events:", sorted(EVENTS))

# 2. Swap the main solver at run time: setup still runs, the swapped-in chain replaces the rest.
EVENTS.clear()
log = eval(task(), solver=[system_message("Policy: {policy}"), generate()],
           model="mockllm/model", log_dir="logs", display="none")[0]
print("\nswapped solver, status:", log.status, "| events:", sorted(EVENTS))
print("system prompt sent:", log.samples[0].messages[0].text)
print("plan logged:", [st.solver for st in log.plan.steps])

# 3. fork(): run several solvers on deep copies of the same state, in parallel.
@solver
def best_of_two() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        branches = await fork(state, [system_message("Be formal."), system_message("Be casual.")])
        branches = [await generate(b) for b in branches]      # each branch calls the model
        print("branch system prompts:", [b.messages[0].text for b in branches],
              "| branch roles:", [m.role for m in branches[0].messages],
              "| parent messages untouched:", [m.role for m in state.messages])
        return await generate(state)
    return solve

eval(Task(dataset=[Sample(input="hello")], solver=best_of_two()),
     model="mockllm/model", log_dir="logs", display="none")
try:
    import asyncio
    asyncio.run(fork(None, [generate()]))
except RuntimeError as e:
    print("fork outside a running task ->", e)
Output · real8 lines
status: success | errors: [('a', None), ('b', "RuntimeError('tool backend unavailable')")]
events: ['cleanup a', 'cleanup b', 'setup a', 'setup b']

swapped solver, status: success | events: ['cleanup a', 'cleanup b', 'setup a', 'setup b']
system prompt sent: Policy: Refunds within 30 days.
plan logged: ['load_policy', 'system_message', 'generate']
branch system prompts: ['Be formal.', 'Be casual.'] | branch roles: ['system', 'user', 'assistant'] | parent messages untouched: ['user']
fork outside a running task -> Called fork() outside of a running task.
  • In the first run, sample b raised inside the solver; with fail_on_error=False the run finished with status success, b carries its error (and no scores), and cleanup ran for both samples.
  • In the second run the main solver was swapped through eval(solver=...). The load_policy setup still ran (the swapped-in system prompt was rendered with the {policy} it put in the store), and the log's plan shows setup plus the new chain.

Use setup for anything every solver variant needs and must not be able to forget: loading per-sample resources, policy text, a customer record. Use cleanup to release what setup acquired. Sandbox resources have their own lifecycle (10B.15), and error-handling policy (fail_on_error, retry_on_error) is 10B.12's.

7.9 Testing a solver without a key#

A solver is code, and the cheapest test for it is the one this whole lesson has used: a mockllm/model with a callable that records what it was sent. Wrapped in pytest:

python
# test_solvers.py: unit-test a solver chain keylessly by capturing what the model receives.
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.solver import Solver, chain, generate, prompt_template, solver, system_message


@solver
def triage_prompting(company: str = "Acme Cloud") -> Solver:
    return chain(
        system_message('Triage tickets for {company}. Reply as {{"category": "..."}}.',
                       company=company),
        prompt_template("Ticket:\n{prompt}\nPlan: {plan}"),
        generate(),
    )


def run_and_capture(sample: Sample) -> list[tuple[str, str]]:
    sent: list[list[tuple[str, str]]] = []

    def capture(input, tools, tool_choice, config):
        sent.append([(m.role, m.text) for m in input])
        return ModelOutput.from_content(model="mockllm", content='{"category": "billing"}')

    model = get_model("mockllm/model", custom_outputs=capture, memoize=False)
    log = eval(Task(dataset=[sample], solver=triage_prompting()), model=model,
               log_dir="logs", display="none")[0]
    assert log.status == "success"
    assert len(sent) == 1, "the chain should call the model exactly once"
    return sent[0]


def test_prompt_is_rendered_completely():
    messages = run_and_capture(Sample(input="charged twice", metadata={"plan": "pro"}))
    assert messages[0] == ("system", 'Triage tickets for Acme Cloud. Reply as {"category": "..."}.')
    assert messages[1] == ("user", "Ticket:\ncharged twice\nPlan: pro")


def test_no_placeholder_survives_rendering():
    # a sample WITHOUT the 'plan' metadata: the placeholder would reach the model unrendered
    messages = run_and_capture(Sample(input="charged twice"))
    leftovers = [text for _, text in messages if "{plan}" in text]
    assert leftovers == [], f"unrendered placeholder sent to the model: {leftovers}"

The output below is real (command: pytest -q -p no:logging -p no:cacheprovider --tb=line test_solvers.py); the absolute directory in the error line is trimmed to …/ and trailing spaces are removed.

Output · real11 lines
.F                                                                       [100%]
=================================== FAILURES ===================================
E   AssertionError: unrendered placeholder sent to the model: ['Ticket:\ncharged twice\nPlan: {plan}']
    assert ['Ticket:\nch...Plan: {plan}'] == []

      Left contains one more item: 'Ticket:\ncharged twice\nPlan: {plan}'
      Use -v to get more diff
…/test_solvers.py:43: AssertionError: unrendered placeholder sent to the model: ['Ticket:\ncharged twice\nPlan: {plan}']
=========================== short test summary info ============================
FAILED test_solvers.py::test_no_placeholder_survives_rendering - AssertionErr...
1 failed, 1 passed in 0.95s

The first test pins the rendered prompt, including the doubled braces of 6.5 turning into single ones. The second test fails on purpose: a sample without plan metadata sends Plan: {plan} to the model, which is the silent placeholder rule of 6.5 caught by a test instead of by a puzzled reviewer. Keep both kinds in your test suite: exact-prompt tests for the templates that matter, and a "no { placeholder survives" check over every sample in the dataset, which costs nothing because the mock answers instantly. 03.10 covers testing LLM code in general; 10A.8 puts such tests in CI.


Part 8: Task configuration#

Deep-dive

8.1 Every Task parameter#

Task takes far more than a dataset, a solver and a scorer. This is every parameter in 0.3.292, grouped, with the lesson that owns each one. (The docs' Task Options table omits turn_limit, headline_metric, review, checkpoint, sentinel and max_samples; the installed class accepts them all.)

Group Parameter Default Meaning Owner
Structure dataset None A Dataset, a list of Samples or a SampleSource Parts 2 to 4
setup None Solver(s) that always run first, even when the solver is swapped 7.8
solver generate() A solver, an agent, or a list (chained) Parts 5 to 7
cleanup None async def f(state), runs after each sample, even on error 7.8
scorer None A scorer or list; a task with none still runs and logs outputs, with no metrics 10B.10
metrics None Metrics that replace the scorer's own 10B.10
headline_metric None Which score and metric summarize the task 10B.10
Model model None A default model for this task (usually given to eval() instead) 10B.12
config GenerateConfig() Generation settings for the task's default model (not for model roles) 10B.12
model_roles None Named models ({"grader": ...}) for get_model(role=...) 7.3, 10B.11
Repetition epochs None (1) An int or Epochs(n, reducer) 10B.10
early_stopping None Stop scheduling samples based on results so far 10B.12
Errors fail_on_error None (True) Fail on the first error, never, a proportion or a count 10B.12
continue_on_fail None Keep going and fail only at the end 10B.12
score_on_error None Score errored samples on their partial state 10B.12
Limits (per sample) message_limit, token_limit, turn_limit, time_limit, working_limit, cost_limit None Messages, tokens (also strings such as "500k"), turns, seconds, working seconds, dollars 10B.15
Agents sandbox, approval, review, checkpoint, on_checkpoint, on_resume, sentinel None Sandboxes, tool-call approval and review, checkpointing, monitors (sentinel is experimental) 10B.14, 10B.15
Concurrency max_samples (keyword-only, new in 0.3.292) None Parallel samples for this task; an eval() or CLI value overrides it 10B.12
Identity name None Defaults to the @task function's registered name, else "task" 8.7
display_name None For the viewer and plots 8.7
description (keyword-only) None What the task asks; logged, does not affect eval-set identity 8.7
version 0 int or str; bump it when the task changes meaning 8.7
metadata, tags None Logged with the run 8.7
viewer None How samples and scores render in Inspect View 10B.13

The rule of thumb in the docs is right: you do not need most of these until you use the feature they belong to. The ones every task should set from day one are a named dataset, explicit sample ids, the solver, the scorer, version, and enough metadata to know later what was run.

8.2 @task and task arguments#

10B.8, 5.2 introduced -T. A task function is a function decorated with @task that returns a Task. Its arguments are the task arguments: the knobs you can turn from the command line without editing code. The decorator registers the function (which inspect list tasks, eval_retry(), eval sets and inspect score need), records the arguments it was called with in the log (eval.task_args), and can carry attributes for filtering: @task(light=True), or @task(name="triage_v2") to register under a different name.

The configuration probes use one parameterized task, cfg/triage_cfg.py:

python
# cfg/triage_cfg.py: a parameterised task used to probe the configuration layers.
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Solver, chain, generate, solver, system_message

SAMPLES = [Sample(id=f"T0{i}", input=f"ticket {i}", target="mockllm") for i in range(1, 5)]


@solver
def terse(style: str = "one line") -> Solver:
    return chain(system_message(f"Answer in {style}."), generate())


@task(light=True)
def triage(prompt_version: str = "v1", n_shots: int = 0, strict: bool = False):
    print(f"  [task built] prompt_version={prompt_version!r} n_shots={n_shots!r} "
          f"({type(n_shots).__name__}) strict={strict!r} ({type(strict).__name__})")
    return Task(
        dataset=SAMPLES,
        solver=[system_message(f"Prompt {prompt_version}"), generate()],
        scorer=includes(),
        epochs=1,
        message_limit=5,
        version=2,
        metadata={"owner": "support-ml", "prompt_version": prompt_version},
        tags=["triage"],
    )


@task
def triage_heavy():
    return Task(dataset=SAMPLES, scorer=includes())

and a helper that prints the realised configuration from the newest log:

python
# cfg/show.py: print the realised configuration of the newest log in ./logs.
import sys
from inspect_ai.log import list_eval_logs, read_eval_log

log = read_eval_log(list_eval_logs("logs")[0], header_only=True)   # newest first
e = log.eval
print(f"  task={e.task} task_args={e.task_args} version={e.task_version}")
print(f"  epochs={e.config.epochs} limit={e.config.limit} message_limit={e.config.message_limit} "
      f"max_tokens={log.plan.config.max_tokens} seed={log.plan.config.seed}")
print(f"  metadata={e.metadata} tags={e.tags}")
print(f"  solver steps={[ (s.solver, s.params) for s in log.plan.steps]}")
print(f"  samples={log.results.total_samples if log.results else None}")

The shell script cfg/run_cli.sh runs one CLI command per configuration feature and calls show.py after each (keyless: every run uses mockllm/model). Each inspect eval in the script ran with --display none (the last with --display plain, piped through grep and sed so only the warning, task and accuracy lines remain, which is why its [task built] lines are missing). Its output, otherwise trimmed only of trailing spaces and the log-timestamp column of the one warning line:

text
$ inspect list tasks triage_cfg.py
triage_cfg.py@triage
triage_cfg.py@triage_heavy

$ inspect list tasks triage_cfg.py -F light=true
triage_cfg.py@triage

$ inspect eval triage_cfg.py@triage --model mockllm/model -T n_shots=3 -T strict=true -T prompt_version=v2
  [task built] prompt_version='v2' n_shots=3 (int) strict=True (bool)
  task=triage task_args={'prompt_version': 'v2', 'n_shots': 3, 'strict': True} version=2
  epochs=1 limit=None message_limit=5 max_tokens=None seed=None
  metadata={'owner': 'support-ml', 'prompt_version': 'v2'} tags=['triage']
  solver steps=[('system_message', {'template': 'Prompt v2'}), ('generate', {'tool_calls': 'loop'})]
  samples=4

$ INSPECT_EVAL_EPOCHS=3 inspect eval triage_cfg.py@triage --model mockllm/model
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v1', 'n_shots': 0, 'strict': False} version=2
  epochs=3 limit=None message_limit=5 max_tokens=None seed=None
  metadata={'owner': 'support-ml', 'prompt_version': 'v1'} tags=['triage']
  solver steps=[('system_message', {'template': 'Prompt v1'}), ('generate', {'tool_calls': 'loop'})]
  samples=12

$ (.env contains INSPECT_EVAL_MESSAGE_LIMIT=8) inspect eval triage_cfg.py@triage --model mockllm/model
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v1', 'n_shots': 0, 'strict': False} version=2
  epochs=1 limit=None message_limit=8 max_tokens=None seed=None
  metadata={'owner': 'support-ml', 'prompt_version': 'v1'} tags=['triage']
  solver steps=[('system_message', {'template': 'Prompt v1'}), ('generate', {'tool_calls': 'loop'})]
  samples=4

$ INSPECT_EVAL_EPOCHS=3 inspect eval triage_cfg.py@triage --model mockllm/model --epochs 2 --message-limit 9 --metadata run=nightly --tags ci
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v1', 'n_shots': 0, 'strict': False} version=2
  epochs=2 limit=None message_limit=9 max_tokens=None seed=None
  metadata={'run': 'nightly', 'owner': 'support-ml', 'prompt_version': 'v1'} tags=['triage', 'ci']
  solver steps=[('system_message', {'template': 'Prompt v1'}), ('generate', {'tool_calls': 'loop'})]
  samples=8

$ inspect eval triage_cfg.py@triage --model mockllm/model --task-config task_args.yaml --generate-config gen.yaml --max-tokens 128
  [task built] prompt_version='v3' n_shots=2 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v3', 'n_shots': 2, 'strict': False} version=2
  epochs=1 limit=None message_limit=5 max_tokens=128 seed=42
  metadata={'owner': 'support-ml', 'prompt_version': 'v3'} tags=['triage']
  solver steps=[('system_message', {'template': 'Prompt v3'}), ('generate', {'tool_calls': 'loop'})]
  samples=4

$ inspect eval triage_cfg.py@triage --model mockllm/model --solver terse -S style=haiku --limit 2-3
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v1', 'n_shots': 0, 'strict': False} version=2
  epochs=1 limit=(1, 3) message_limit=5 max_tokens=None seed=None
  metadata={'owner': 'support-ml', 'prompt_version': 'v1'} tags=['triage']
  solver steps=[('system_message', {'template': 'Answer in haiku.'}), ('generate', {'tool_calls': 'loop'})]
  samples=2

$ inspect eval --run-config run.yaml
  [task built] prompt_version='v4' n_shots=0 (int) strict=False (bool)
  task=triage task_args={'prompt_version': 'v4', 'n_shots': 0, 'strict': False} version=2
  epochs=2 limit=2 message_limit=5 max_tokens=512 seed=None
  metadata={'owner': 'support-ml', 'prompt_version': 'v4'} tags=['triage']
  solver steps=[('system_message', {'template': 'Prompt v4'}), ('generate', {'tool_calls': 'loop'})]
  samples=4

$ inspect log export-config <newest log>
task:
  task: triage_cfg.py@triage
  args:
    prompt_version: v4
    n_shots: 0
    strict: false
model:
  model: mockllm/model
  config:
    max_tokens: 512
generate_config:
  max_tokens: 512
eval_config:
  limit: 2
  epochs: 2
  fail_on_error: true
  continue_on_fail: false
  score_on_error: false
  message_limit: 5
tags:
- triage
metadata:
  owner: support-ml
  prompt_version: v4

$ inspect eval triage_cfg.py --model mockllm/model -T prompt_version=v9   (no @name: every task in the file runs)
WARNING param 'prompt_version' not used by task 'triage_heavy'
triage (4 samples): mockllm/model
triage | generate | Steps: 4/4 100% | Samples: 4/ 4 | accuracy: n/a | mockllm: 0/20 | HTTP retries: 0
triage_heavy (4 samples): mockllm/model
triage_heavy | generate | Steps: 4/4 100% | Samples: 4/ 4 | accuracy: n/a | mockllm: 0/20 | HTTP retries: 0
triage (4 samples): mockllm/model
accuracy 1.000
triage_heavy (4 samples): mockllm/model
accuracy 1.000

The first three blocks are about task arguments:

  • inspect list tasks finds every @task in a file (file.py@name), and -F light=true filters on decorator attributes. Use attributes to mark tasks as light, nightly, needs_sandbox and so on, then run a subset with inspect list tasks -F or list_tasks(filter=...) (10B.12 uses this with eval sets).
  • -T key=value sets a task argument. Values are parsed like YAML: -T n_shots=3 arrived as the integer 3 and -T strict=true as the boolean True. So -T prompt_version=2 would arrive as the integer 2, not the string "2": give arguments type hints and convert inside the task function (str(prompt_version)) when the type matters. In Python, call the function with arguments (triage(prompt_version="v2")) or pass eval("triage_cfg.py@triage", task_args={...}).
  • The log records the arguments (task_args={'prompt_version': 'v2', 'n_shots': 3, 'strict': True}), including defaults you did not pass. Six months later, that line is the only proof of which prompt version produced a number.
  • inspect eval file.py without @name runs every task in the file (the last block ran both triage and triage_heavy). A -T argument that a task does not accept is ignored for that task with only a warning (param 'prompt_version' not used by task 'triage_heavy'). Always name the task: file.py@triage.

8.3 Solver-agnostic tasks: --solver and -S#

A task's solver is a default, not a fixed part of its identity. --solver name (or eval(solver=...)) replaces it at run time, and -S key=value passes arguments to that solver's factory. The --solver terse -S style=haiku --limit 2-3 block above replaced the task's chain with the registered terse solver (the log's plan shows Answer in haiku.) and ran samples 2 and 3 (recorded as limit=(1, 3), the 0-based slice of 4.3).

To make a task work well with any solver:

  • Put what every solver needs in setup (prompt context, resources), so a swapped-in solver cannot skip it (7.8).
  • Keep the scorer independent of solver details: score state.output, not a message at a fixed index, because another solver produces a different conversation.
  • Alternatively, take the solver as a task argument and choose inside the task function, which Part 9 does (-T solver=oracle): the log then records the choice in task_args as well as in the plan.

8.4 task_with(), and why it mutates#

task_with(task, **overrides) returns a task with any Task parameter replaced: the way to adapt a task you do not control (one from a package such as Inspect Evals) to your solver, sandbox, limits or scorer.

python
# s11_task_with.py: task_with() mutates, eval() merges metadata, the scorer is fixed at run time.
from inspect_ai import Task, eval, task, task_with
from inspect_ai.dataset import Sample
from inspect_ai.scorer import exact, includes


@task
def support_faq():
    return Task(dataset=[Sample(id="q1", input="Do you ship to Peru?", target="mockllm")],
                scorer=includes(), message_limit=5, metadata={"owner": "support-ml"})


base = support_faq()
variant = task_with(base, message_limit=20, name="support_faq_long",
                    metadata={"variant": "long"})
print("same object:", variant is base, "| base.message_limit:", base.message_limit,
      "| base.name:", base.name, "| base.metadata:", base.metadata)

# The fix: build a fresh task for each variant.
short = task_with(support_faq(), name="support_faq_short", message_limit=3)
long_ = task_with(support_faq(), name="support_faq_long", message_limit=20)
print("independent:", short is not long_, "|", short.name, short.message_limit, "|", long_.name, long_.message_limit)

# eval(metadata=...) MERGES with the task's metadata; task_with(metadata=...) REPLACED it above.
log = eval(support_faq(), model="mockllm/model", metadata={"run": "nightly"},
           log_dir="logs", display="none")[0]
print("eval(metadata=) merges:", log.eval.metadata)

# Swapping the scorer is a task_with() job; eval() has no scorer argument.
log = eval(task_with(support_faq(), scorer=exact()), model="mockllm/model",
           log_dir="logs", display="none")[0]
print("scorer after task_with:", [s.name for s in log.results.scores])
try:
    eval(support_faq(), model="mockllm/model", scorer=exact(), display="none")
except Exception as e:   # unknown keywords are treated as GenerateConfig fields
    print("eval(scorer=...) ->", type(e).__name__ + ":", str(e).splitlines()[1].strip()[:80])
Output · real5 lines
same object: True | base.message_limit: 20 | base.name: support_faq_long | base.metadata: {'variant': 'long'}
independent: True | support_faq_short 3 | support_faq_long 20
eval(metadata=) merges: {'run': 'nightly', 'owner': 'support-ml'}
scorer after task_with: ['exact']
eval(scorer=...) -> ValidationError: Value error, Unknown GenerateConfig field(s): scorer. Use extra_body for provide
  • task_with() modifies the task in place and returns the same object. After deriving variant from base, base itself has the new limit, name and metadata. The docs say so; it is still the most common surprise. Build a fresh task for every variant: task_with(support_faq(), ...) twice, never task_with(base, ...) twice.
  • task_with(metadata=...) replaces the task's metadata (the owner key is gone), while eval(metadata=...) merges with it (run and owner both survive). The same holds for tags.
  • The scorer can be swapped only with task_with(). eval() has no scorer argument, and passing one anyway gives a confusing error: unknown keyword arguments to eval() are treated as GenerateConfig fields, so the message is Unknown GenerateConfig field(s): scorer. A misspelt generation option (max_token=100) fails the same way, which is at least loud.

8.5 The four configuration layers#

A setting can come from four places. The docs give the precedence, lowest to highest:

flowchart LR
    T["1. Task definition: Task(...) and @task defaults"] --> W["2. task_with(task, ...)"]
    W --> E["3. Environment: INSPECT_EVAL_* and .env (CLI)"]
    E --> C["4. eval() arguments or CLI flags"]
    C --> R["Realised config, recorded in the log"]
    R -->|"inspect log export-config"| Y["run.yaml for --run-config"]
    Y --> C

The CLI blocks of 8.2 show each layer winning in turn: the task says epochs=1, message_limit=5; INSPECT_EVAL_EPOCHS=3 in the shell raised epochs to 3 (12 sample runs); a .env file with INSPECT_EVAL_MESSAGE_LIMIT=8 raised the message limit to 8; and --epochs 2 --message-limit 9 on the command line beat the shell variable and the task (epochs=2, message_limit=9). Every CLI flag has an INSPECT_EVAL_ twin (upper case, hyphens to underscores), and shell variables beat .env values (except in a VS Code terminal, where Inspect loads .env with override so that edits to the file take effect).

Now the surprise. The same environment variables, set for a Python script that calls eval():

python
# cfg/env_py.py: do INSPECT_EVAL_* variables reach the Python eval() API?
import os
from inspect_ai import eval
from triage_cfg import triage

os.environ["INSPECT_EVAL_EPOCHS"] = "3"
os.environ["INSPECT_EVAL_MESSAGE_LIMIT"] = "7"
log = eval(triage(), model="mockllm/model", display="none")[0]
print("python eval() with INSPECT_EVAL_EPOCHS=3, INSPECT_EVAL_MESSAGE_LIMIT=7 ->",
      "epochs", log.eval.config.epochs, "| message_limit", log.eval.config.message_limit)

# INSPECT_EVAL_MODEL is the documented exception: eval() falls back to it when model is omitted.
os.environ["INSPECT_EVAL_MODEL"] = "mockllm/model"
log = eval(triage(), display="none")[0]
print("python eval() with no model and INSPECT_EVAL_MODEL set ->", log.eval.model)
Output · real; run with INSPECT_EVAL_EPOCHS=3 also exported in the shell4 lines
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
python eval() with INSPECT_EVAL_EPOCHS=3, INSPECT_EVAL_MESSAGE_LIMIT=7 -> epochs 1 | message_limit 5
  [task built] prompt_version='v1' n_shots=0 (int) strict=False (bool)
python eval() with no model and INSPECT_EVAL_MODEL set -> mockllm/model

INSPECT_EVAL_EPOCHS and INSPECT_EVAL_MESSAGE_LIMIT had no effect on the Python eval() call (epochs stayed 1, the message limit stayed 5), while INSPECT_EVAL_MODEL did (the documented fallback when model is omitted). The INSPECT_EVAL_* layer is a feature of the inspect command line, which maps every flag to a variable; the Python API reads only a few variables of its own (the model, the log directory and format, the display, and similar INSPECT_* settings documented on the options page). The docs' four-layer description does not make this distinction. In a notebook or a script, pass settings to eval() explicitly or read the variables yourself.

One more exception was found in 10B.8, 5.6: a model set on the Task is used even when --model (or eval(model=...)) names another, because the loader takes task.model or model. Leave model off tasks you mean to reuse and use a model role for any fixed second model.

What can be set where (from the docs' override reference, checked against the runs above and 10B.8):

Setting Task task_with eval() CLI
dataset, setup, cleanup, scorer, metrics yes yes
solver yes yes solver= --solver, -S
model, config (GenerateConfig), model_roles yes yes yes --model, generation flags, --generate-config, --model-role (but a model on the Task wins over --model)
epochs, limits, fail_on_error, continue_on_fail, score_on_error yes yes yes flags of the same name
early_stopping yes yes
sandbox, approval yes yes yes --sandbox, --approval
name, version, description yes yes
metadata, tags yes yes (replaces) yes (merges) --metadata, --tags
limit, sample_id, sample_shuffle, retry_on_error, debug_errors, score, trace yes flags
task arguments function arguments task_args= -T, --task-config

The design is deliberate: what an eval is (data, scoring, identity) can only be changed in code; how a run goes (model, limits, sample selection, repetitions) can be changed at run time. When you consume someone else's task, that table tells you whether you need task_with() or just a flag.

8.6 Configuration files: task, generate, run and export#

Four files turn long command lines into reviewable artefacts (blocks five, seven and eight of the CLI output):

Option File contains Notes
--task-config file.yaml Task arguments (prompt_version: v3) Same as several -T; -T flags still win
--generate-config file.yaml GenerateConfig fields (max_tokens, seed, ...) Individual flags win: --max-tokens 128 beat the file's 256, while the file's seed: 42 survived
--solver-config file.yaml Solver arguments Same as several -S
--run-config run.yaml Everything: task, model, model_roles, generate_config, solver, eval_config All keys optional; cannot be combined with the three above; explicit CLI flags still win

The run config is the one to keep in the repository next to a published number. The inspect log export-config block (first met in 10B.8, 6.5) shows the other half of the loop: it reads a finished log and writes the realised configuration in run-config format, including values you never typed (the task arguments' defaults, fail_on_error: true, the message limit that came from the task). So the reproducibility workflow is:

bash
inspect log export-config logs/2026-11-24T16-02-28-00-00_triage_....eval > run.yaml   # from a run you trust
inspect eval --run-config run.yaml --model <another model>                              # same eval, new model

A run config without a model key is what the docs call a "paper config": the generation and eval settings of a published result, applied to whatever model you pass. Two caveats: the exported file records the task by reference (triage_cfg.py@triage), so it reproduces the run only if the task file and its dataset are unchanged (version them, 8.7); and it does not capture the model provider's own changes behind a model name (10B.12 covers pinning model versions).

8.7 Task identity: name, version, metadata and tags#

Logs, inspect view, evals_df() and eval sets identify a task by its name, its arguments and its version. Use them deliberately:

  • name defaults to the @task function's name. An undecorated Task(...) is called task in the log, which is why every quick test in this lesson's logs/ folder is named ..._task_....eval. Name real tasks.
  • version (default 0) marks changes to what the task means: a relabelled dataset, a new scorer rule, a changed system prompt. Bump it whenever a score from the new version should not be compared with the old one without thought. The log records it as task_version, and comparing across versions is then a visible decision rather than an accident (10A.2, 6.3 is the same discipline for datasets; 04.10, Part 4 for prompts).
  • description is a one-line statement of what the task asks; it is logged and shown, and does not affect eval-set identity.
  • metadata and tags are free-form and logged. Good metadata: the dataset file hash (3.9), the labelling-guidelines version, the owner. Good tags: the suite (triage), the tier (smoke, nightly), the solver variant.

8.8 Packaging tasks#

Tasks, solvers, scorers, tools and model providers can be shipped as an installable Python package and referred to by name, which is how inspect eval inspect_evals/gpqa_diamond works. The mechanism is a setuptools entry point in the inspect_ai group that points at a module importing everything to register. A minimal package, acme_evals:

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

[project.entry-points.inspect_ai]
acme_evals = "acme_evals._registry"

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

src/acme_evals/tasks.py holds an ordinary @task (here refund_policy), and src/acme_evals/_registry.py imports it:

python
# Everything imported here is registered with Inspect when the package is installed.
from .tasks import refund_policy  # noqa: F401

With the package installed, the task runs by package/task name from any directory:

text
$ uv run --with inspect-ai --with ./pkg/acme_evals inspect eval acme_evals/refund_policy --model mockllm/model --display plain   (output filtered with grep)
refund_policy (1 sample): mockllm/model
generate     | Steps:   1/1 100% | Samples:   1/  1 | accuracy:  n/a | mockllm:  0/20 | HTTP retries: 0
refund_policy (1 sample): mockllm/model
accuracy  1.000

(Real output, filtered to the task and result lines, trailing spaces trimmed.) The entry-point group is the same for every component type, so acme_evals/my_scorer works with inspect score --scorer and acme_evals/my_solver with --solver. For Poetry the table is [tool.poetry.plugins.inspect_ai]. Packaging is the right home for evals shared across teams: dependencies are declared, versions are pinned by the package version, and nobody copies task files around. 10B.13 covers the other extension points.

8.9 Hugging Face eval.yaml tasks (illustrative: downloads)#

A Hugging Face dataset repository can contain an eval.yaml file that defines Inspect tasks over its data. Inspect runs them directly:

bash
inspect eval hf/OpenEvals/aime_24 --model openai/gpt-6-luna            # every task in the file
inspect eval hf/OpenEvals/MuSR/musr:murder_mysteries --model openai/gpt-6-luna   # one named task
inspect eval hf/OpenEvals/MuSR@df154a5 --model openai/gpt-6-luna       # pinned to a revision

The file's fields map onto what this lesson covered: config and split to hf_dataset(), field_spec to a FieldSpec (with extras: target can be literal:<value>, or an integer label that is turned into a letter; choices can list several fields; input_image names a base64 image field), shuffle_choices, epochs and epoch_reducer, solvers and scorer. As with any Hub data, pin the revision (@<sha>) for a result you will cite. The tasks page has the full field list.

8.10 Exploring variants without losing track#

During development you will want to try combinations: two prompt versions times two solver strategies times three models. Make each knob a task argument, build the grid with itertools.product, and pass the list of tasks (and a list of models) to eval_set() with its own log directory; each combination becomes one log with its arguments recorded, and a re-run skips the ones already done. Eval sets, their retries and their identity rules are 10B.12's subject; Inspect Flow, a companion package, adds declarative sweeps on top. The methodological warning is 10A.8's: every extra variant you compare is another chance for a lucky difference, so decide what you will compare before you look.


Part 9: Worked example: the triage task, rebuilt properly#

10B.8, Part 4 ported 10A.1's triage eval faithfully, keeping its data and scorers so the numbers could be reconciled with evalkit. This part builds the production-shaped version, the way you would write it for a new eval today, using everything this lesson has covered: a validated dataset with stable ids and metadata, a system prompt in a file with its JSON braces escaped, a prompt template fed by metadata, a validate-and-repair solver that records its attempts in the store, task arguments for the company name, the repair budget and the solver variant, two control solvers, a version and metadata. The scorer is deliberately small; 10B.10 builds better ones.

The project folder triage/ holds three files: tickets.jsonl (the eight tickets of 2.5), the system prompt triage_system.txt:

text
You triage support tickets for {company}.
Reply with JSON only, in exactly this shape: {{"category": "...", "priority": "..."}}
category is one of: billing, technical, account, shipping, other.
priority is one of: P1 (outage, security, data loss), P2 (blocked or charged wrongly), P3 (everything else).

and the task module:

python
# triage_task.py: the ticket-triage eval as an Inspect task (lesson 10B.9, Part 9).
import json

from pydantic import Field

from inspect_ai import Task, task
from inspect_ai.dataset import Sample, json_dataset
from inspect_ai.model import ChatMessageUser, ModelOutput
from inspect_ai.scorer import Score, Scorer, Target, accuracy, scorer, stderr
from inspect_ai.solver import (Generate, Solver, TaskState, chain, prompt_template,
                               solver, system_message)
from inspect_ai.util import StoreModel, store_as

CATEGORIES = {"billing", "technical", "account", "shipping", "other"}
PRIORITIES = {"P1", "P2", "P3"}


# ---------------------------------------------------------------- dataset
def record_to_sample(record: dict) -> Sample:
    """One JSONL row -> one Sample, with a stable id and a canonical JSON target."""
    for key in ("ticket_id", "text", "category", "priority"):
        if not record.get(key):
            raise ValueError(f"row {record.get('ticket_id', '?')}: missing {key!r}")
    if record["category"] not in CATEGORIES or record["priority"] not in PRIORITIES:
        raise ValueError(f"row {record['ticket_id']}: label outside the allowed set")
    target = {"category": record["category"], "priority": record["priority"]}
    return Sample(
        id=record["ticket_id"],
        input=record["text"],
        target=json.dumps(target, sort_keys=True),
        metadata={"intent": record["intent"], "edge": record["edge"], "plan": record["plan"]},
    )


def parse_triage(text: str) -> tuple[dict | None, str]:
    """Return (parsed, problem). problem is "" when the reply is valid."""
    try:
        got = json.loads(text)
    except json.JSONDecodeError as e:
        return None, f"not valid JSON ({e.msg})"
    if not isinstance(got, dict) or set(got) != {"category", "priority"}:
        return None, "JSON must have exactly the keys category and priority"
    if got["category"] not in CATEGORIES or got["priority"] not in PRIORITIES:
        return None, "category or priority is outside the allowed values"
    return got, ""


# ---------------------------------------------------------------- solvers
class RepairLog(StoreModel):
    attempts: int = Field(default=0)
    problems: list[str] = Field(default_factory=list)


@solver
def generate_with_repair(max_attempts: int = 2) -> Solver:
    """Generate; if the reply is not valid triage JSON, say why and ask again."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        repair = store_as(RepairLog)
        for _ in range(max_attempts):
            repair.attempts += 1
            state = await generate(state)
            _, problem = parse_triage(state.output.completion)
            if not problem:
                break
            repair.problems.append(problem)
            state.messages.append(ChatMessageUser(
                content=f"Your reply was rejected: {problem}. Reply with the JSON object only."))
        return state
    return solve


@solver
def triage_solver(company: str = "Acme Cloud", max_attempts: int = 2) -> Solver:
    return chain(
        system_message("triage_system.txt", company=company),
        prompt_template("Ticket:\n<<<\n{prompt}\n>>>\nCustomer plan: {plan}"),
        generate_with_repair(max_attempts=max_attempts),
    )


@solver
def oracle() -> Solver:
    """Control: answer with the target. The scorer must give 100%."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state.output = ModelOutput.from_content(model="oracle", content=state.target.text)
        return state
    return solve


@solver
def null_answer() -> Solver:
    """Control: answer with nothing. The scorer must give 0%."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state.output = ModelOutput.from_content(model="null", content="")
        return state
    return solve


# ---------------------------------------------------------------- scorer (10B.10 goes deeper)
@scorer(metrics=[accuracy(), stderr()])
def triage_match() -> Scorer:
    async def score(state: TaskState, target: Target) -> Score:
        got, problem = parse_triage(state.output.completion)
        want = json.loads(target.text)
        if problem:
            return Score(value="I", answer=state.output.completion, explanation=problem)
        return Score(value="C" if got == want else "I", answer=json.dumps(got, sort_keys=True))
    return score


# ---------------------------------------------------------------- task
@task
def triage(company: str = "Acme Cloud", max_attempts: int = 2, solver: str = "default"):
    solvers = {"default": triage_solver(company, max_attempts),
               "oracle": oracle(), "null": null_answer()}
    dataset = json_dataset("tickets.jsonl", record_to_sample, name="tickets")
    return Task(
        dataset=dataset,
        solver=solvers[solver],
        scorer=triage_match(),
        version=1,
        metadata={"owner": "support-ml", "labels": "guidelines-v2"},
        tags=["triage", f"solver:{solver}"],
    )

The runner plays a scripted model: right on six tickets, wrong on the priority of T01 (the multi-intent ticket, which the labels say is P2), and a chatty non-JSON reply to T05 that the repair loop has to fix. It runs the task three times, with the real solver and with each control:

python
# run_triage.py: run the triage task keyless with a scripted model, plus the two controls.
from inspect_ai import eval
from inspect_ai.model import ModelOutput, get_model

from triage_task import triage

REPLIES = {   # keyword in the ticket -> what the scripted "model" says
    "charged twice": '{"category": "billing", "priority": "P3"}',         # wrong priority
    "log in": '{"category": "technical", "priority": "P1"}',
    "second admin": '{"category": "account", "priority": "P3"}',
    "hacked": '{"category": "account", "priority": "P1"}',
    "standing desks": "Sure! This looks like a shipping question.",       # prose first
    "crashes": '{"category": "technical", "priority": "P2"}',
    "quick fix": '{"category": "other", "priority": "P3"}',
    "downgrade": '{"category": "billing", "priority": "P3"}',
}

def scripted(input, tools, tool_choice, config):
    text = "\n".join(m.text for m in input)
    if "rejected" in input[-1].text:                     # the repair turn
        return ModelOutput.from_content(model="mockllm",
                                        content='{"category": "shipping", "priority": "P2"}')
    reply = next(v for k, v in REPLIES.items() if k in text)
    return ModelOutput.from_content(model="mockllm", content=reply)

model = get_model("mockllm/model", custom_outputs=scripted, memoize=False)
for variant in ("default", "oracle", "null"):
    log = eval(triage(solver=variant), model=model, log_dir="logs", display="none")[0]
    metrics = {k: round(v.value, 3) for k, v in log.results.scores[0].metrics.items()}
    misses = [s.id for s in log.samples if s.scores["triage_match"].value != "C"]
    print(f"{variant:8} status={log.status} {metrics} misses={misses}")
    if variant == "default":
        default_log = log

s = next(x for x in default_log.samples if x.id == "T05")
print("\nT05 conversation:")
for m in s.messages:
    print(f"  {m.role:9} | {m.text[:95]!r}")
print("T05 store:", s.store)
t01 = next(x for x in default_log.samples if x.id == "T01").scores["triage_match"]
print("T01 score:", t01.value, t01.answer)
Output · real12 lines
default  status=success {'accuracy': 0.875, 'stderr': 0.125} misses=['T01']
oracle   status=success {'accuracy': 1.0, 'stderr': 0.0} misses=[]
null     status=success {'accuracy': 0.0, 'stderr': 0.0} misses=['T01', 'T02', 'T03', 'T04', 'T05', 'T06', 'T07', 'T08']

T05 conversation:
  system    | 'You triage support tickets for Acme Cloud.\nReply with JSON only, in exactly this shape: {"categ'
  user      | 'Ticket:\n<<<\nWhen will my order ship? I ordered the standing desks two weeks ago and tracking ha'
  assistant | 'Sure! This looks like a shipping question.'
  user      | 'Your reply was rejected: not valid JSON (Expecting value). Reply with the JSON object only.'
  assistant | '{"category": "shipping", "priority": "P2"}'
T05 store: {'RepairLog:instance': None, 'RepairLog:attempts': 2, 'RepairLog:problems': ['not valid JSON (Expecting value)']}
T01 score: I {"category": "billing", "priority": "P3"}

How to read this:

  • The controls passed: the oracle scored 1.0 and the null answer 0.0. Only after that does 0.875 mean anything (Part 10.1).
  • T05 was rescued by the repair loop: the first reply was prose, the solver told the model why it was rejected, the second reply was valid. The store records attempts: 2 and the problem. The headline accuracy counts T05 as correct, which is the production behaviour if production has the same repair loop. If it does not, this eval is measuring a different system. Either way, report the repair rate (samples with attempts > 1) next to accuracy, because a model that needs repairs on 30% of tickets costs more and fails more under load than one that needs none.
  • The system prompt arrived intact: the conversation shows {"categ... with single braces, because the file doubles them (6.5).
  • The miss is diagnosable from the log: T01's answer was billing/P3 against a P2 label. Whether that is a model error or a labelling disagreement is an error-analysis question (10A.1, Part 4), and the log has what you need to answer it.
  • 8 samples give a standard error of 0.125: the interval around 0.875 runs from roughly 0.63 to 1.0 by the normal approximation (which overshoots 1 and is unreliable at n = 8; a Wilson interval, 10A.7, gives about 0.53 to 0.98). That is a smoke test, not a measurement (10A.2, Part 5).

The same task from the command line, using the task arguments:

bash
inspect eval triage/triage_task.py@triage --model mockllm/model -T solver=oracle   # control
inspect eval triage/triage_task.py@triage --model openai/gpt-6-luna                 # illustrative: needs a key
inspect eval triage/triage_task.py@triage --model anthropic/claude-haiku-5-5 -T max_attempts=1

The first line ran keyless from the parent directory (accuracy 1.000): the relative paths tickets.jsonl and triage_system.txt resolved because inspect eval runs a task file from its own directory. The provider lines are illustrative; 10B.12 covers model strings, keys and running against real providers.


Part 10: Methodology: making the dataset and solver defensible#

Deep-dive

A score is a claim that this model, given these cases presented this way, gets this fraction right. Parts 2 to 8 were about controlling each part of that sentence. This part is about checking it.

10.1 Control solvers: oracle and null#

Before reading any real model's score, run the task with two solvers that have known answers:

Control What it does Expected score If it is not
Oracle Answers with the target (state.target.text) 100% The scorer, the target format or the parsing is broken; or some targets are missing or malformed
Null Answers with nothing (or a fixed irrelevant string) 0%, never chance: an empty answer scores N (no response) under choice() Empty targets (2.2), a scorer that rewards format over content, or answers leaking into the input

Part 9 made them task arguments (-T solver=oracle, -T solver=null) so they run through exactly the same dataset and scorer as the real solver. They cost nothing (no model calls) and they catch the expensive bugs: a run in which every sample "passes" because the targets are empty, a scorer that cannot parse its own target format, a multiple-choice set where the constant-letter control (below) scores 60% because most answers are "A". 10A.7, 5.5 is the same idea for agent harnesses (negative controls and oracle runs); in Inspect it is two small solvers. Add a third for multiple choice, a constant-letter solver, to measure how well "always answer A" does on your data: its score is the real chance baseline of your dataset. Build it as multiple_choice() driven by a mockllm/model whose custom_outputs always return ANSWER: A (or as a solver that calls state.choices.mark_choice(0, True)). A solver that only sets state.output to "ANSWER: A" scores 0, because choice() scores the choices multiple_choice() marked, not the completion text.

10.2 Read what was actually sent#

Every silent failure in this lesson (unknown placeholders, JSON braces, a missing template file, a None metadata value, a solver that skipped generate()) is visible in one place: the messages of a sample in the log. Make it a habit, for every new task and every prompt change:

  1. Run one or two samples (--limit 2) against mockllm/model or a cheap model.
  2. Open the log (inspect view) or read it in code (read_eval_log(path).samples[0].messages), and read the system prompt, the user turn and anything a solver inserted, as text.
  3. Search the rendered prompts for { followed by a word and }: any survivor is a bug.
  4. Check plan.steps in the log: is the solver chain the one you think, with the arguments you think?

The test in 7.9 automates steps 3 and 4 for CI.

10.3 Elicitation and fairness across models#

The solver decides how hard the eval tries to get the right answer out of the model. That choice is elicitation, and it is part of the measurement:

  • The same solver is not the same treatment for every model. A chain-of-thought instruction helps some models, does nothing for reasoning models and can hurt others (6.6). A prefill works on one provider and is rejected by another (6.3). When you compare models, say which solver you used and whether it suits each of them.
  • Under-elicitation understates capability; over-elicitation measures your scaffold. A safety or capability evaluation that wants an upper bound (as Inspect's original users do) tries several solvers and reports the best, clearly labelled. A product evaluation should use the solver that matches production, because that is what users will get.
  • Compare solvers the way you compare prompts: same dataset, same seed, paired by sample id, with an interval on the difference (10A.8). The --solver switch makes this a one-flag change; the analysis is 10B.13's.
  • Never let a solver see the scorer or the target unless the reported number says so (7.6, 6.10).

10.4 The dataset checklist, in Inspect terms#

10A.2 taught dataset hygiene. Here is where each item lands in Inspect:

10A.2 practice In Inspect
Stable example ids (10A.2, 1.2) Explicit ids from the source, or auto_id=True on an unchanging file; never run-time numbering (2.4)
Schema validation at load time (10A.2, 8.4) Raise in record_to_sample; typed metadata with a frozen model (3.6, 2.5)
Slices (10A.2, 3.2) metadata keys; grouped metrics and samples_df() later
Splits (10A.2, 6.1) A split metadata key and a task argument that filters on it (3.9)
Group-aware splits (10A.2, 6.7) Keep a parent id in metadata for one-to-many records; filter by it, not by limit
Versioning (10A.2, 6.3) Dataset name and location, a file hash in task metadata, version on the task, pinned revision on the Hub
Sample size (10A.2, Part 5) No help from Inspect: count before you run; limit subsets need the same interval reasoning
Contamination (10A.2, 6.2) No help from Inspect: public Hub data is the riskiest source
Symptom Cause Fix
New cases score 100%, even nonsense answers Empty target (default "") with includes()/match() Validate targets at load time; run the null control (2.2)
"Sample 7 regressed" but it is a different question Run-time positional ids plus a shuffle Explicit ids or auto_id=True (2.4)
Log says dataset "difficulty" for qa.csv csv_dataset name bug in 0.3.292 (explicit name= also ignored) .filter(lambda s: True, name="qa") (3.2)
ValueError: No input in dataset No input column and no FieldSpec, or a row whose input is empty (Sample(input="") and record_to_sample accept it) Map fields with FieldSpec or a function (3.4)
limit=10 gives an odd mix of cases limit counts samples after one-to-many conversion (records in hf_dataset) Filter by parent id (3.6)
First header is question, field lookup fails encoding="utf-8" passed for an Excel CSV Keep the default utf-8-sig (3.2)
Model receives {tone} or {nope} literally Unknown or None-valued placeholder Test for surviving placeholders (6.5, 7.9)
JSON instructions arrive as {{"category"}: ...} Single braces in a template Double the braces (6.5)
System prompt is prompts/sytem.txt Template path typo; resource() falls back to literal text Read the file yourself or resource(path, type="file") (6.5)
TypeError: ... is not declared as an async callable Inner solve is a plain def async def solve (5.1)
Role model is the main model get_model(role=...) called in the factory Call it inside solve() (7.3)
Two task variants share settings task_with() mutated the shared base task A fresh task per variant (8.4)
.env setting ignored in a notebook INSPECT_EVAL_* variables are read by the CLI, not eval() Pass settings to eval() (8.5)
A second task ran that you did not ask for inspect eval file.py runs every task file.py@name (8.2)
Unknown GenerateConfig field(s): scorer No scorer argument on eval() task_with(task, scorer=...) (8.4)
Letters in two logs disagree for the same answer Different shuffle_choices seeds Compare option text or fix the seed (4.4)
Adaptive run reports "75% accuracy" SampleSource chose the denominator Report the designed quantity (3.10)
Run order differs, results differ Shared mutable state or a shared mock iterator Per-sample store; input-keyed mocks (7.7)

10.6 Decision table#

You need to... Use Section
A handful of cases written in code A list of Samples or MemoryDataset(name=...) 3.1
Load a CSV or JSONL you control csv_dataset/json_dataset with column names input/target, or a FieldSpec 3.2 to 3.5
Transform, validate or expand records A record_to_sample function that raises on bad rows 3.6
Data from the Hub hf_dataset(..., split=, revision=); trust=True only after reading the code 3.7
Parquet, a database, an API Build Samples yourself, wrap in MemoryDataset 3.9
Typed, validated metadata FieldSpec(metadata=FrozenModel) + metadata_as() 2.5
Stable comparisons across runs Explicit ids 2.4
A quick look at a few cases --limit / --sample-id (fixed seed if shuffled) 4.3
Multiple choice choices + letter targets, multiple_choice() + choice(), shuffle_choices=<seed> at load 4.4, 6.7
Adaptive difficulty SampleSource, and report the designed quantity 3.10
A system prompt or prompt wrapper system_message() / prompt_template(), braces doubled, file read strictly 6.2 to 6.5
Retrieval, repair loops, scripted turns A custom @solver that records what it did in the store 7.2, Part 9
A second model inside a solver get_model(role=...) inside solve() 7.3
Something every solver variant must do Task(setup=...) 7.8
Try another solver --solver name -S arg=..., or a solver task argument 8.3
Adapt a packaged task task_with(fresh_task(), ...) 8.4
Reproduce a run inspect log export-config then --run-config 8.6
Share evals across teams A package with an inspect_ai entry point 8.8
Know whether the eval works at all Oracle and null control solvers 10.1

Part 11: evalkit and Inspect, side by side#

Reference

11.1 The mapping#

evalkit (10A.1, 10A.2) Inspect What differs
Example(id, input, reference, metadata) Sample(id, input, target, metadata, choices, ...) target defaults to "" and can be a list; input can be chat messages or multimodal; ids may be assigned at run time
EvalExample (inputs dict, expected, split, tags, rubric, provenance) Sample plus your record_to_sample No split, rubric or provenance fields: carry them in metadata (the adapter in 3.9)
load_dataset(), load_jsonl(), Parquet loader json_dataset, csv_dataset, file_dataset, hf_dataset No Parquet reader in Inspect; CSV and Hub loaders exist
EvalDataset.card and content_sha Dataset.name, Dataset.location, task metadata Inspect logs name and location; a content hash is yours to add
make_splits(), stratified_sample() filter(), slicing, shuffle(seed), --limit with --sample-shuffle Inspect has no stratified splitting; keep 10A.2's functions and filter by the split they assign
to_core_examples(render=...) record_to_sample Same job: decide what text the system under test receives
The task: Example -> str callable The solver chain before generate() Inspect separates prompt construction (solvers) from the call; evalkit's task returns a prompt string
call_model generate (the model under test) and get_model() Inspect owns the model call, its config, concurrency, retries and logging
FakeCallModel / scripted outputs mockllm/model with custom_outputs Same purpose; key the mock on input
run_eval(..., repeats=) eval(task, epochs=) Epochs are reduced per sample before metrics (10B.10)
A prompt-template library (04.10) system_message, prompt_template and the rest Skip-unknown formatting: missing variables do not raise

11.2 Corrections to 10A.10 Part 4.4 and the concept map#

The coordinator will patch 10A.10; until then, read Part 4.4 with these corrections:

  1. The INSTRUCTIONS system prompt is altered before it reaches the model. system_message() treats {"category": ...} as a placeholder and sends {{"category"}: one of ...} (6.5, real output). Double the braces or put the JSON example outside the template.
  2. "Dataset storage: ... parquet" in the concept map: there is no Parquet loader (3.9).
  3. "Repeats: --epochs / sample-level epochs": epochs are per task or per run, with reducers; there are no sample-level epochs (10B.10).
  4. "Slices: dataset metadata columns": true as far as it goes; the slice computation itself is grouped metrics or samples_df().
  5. The failure gallery should add: empty targets pass text scorers, unknown placeholders pass through silently, JSON braces are mangled, a missing template file is sent as its name, csv_dataset's name bug, and task_with() mutation.
  6. Its {{vars}} row says Inspect uses {param}: correct, and the rules in 6.5 are what that means in practice.

Part 12: Older code and tutorials#

Reference

Inspect has renamed several things since 2024. Older tutorials, papers' code and early Inspect Evals tasks use these spellings, and most still load:

python
# s17_legacy.py: older spellings that still load, and what they turn into.
import warnings


from inspect_ai import Task
from inspect_ai.dataset import Sample
from inspect_ai.solver import generate, multiple_choice, system_message

warnings.simplefilter("always")
data = [Sample(input="x", choices=["a", "b"], target="A")]
with warnings.catch_warnings(record=True) as caught:
    t1 = Task(dataset=data, plan=[system_message("old"), generate()])      # pre-"solver" name
    t2 = Task(dataset=data, max_messages=7)                                  # old message_limit
    t3 = Task(dataset=data, epochs=2, epochs_reducer="mode")                 # old reducer argument
    s = multiple_choice(shuffle=True)                                        # old choice shuffling
print("plan= ->", type(t1.solver).__name__, "| max_messages= -> message_limit", t2.message_limit,
      "| epochs_reducer= -> epochs", t3.epochs, "| reducer set:", t3.epochs_reducer is not None)
print("python warnings raised:", len(caught), "(the deprecation notices above go to Inspect's logger)")
Output · real4 lines
DEPRECATED: the 'epochs_reducer' parameter is deprecated (please use the 'epochs' parameter instead)
The multiple choice shuffle parameter is deprecated. Please shuffle choices at the time your dataset is read by using the shuffle_choices method/parameter of the datasets API.
plan= -> Chain | max_messages= -> message_limit 7 | epochs_reducer= -> epochs 2 | reducer set: True
python warnings raised: 0 (the deprecation notices above go to Inspect's logger)
Old Current Behaviour in 0.3.292
Task(plan=[...]) Task(solver=[...]) Accepted silently (a Chain); the source explains it does not warn because "it would affect 100% of evals in the wild"
Plan(...), plan(...) a list of solvers or chain() Still exported; prefer chain()
Task(max_messages=N) message_limit=N Accepted silently
Task(epochs_reducer=...) epochs=Epochs(n, reducer) Works, logs a deprecation notice
Task(tool_environment=...) sandbox=... Works, warns
multiple_choice(shuffle=True) shuffle_choices= on the loader, or dataset.shuffle_choices(seed) Works, logs a deprecation notice
basic_agent(...) react() from inspect_ai.agent Still exported without a warning; the docs lead with react() (10B.14)
from inspect_ai.dataset._dataset import Sample (in one docs example) from inspect_ai.dataset import Sample Private module paths can move in any release
Synchronous def solve(...) (in the source docstrings) async def solve(...) TypeError (5.1)

The deprecation notices go to Inspect's logger, not Python's warnings module (the script caught none), so -W error in a test run will not turn them into failures. Search old code for these names when you port it, and check the changelog's "Breaking Changes" sections for the releases in between.


Common misconceptions#

Misconception Reality
"A sample without a target just won't be scored." target defaults to "", and includes()/match() score an empty target as correct for any output (2.2).
"Samples get ids 1, 2, 3 when the file is loaded." Loaders leave id=None unless you pass auto_id=True; the run numbers the samples by their position at that moment, after any shuffle (2.4).
"limit=10 reads ten records." In csv_dataset and json_dataset it keeps ten samples after conversion and shuffling; in hf_dataset it keeps ten records (3.6).
"Passing name= to csv_dataset names the dataset." Not in 0.3.292: the last column header wins either way; rename with filter(..., name=) (3.2).
"Inspect can read Parquet." It cannot; read with pandas and build a MemoryDataset (3.9).
"A typo in a template placeholder raises an error." Unknown and None-valued placeholders are sent to the model literally (6.5).
"Literal JSON in a system prompt is fine." Single braces are parsed as placeholders and rewritten into invalid text; double them (6.5).
"A missing template file raises FileNotFoundError." Not by default: resource() sends the path itself as the prompt (6.5).
"multiple_choice() needs a generate() after it." It calls the model itself (6.7).
"self_critique() is one extra call." It is two: a critique and a regenerated answer (6.8).
"task_with() returns a modified copy." It modifies the task you pass and returns the same object (8.4).
"INSPECT_EVAL_* settings in .env apply everywhere." They configure the inspect CLI; Python's eval() reads only INSPECT_EVAL_MODEL and a few INSPECT_* settings (8.5).
"I can swap the scorer with a CLI flag." Only task_with() can swap a live task's scorer; inspect score re-scores finished logs (8.4).
"Metadata is a good place for per-sample working data." Metadata is read-only case description; working data goes in the store, which is logged (7.5).
"An accuracy is an accuracy." Not over an adaptive SampleSource, a best-of-n solver or a repair loop that production lacks: say what was measured (3.10, 6.10, Part 9).

Key takeaways#

  • The TaskState is the thread through a task: a sample becomes a state, setup and solvers transform it, scorers read it, cleanup closes it, and the log keeps it. input is the case; messages is what the model receives.
  • Validate the dataset at load time. Raise in record_to_sample on missing or out-of-set labels, use a frozen Pydantic model for metadata, and never let an empty target through: it passes text scorers.
  • Give every sample an explicit, content-independent id. Run-time numbering follows position, and positions change with every shuffle; retries, --sample-id, eval sets and paired comparisons all key on ids.
  • Know your loader's quirks: utf-8-sig CSVs, ragged and duplicate columns refused, all-empty rows dropped, limit counting samples (records on the Hub), no Parquet reader, and the 0.3.292 csv_dataset name bug.
  • Shuffle deliberately: load-time shuffle and run-time --sample-shuffle for random subsets with a fixed seed; shuffle_choices with a fixed seed against position bias, remembering that logged letters are in the shuffled order.
  • Run-time selection belongs to the run: --limit (1-based inclusive ranges on the CLI, 0-based slices in Python), --sample-id with globs, --sample-shuffle. The log records them.
  • Templates fail silently: metadata < store < params; unknown or None placeholders pass through; single JSON braces are mangled; a missing file is sent as its name. Read the rendered prompt in the log and test for surviving placeholders.
  • Solvers are factories returning async functions, registered so their arguments are logged and they can be swapped by name. await every model call, resolve model roles inside solve(), keep shared state out, record what you did in the store.
  • Know what each built-in sends: the exact chain_of_thought(), multiple_choice() and self_critique() templates are in this lesson and in every log's plan; their output formats decide which scorer works.
  • setup survives a solver swap and cleanup survives an exception. Put must-run steps in setup.
  • Configuration has four layers (task, task_with, environment, eval()/CLI), but the environment layer is a CLI feature. Dataset, scorer, metrics and identity change only in code; the run's model, limits, epochs and selection change at run time.
  • task_with() mutates: build a fresh task per variant. eval(metadata=) merges; task_with(metadata=) replaces.
  • Make runs reproducible from their logs: task arguments, version, metadata with a data hash, and inspect log export-config into --run-config.
  • Prove the eval works before trusting it: an oracle solver must score 100%, a null solver 0%, on the same dataset and scorer; for multiple choice add a constant-letter control, whose score is the dataset's real chance baseline.

Terms introduced in this lesson#

Term One-line definition
Sample (Inspect) One eval case: input, target, id, metadata, choices and agent fields
Target (Inspect) The ideal answer, a list of acceptable answers, a choice letter, or grading guidance; defaults to ""
MemoryDataset Inspect's in-memory dataset; every loader returns one, and it wraps samples you build yourself
FieldSpec A mapping from source field names to Sample fields, including metadata columns or a frozen metadata model
record_to_sample A function from one source record to one or more Samples, for transformation and validation at load time
auto_id Loader option that numbers samples at load time, before shuffling
Typed metadata Sample metadata validated by a frozen Pydantic model and read with metadata_as()
Choice shuffling Reordering multiple-choice options and rewriting target letters to match (shuffle_choices)
SampleSource A dataset that produces samples while the task runs, in response to results
Solver (Inspect) An async function (TaskState, generate) -> TaskState; any step that shapes the conversation or calls the model
Solver factory The @solver-decorated function that takes configuration and returns the async solver
TaskState The per-sample, per-epoch state solvers transform: messages, output, metadata, store, target and more
generate (solver argument) The function that calls the model under test on state.messages and sets state.output
Template substitution (Inspect) Rendering {name} from metadata, store and params with unknown placeholders left in place
Store / StoreModel Per-sample key-value state shared by solvers, tools and scorers, logged with the sample; StoreModel is its typed form
setup / cleanup (task) A solver that runs before the main solver even when it is swapped; an async function that runs after each sample even on error
fork() Runs several solvers on deep copies of a state in parallel
Task argument A parameter of an @task function, set with -T, --task-config or task_args, and logged
task_with() Overrides any Task parameter on an existing task, in place
Configuration layers (Inspect) Task definition, task_with(), environment variables, then eval()/CLI, lowest to highest precedence
Run config A YAML or JSON file holding a whole eval configuration for --run-config, exportable from a log
Control solver A solver with a known score (oracle 100%, null 0%) used to check that a task and scorer work
Elicitation How hard and in what way a solver tries to get the right answer out of a model; part of what an eval measures

Exercises#

All exercises run keyless with mockllm/model. Answers follow each one.

  1. Find the empty targets. Write a record_to_sample for data/tickets.jsonl that maps category to target, then delete the category value from one line (leave "category": ""). Make your function raise a ValueError naming the ticket, and confirm the load fails before any model call.

    Answer

    Check if not record.get("category"): raise ValueError(f"{record['ticket_id']}: empty category") before building the Sample. json_dataset("data/tickets.jsonl", record_to_sample) then raises during loading. Without the check, the sample would load with target="" and pass includes() for any output (2.2).

  2. Ids under shuffling. Load data/qa.csv three ways (no ids; auto_id=True; a FieldSpec(id=...) after adding an id column with values q1, q2, q3) and run each with eval(..., sample_shuffle=5). Print (id, input) pairs from the logs. Which of the three give the same pairs as a run without sample_shuffle?

    Answer

    auto_id=True and the explicit id column both keep their pairs, because the ids are set before the run shuffles. The no-id version is numbered after the shuffle, so its pairs change (2.4).

  3. Fix the name. Load data/qa.csv with csv_dataset and give the logged dataset the name quiz-v1. Verify it in log.eval.dataset.name.

    Answer

    csv_dataset("data/qa.csv", spec).filter(lambda s: True, name="quiz-v1"). Passing name="quiz-v1" to csv_dataset alone gives difficulty in 0.3.292 (3.2).

  4. Break and fix a template. Use system_message('Reply as {"label": "spam" or "ham"}. Customer tier: {tier}.') on a sample with metadata={"tier": "gold"} and capture what a scripted model receives. Fix both problems you see.

    Answer

    The JSON is rewritten into {{"label"}: "spam" or "ham"} and {tier} is substituted correctly. Fix the braces by doubling them: 'Reply as {{"label": "spam" or "ham"}}. Customer tier: {tier}.'. Also test a sample without tier: {tier} reaches the model literally, so either require it in typed metadata (2.5) or give it a default with a parameter (system_message(..., tier="standard"), remembering that params beat metadata, so put the default in metadata at load time instead if per-sample values must win).

  5. A guard solver. Write a solver that answers tickets shorter than 10 characters with {"category": "other", "priority": "P3"} without calling the model, and lets the rest through to generate(). Count how many samples it handled in the store.

    Answer

    Inside solve, if len(state.input_text.strip()) < 10: set state.output = ModelOutput.from_content(model="rule", content=...), state.store.set("guarded", True), state.completed = True. Count s.store.get("guarded") over log.samples. Report the guarded share alongside accuracy (7.4).

  6. Solver swap with setup. Add a setup solver to Part 9's task that stores the company name, change the system prompt to read {company} from the store, then run with eval(task, solver=[system_message("triage_system.txt"), generate()]). Does the company still appear in the prompt?

    Answer

    Yes: setup runs even when the solver is swapped, and template solvers read the store (7.8, 6.5). Remove the setup and run again: the placeholder survives literally, which your placeholder test (7.9) should catch.

  7. task_with variants. From Part 9's triage(), build three variants with message limits 1, 2 and 3 using task_with. First do it wrongly (one base task) and print each variant's message_limit; then do it right.

    Answer

    With one base, all three names point at the same object and all show 3. With task_with(triage(), message_limit=n) per variant, they show 1, 2, 3 (8.4).

  8. Controls for multiple choice. Build a 10-question multiple-choice dataset where 7 targets are "A". Implement the constant-letter control as multiple_choice() driven by a mockllm/model whose custom_outputs always return ANSWER: A (or as a solver that calls state.choices.mark_choice(0, True); a solver that only sets state.output scores 0, because choice() reads the marked choices, not the text). Run it, then shuffle the choices with a seed and run again. Explain the two numbers.

    Answer

    Unshuffled, the constant solver scores 70%: the "chance" baseline of your dataset, not 25%. After shuffle_choices(seed=...), the correct letters are spread out and the constant solver drops towards 25% (with only 10 questions, the exact value depends on the seed). Any real model's score must be read against that baseline (10.1, 4.4).

  9. Reproduce from a log. Run Part 9's task from the CLI with -T max_attempts=1 --limit 4, export its configuration with inspect log export-config, and rerun with --run-config. Compare task_args and limit in the two logs.

    Answer

    They match: the exported YAML contains the task reference, all task arguments (including defaults), the model and eval_config with the limit (8.6). Change tickets.jsonl and rerun: the config still matches, but the results may not, which is why the dataset hash belongs in metadata (8.7).

  10. Adaptive data. Modify s12_sample_source.py so that the scripted model is right up to n <= 6. What does the log's accuracy report now, and what is the right summary?

    Answer

    The run goes to level 5 (n = 6) correct and fails at level 6 (n = 7): six samples, five correct, accuracy 0.833, compared with 0.75 before. The accuracy barely moved while the capability (highest level passed: 5 against 3) changed a lot. Report the highest level passed (3.10).


Check yourself#

  1. What is the default value of Sample.target, and why is it dangerous?
  2. When does a sample with no id in the file receive its id, and what does that imply for comparing two runs that used --sample-shuffle?
  3. What does auto_id=True change?
  4. Which encoding does csv_dataset use by default, and what problem does it solve?
  5. In json_dataset, what does limit=5 count if your record_to_sample returns three samples per record? And in hf_dataset?
  6. Why must a metadata model passed to FieldSpec be frozen=True, and where should mutable per-sample data go?
  7. Where does system_message() put its message when the sample input already starts with a system message?
  8. A template contains {plan} and the sample's metadata has plan: None. What does the model receive?
  9. Why does system_message('Reply as {"a": 1}') not send what you wrote, and what is the fix?
  10. Which solver calls the model itself, so you must not add generate() after it?
  11. Why should get_model(role="grader") be called inside solve() and not in the solver factory?
  12. What happens to setup when you run inspect eval task.py --solver other?
  13. t2 = task_with(t1, message_limit=50). What is t1.message_limit now?
  14. You put INSPECT_EVAL_EPOCHS=5 in .env. Which of inspect eval task.py and a Python script calling eval(task()) runs five epochs?
  15. Name the two control solvers and the score each must get.

Further resources#

Official Inspect documentation (each page also exists as Markdown: append .md to the .html URL; https://inspect.aisi.org.uk/llms.txt is the index):

In this course: 10A.1 (evalkit's Example and run_eval), 10A.2 (dataset design, splits, versioning), 10A.7, 5.5 (controls and self-tests), 10A.10, Part 4 (the first Inspect task), 04.10 (prompt templates and versioning), and the next lessons of the track: 10B.10 (scorers, metrics, epochs), 10B.11 (model grading), 10B.12 (running at scale).


← 10B.8: Inspect AI Fundamentals: Task = Dataset + Solver + Scorer (optional) | Module 10B overview | 10B.10: Inspect Scorers, Metrics, Epochs and the Statistics Inspect Reports (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