10B.12 Running Inspect Evals for Real: Models, Configuration, Concurrency, Caching, Errors and Eval Sets (optional)

ProductionLesson 12 of 1824,830 wordsOptional16 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

The first four Inspect lessons built an eval and made its number defensible: a task (10B.8), its data and solvers (10B.9), its scorers and statistics (10B.10) and its model grader (10B.11). All of that ran against a scripted mock on twelve tickets in about a second. Real runs are different. A real run sends thousands of requests to a provider that rate-limits you, times out, returns 500s, occasionally refuses, silently upgrades the model behind an alias, and bills you for every token, while your laptop goes to sleep or your CI runner is killed halfway through. This lesson is about everything between "the task works" and "the number is in the release report": choosing and configuring models, what each GenerateConfig field does and which value actually reaches the provider, how Inspect decides how many requests are in flight, the three layers of retries and how they interact, the response cache and its traps, batch mode, the error policy and what it does to your denominator, recovering failed and crashed runs, eval sets as the unit of a real run, and a CI gate that cannot go green on a broken eval. Every behaviour is shown on a keyless run whose output is real, including rate limiting, a transient network failure, a kill -9 in the middle of a run and the recovery afterwards.

What you'll learn

  • Model strings for every kind of provider, running several models in one command (--model a,b and --model-spec), model arguments, the none model, and how to pin a model version so a number stays reproducible
  • get_model() in production: memoization (and the one provider it does not apply to), calling a model outside an eval, context managers, and model roles as the run-time switch for every model that is not the one under test
  • Writing your own provider with @modelapi, and using it to run any call_model(prompt) -> str function, such as evalkit's, inside Inspect with retries and concurrency limits
  • GenerateConfig field by field, the five places a setting can come from, which one wins (measured, including two places where the log disagrees with what was sent), and what each provider honours
  • Concurrency: adaptive connections (start 20, grow to 100, back off on rate limits), static max_connections, max_samples, max_tasks, the other limits, sharding a task across processes, and how to choose, all with measured peak in-flight counts
  • Model-call retries and timeouts: max_retries, timeout, attempt_timeout, stream_idle_timeout, the backoff schedule, and how a transient failure stays invisible to the sample
  • Inspect's response cache: what is in the key, what is not, CachePolicy, why caching and epochs need care, why a model built from a Python callable caches per instance only, and inspect cache
  • Batch mode: when the provider batch APIs pay off and when they make an eval take days
  • The sample error policy: fail_on_error as a boolean, a proportion or a count, continue_on_fail, retry_on_error and the distribution shift it can cause, score_on_error, refusals and fail_on_refusal, and errors raised by scorers
  • Recovering work: eval_retry() (what it re-runs, where the new log goes, why your task files must be import-safe), crash recovery after a killed process, and stalled samples
  • Eval sets: the log directory as the unit of work, automatic retries, sample reuse, no-op re-runs, amending a set, task identity, dirty directories, exit codes, suites built from directories and attributes, and publishing
  • Early stopping, and why it silently does nothing under default concurrency
  • A production CI gate over an eval set that checks completeness, coverage, errors, retries, refusals, task versions, floors and paired non-regression, plus the GitHub Actions workflow around it
  • The methodology of a real run: the pre-flight ladder, the reproducibility record, a failure gallery and a decision table

What you don't need

  • An API key. Every runnable sample uses mockllm/model or a small provider written in this lesson, and every output marked as real is what those runs printed. Samples that name a real provider (OpenAI, Anthropic, and the optional Google and OpenRouter) or use batch mode are labelled illustrative.
  • Docker, a server or a hosted service. Nothing here starts one. The crash-recovery demonstration kills a local Python process, nothing else.
  • The task-building material. Datasets, solvers and task configuration files are 10B.9, scoring and statistics 10B.10, model grading 10B.11, logs and dataframes in depth 10B.13, and per-sample limits for agents (message_limit, token_limit, time_limit, cost_limit) 10B.15. This lesson links to them and never re-teaches them.
  • The provider-neutral engineering. Rate limits, retries and backoff are 03.8; concurrency and batch APIs 03.9; prompt caching and cost 03.7; regression gates and their statistics 10A.8. Here they are mapped onto Inspect's settings.

Setup

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

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

The samples reuse three files from 10B.8, Part 4: triage.py (the twelve-ticket triage task with its triage_format and triage_labels scorers), fake_triage.py (the scripted mock, scripted_model(), and its RESPONSES table) and the idea of the log gate in gate.py. Put them in the same folder. The CI gate in Part 13 also imports evalkit.compare from 10A.8, 4.1 (stdlib only; copy the evalkit/ folder next to the samples). For the illustrative real-provider runs you would add the provider SDK (uv add openai, uv add anthropic, or the optional uv add google-genai; OpenRouter, also optional, goes through openai) and a key in .env.

Several samples are split across files that import each other, so run them with uv run python file.py from that folder (Python puts the script's own folder on the import path). CLI commands are uv run inspect ... from the same folder.

Versions (current at time of writing, read from PyPI on 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT licence, Python ≥ 3.11). Every sample marked as run was executed on 24 November 2026 with Python 3.13.14 and inspect-ai 0.3.292, using uv run --no-project --with inspect-ai, and the output blocks are what those runs printed, trimmed only where marked. Timings in the outputs come from a laptop and will differ on yours. The official documentation and the installed package source were checked the same day. Inspect ships a release every few days and several facts in this lesson changed during 2026 (the changelog dates are given where they matter), so re-check against inspect eval --help and the changelog for the version you install.


What you must be able to do after this lesson#

  • Name the three retry layers in an Inspect run and what each retries
  • Choose a sample error policy (fail_on_error, continue_on_fail) and say how it can inflate a score
  • Work out which GenerateConfig value reaches the provider
  • Run an eval set and recover a run with eval_retry()
  • Use the response cache and read its cache key
  • Build a CI gate that fails on a broken or empty eval

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Run the same eval on three models tonight." 2.3 and Part 11
"Our internal model sits behind an HTTP endpoint. Can Inspect evaluate it?" 2.7
"I set temperature 0, so the eval is deterministic." 3.4 and 3.5
"Which max_tokens did the model actually get?" 3.1
"We hit the rate limit. Turn concurrency down to 10." Part 4
"The run hung for twenty minutes on one sample." Part 5
"Cache the responses so re-runs are free." Part 6
"Use the batch API, it's half price." Part 7
"Three samples errored. Is the 0.94 still valid?" Part 8
"Just add --retry-on-error." 8.4
"The laptop went to sleep in the middle of the run." 9.4
"Re-run the eval set; it will pick up where it stopped." Part 11
"Can we stop sampling once the answer is clear?" Part 12
"CI was green, but the eval had crashed." Part 13
"How do I defend a number from a 6-hour run?" Part 14

Part 1: From a demo run to a real run#

1.1 What changes when the model is real#

Every earlier Inspect lesson ran in a second against mockllm/model. Swap in a hosted model and five things change at once:

Concern Demo run Real run Where
Which model, exactly mockllm/model, never changes A provider alias that can be upgraded under you, with provider-specific options Part 2
Generation settings Ignored by the mock Some honoured, some dropped with a warning, some rejected, depending on provider and model Part 3
Throughput Unlimited Bounded by rate limits you do not control and only partly know Part 4
Failure None Timeouts, 429s, 5xx, refusals, your own bugs on rare inputs, crashes of your own process Parts 5, 8, 9
Cost and time Zero Real money per token and hours of wall time, so re-runs, caching and batching matter Parts 6, 7, 11

None of this changes what the task is. The dataset, solver, scorers and their statistics are exactly what 10B.8 to 10B.11 built. What changes is the run: the set of choices made when you execute the task, recorded in the log, and the failures that happen during it.

1.2 One run, layer by layer#

The single most useful picture for this lesson is where each kind of failure is handled. Inspect has three retry layers and one "give up" decision at each, and they are easy to confuse:

flowchart TB
    subgraph setl ["Eval set (Part 11): one log directory"]
        S1["Task x model pairs, each a log file"]
        S2{"Task log status = error?"}
        S3["Retry the task (retry_attempts, default 10), reusing completed samples"]
    end
    subgraph taskl ["Task run (Parts 8 and 9)"]
        T1["Samples run concurrently (Part 4)"]
        T2{"Sample raised?"}
        T3["retry_on_error: re-run the sample from scratch"]
        T4{"Errors over fail_on_error threshold?"}
    end
    subgraph modell ["Model call (Part 5)"]
        M1["generate() request to the provider"]
        M2{"Provider error retryable?"}
        M3["Back off and retry (max_retries, timeout)"]
    end
    S1 --> T1
    T1 --> M1
    M1 --> M2
    M2 -->|"yes"| M3
    M3 --> M1
    M2 -->|"no, or retries exhausted"| T2
    T2 -->|"yes"| T3
    T3 --> T1
    T2 -->|"retries exhausted"| T4
    T4 -->|"yes: log status error"| S2
    T4 -->|"no: sample logged with error, not scored"| S1
    S2 -->|"yes"| S3
    S3 --> S1

Read it from the inside out:

  1. Model-call retries (Part 5). A request that fails with an error the provider marks as transient (a 429, a 5xx, a dropped connection) is retried inside the model layer with exponential backoff. The sample never sees it, unless the retries run out.
  2. Sample retries (8.4). An exception that escapes the solver or scorer is a sample error. With retry_on_error, the whole sample runs again from the start. Without it, or once it is used up, the sample is recorded with its error and is not scored.
  3. The error threshold (8.2). fail_on_error decides whether the errors so far are too many: if so, the task's log gets status error.
  4. Task retries (Part 9, Part 11). A task log with status error (or started, after a crash) can be retried by eval_retry() or automatically by an eval set, and the retry reuses the samples that already completed.

Each layer has a different effect on what you measure. Model-call retries are invisible and harmless (the same request, sent again). Sample retries re-roll the whole sample and can bias the result (8.4). Errors that are tolerated leave the denominator (10B.10, 4.6). Task retries reuse finished samples, so they are only as safe as your sample ids are stable (11.6).

1.3 The files this lesson uses#

File What it is First used
triage.py, fake_triage.py 10B.8's triage task and scripted mock, unchanged 2.7
triage_call_model.py 10A.1's FakeTriageModel as a plain call_model(prompt) -> str function 2.7
callmodel_api.py A model provider that runs any call_model function inside Inspect 2.7
orders_task.py A six-sample task whose "order lookup" step fails on demand (a flag file), and which logs every attempt Part 9
slow_task.py A twenty-sample task with a half-second step, for the crash demonstration 9.4
ci_gate.py, gate_spec.json The production gate over an eval-set directory Part 13

Every task file in this lesson only defines tasks; none runs an eval when imported. That is not style: 9.2 shows what breaks otherwise.

1.4 What this lesson adds to 10B.8 to 10B.11#

Earlier lesson gave you This lesson adds
--model, a model string table and .env keys (10B.8, 4.9) Every provider family, model specs, model args, version pinning, get_model() internals, custom providers
The four configuration layers and run-config files (10B.9, 8.5) Where a GenerateConfig value comes from, measured at the provider, and what each provider does with it
"Inspect exits 0 on a failed run" and a minimal log gate (10B.8, 9.6) The full error policy, recovery, eval sets, and the production gate
score_on_error and the silent TimeoutError (10B.10, 4.3) The other error settings and how they compose
Epochs and caching in one paragraph (10B.10, 7.11); the grader's nonce defeats caching (10B.11, 8.3) The cache in full, including a race between concurrent epochs
The rules of a gate on Inspect numbers (10B.10, 8.8) Those rules as running code over an eval set

Part 2: Models and providers#

2.1 Model strings#

Every model in Inspect is named provider/model-name, and the part before the first slash picks the code that talks to the API. The built-in providers, from the models page as of November 2026:

Family Providers (prefix in parentheses where it is not obvious)
Lab APIs OpenAI (openai), Anthropic (anthropic), Google (google), Grok (grok), Mistral, DeepSeek, Moonshot AI, Meta, Perplexity
Cloud APIs AWS Bedrock, AWS SageMaker, Azure AI
Hosted open models Groq, Together AI, Fireworks AI, Cloudflare (cloudflare, renamed from cf in 0.3.248), Hugging Face Inference Providers, SambaNova
Local inference (optional, see 11C.6) Hugging Face (hf), vLLM (vllm), Ollama (ollama), llama-cpp-python, SGLang, TransformerLens, nnterp
Anything else Any OpenAI-compatible endpoint (openai-api/<service>/<model>), OpenRouter (openrouter/<vendor>/<model>), a LiteLLM proxy (litellm-proxy/<name>), or your own provider (2.7)
Testing mockllm/<anything> (the scripted mock of 10B.8, 3.3) and none (no model)

The provider SDK is not part of inspect-ai: --model openai/... fails until you uv add openai. The providers page is the authority for each provider's environment variables, model arguments and quirks, and it is long (about fourteen thousand words); read your provider's section before your first real run, not this lesson's summary of it.

2.2 Two primary and two optional providers#

OpenAI and Anthropic are the two primary providers of this course; Google (Gemini) and OpenRouter are optional, so read their rows only if you use them. The table gives the settings for all four (as of November 2026; model ids from 02.9, Part 2):

Provider Model string SDK Key variable Worth knowing
OpenAI openai/gpt-6-luna openai OPENAI_API_KEY Uses the Responses API for GPT-5 and later (-M responses_api=false switches to Chat Completions); -M service_tier=flex for the cheaper, slower flex tier (03.9, Part 12); OPENAI_BASE_URL for a proxy
Anthropic anthropic/claude-haiku-5-5 anthropic ANTHROPIC_API_KEY Does not send temperature, top_p or top_k (the API rejects them since version 2026-10-21) and logs a warning if you set them; prompt caching is on by default (-M cache_ttl=1h changes the TTL); --fallback-models retries refused requests on another Claude model (first-party API only)
Google (optional) google/gemini-3.8-flash google-genai GOOGLE_API_KEY (0.3.292 also accepts GEMINI_API_KEY; GOOGLE_API_KEY wins if both are set) -M arguments go to genai.Client; Vertex AI and OAuth are configured through the provider's own variables; requests default to a one-hour SDK timeout unless you set timeout
OpenRouter (optional) openrouter/openai/gpt-6-luna (any vendor/model from the catalogue) openai OPENROUTER_API_KEY -M models=... for OpenRouter's own fallbacks, -M provider=... for routing; Anthropic prompt caching is on by default for openrouter/anthropic/* and Inspect pins each sample to one backend with an x-session-id header

Two more you will meet in companies:

  • OpenAI-compatible endpoints. openai-api/<service>/<model> reads <SERVICE>_API_KEY and <SERVICE>_BASE_URL (upper case, hyphens become underscores). An internal gateway that speaks the Chat Completions protocol becomes openai-api/gateway/our-model with GATEWAY_BASE_URL and GATEWAY_API_KEY in .env. This is usually the shortest path to evaluating an in-house deployment.
  • LiteLLM proxy. litellm-proxy/<model_name> with LITELLM_PROXY_BASE_URL and LITELLM_PROXY_API_KEY; Inspect reads the proxy's model listing to find the upstream model (for context windows and prices).
bash
# illustrative: each line needs the provider SDK and a key in .env
uv run inspect eval triage.py --model openai/gpt-6-luna
uv run inspect eval triage.py --model anthropic/claude-haiku-5-5
uv run inspect eval triage.py --model google/gemini-3.8-flash                # optional
uv run inspect eval triage.py --model openrouter/anthropic/claude-haiku-5.5  # optional
uv run inspect eval triage.py --model openai-api/gateway/support-triage-v3   # GATEWAY_BASE_URL, GATEWAY_API_KEY

Example output (illustrative — your exact output will differ): one results panel per command, in the shape of 10B.8, 4.9, with that provider's token counts; nothing here was run, because each line needs a key.

2.3 Choosing models for a run#

Four ways to say which model(s) to evaluate, from the most to the least explicit:

How Example Use when
--model / eval(model=...) --model openai/gpt-6-luna One model
A comma-separated list --model openai/gpt-6-luna,anthropic/claude-haiku-5-5 Several models with the same settings; one log per model, run in parallel
--model-spec, once per model --model-spec '{model: openai/gpt-6-luna, reasoning_effort: low}' Each model needs its own settings, or the same model twice with different settings
INSPECT_EVAL_MODEL in .env or the shell INSPECT_EVAL_MODEL=openai/gpt-6-luna A personal default; the only INSPECT_EVAL_* variable that Python's eval() also reads (10B.9, 8.5)

A model spec is the same mapping as a model role binding: a required model, any GenerateConfig field, model_args and base_url. Keyless, two specs for the same mock with different settings:

bash
# r13_model_spec.sh: one model, two configurations, one command (lesson 10B.12)
inspect eval orders_task.py --log-dir logs-r13 --display none \
  --model-spec '{model: mockllm/model, max_tokens: 64}' \
  --model-spec '{model: mockllm/model, max_tokens: 512, seed: 42}'
python -c "
from inspect_ai.log import list_eval_logs, read_eval_log
for info in reversed(list_eval_logs('logs-r13')):
    log = read_eval_log(info)
    cfg = next(e for e in log.samples[0].events if e.event == 'model').config
    print(log.eval.model, '| max_tokens sent:', cfg.max_tokens, '| seed sent:', cfg.seed, '|', log.status)
"
Output · real2 lines
mockllm/model | max_tokens sent: 64 | seed sent: None | success
mockllm/model | max_tokens sent: 512 | seed sent: 42 | success

Two logs, one per spec, each with its own settings recorded on the model call itself. (orders_task.py is printed in 9.1; any task works here.) Rules that bite:

  • --model-spec cannot be combined with --model, --model-base-url, --model-config or -M; put those inside each spec.
  • A generation flag on the command line (--max-tokens 100) overrides the same field in every spec. To compare settings, set them only in the specs.
  • A role you leave unset (grader, say) falls back to the model of the spec being run, so each model would grade its own samples (10B.11, 5.1). Bind the grader explicitly with --model-role when you compare models.
  • In an eval set, two specs that differ only in base_url or credentials are rejected as not distinct, because task identity ignores them (11.4).

Model arguments are constructor options that are not generation settings: -M key=value, --model-config file.yaml, eval(model_args={...}) or keyword arguments to get_model(). They go to the provider's client (-M service_tier=flex for OpenAI, -M location=us-east5 for Google on Vertex, -M emulate_tools=true for an OpenAI-compatible endpoint without native tool calls). Each provider's section of the providers page lists its own. --model-base-url (or <PROVIDER>_BASE_URL) points a provider at a proxy.

No model. --model none or eval(model=None) runs with the none provider. Use it for tasks that only call role-bound models or no model at all, and to stop a stray INSPECT_EVAL_MODEL from being picked up. A task that calls generate() under none fails:

python
# r01_models.py: get_model(), memoization, and calling a model outside an eval (lesson 10B.12)
import asyncio

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model

# get_model() memoizes: identical arguments return the same Model object...
# ...except for mockllm, which 0.3.292 never memoizes (see r03 for a provider that is).
a = get_model("mockllm/model")
b = get_model("mockllm/model")
print("mockllm, same arguments -> same object:", a is b)
print("name:", a.name, "| str(model):", str(a), "| api:", type(a.api).__name__)


async def main() -> None:
    # A Model can be called directly, outside any eval: a quick smoke test of credentials,
    # a one-off generation in a notebook, or a helper in a script.
    out = await a.generate("Classify this ticket: my invoice is wrong")
    print("completion:", out.completion, "| stop_reason:", out.stop_reason)
    print("usage:", out.usage.input_tokens, "in /", out.usage.output_tokens, "out (mock numbers)")

asyncio.run(main())

# --model none: a task that calls generate() with no model fails as a PrerequisiteError
log = eval(Task(dataset=[Sample(input="hi", target="x")], name="no_model"),
           model=None, log_dir="logs-r01", display="none")[0]
print("model=None ->", log.status, "|", type(log.error).__name__ if log.error else None,
      "|", log.error.message if log.error else None)
bash
uv run python r01_models.py
Output · real5 lines
mockllm, same arguments -> same object: False
name: model | str(model): mockllm/model | api: MockLLM
completion: Default output from mockllm/model | stop_reason: stop
usage: 9 in / 33 out (mock numbers)
model=None -> error | EvalError | No model specified (and no model environment variable defined)

The last line is the none model at work: the run fails with status error, and the message names the cause. The first lines are about get_model(), next.

2.4 get_model() in production code#

10B.9, 7.3 covered calling get_model() inside a solver (and why role lookups belong inside solve()). Four facts matter once you run at scale:

Memoization, and its exception. get_model() caches Model objects in a module-level dictionary keyed on the model string, role, config, base URL, API key and model args, so a solver that calls get_model("openai/gpt-6-luna") on every sample reuses one client and one connection pool. The run above shows the exception: mockllm is never memoized in 0.3.292 (the source excludes it because its custom_outputs can be a generator that must not be shared). So the memoize=False you see in the keyless samples of 10B.8 to 10B.11 is harmless but not needed for the mock; it matters for real providers, where you want a fresh Model only when you deliberately need separate state. 2.7 shows memoization working for an ordinary provider.

Calling a model outside an eval. await model.generate("...") works anywhere you can await: the run above called the mock directly and got its default reply, a stop reason and (fake) usage. Use it for a credentials smoke test before a long run, in notebooks, or in helper scripts. Inside an eval, the same call is recorded in the sample's transcript and counted in its usage.

Closing clients. A Model is an async context manager (async with get_model(...) as model:), which closes the provider's HTTP client when the block ends. Short scripts rarely need it. Use it in long-lived processes (a service that runs evals on demand) so connections do not accumulate. A sync with form exists, but the docs warn it does not work for providers that need an async close (OpenAI, Anthropic, Grok, Together, Groq, Ollama, llama-cpp-python, Cloudflare).

Configuration on the model. get_model(..., config=GenerateConfig(...)) gives the model its own settings, which are the lowest layer of the precedence measured in 3.1: a Task's config or an eval() argument overrides them.

2.5 Model roles at run time#

A model role is a named slot (grader, critic, user_simulator, red_team) that code looks up with get_model(role="...") and the caller binds at run time. 10B.9, 7.3 covers lookups in solvers and 10B.11, 5.3 lists every surface that binds a role (Task, task_with, eval(), --model-role, inline YAML with settings, run-config files, a comma-separated list for a panel). What matters for running:

  • Roles are the run-time switch for every model that is not the model under test. Never hard-code a second model id in a solver or scorer you intend to reuse; give it a role with a sensible default=, so a CI job can bind a cheap model and a release run a validated one, with no code change.
  • Roles inherit operational settings, not generation settings. An eval() or CLI max_connections, max_retries, timeout or cache reaches role models too (10B.11, 8.3 measured this for cache), while --temperature or --max-tokens configures only the model under test. A role's own settings go in its binding.
  • The log records every role (eval.model_roles) and its usage separately (stats.role_usage, and a grader (role) line in the results panel). In an eval set, bind roles per task with task_with(..., model_roles=...) when you want to vary the role across tasks; a role given to eval_set() applies to all of them.
  • Each role model has its own connection pool (4.7), so a slow grader does not starve the model under test of connections, and vice versa.

2.6 Pinning the model version#

A model name like gpt-6-luna is often an alias that the provider moves to a newer snapshot when one ships. Inspect records the name you passed, not the snapshot that served the request, so two runs a month apart can show "the same model" producing different numbers with nothing in your code or the log to explain it. 02.9, Part 8 covers how each provider versions its models. For evals:

  1. Use a dated snapshot id where the provider offers one, for the model under test and for every role model (a grader alias that moves is worse, because it changes your instrument; 10B.11, 5.4).
  2. Where there is no snapshot id (some gateways, OpenRouter routes, local servers), record what you can: the provider's response model field (ModelOutput.model holds what the provider reported), the gateway's deployment name, the local weights' checksum. Put it in the run's --metadata.
  3. Treat a model upgrade as a new baseline. 10A.8, 8.1 is the playbook; the Inspect-specific step is clearing the cache for that model (6.6), because the cache key contains the name, not the snapshot.

2.7 Your own provider: @modelapi and evalkit's call_model#

Sooner or later you need to evaluate something that is not a vendor model: an internal service behind your own HTTP API, a RAG pipeline that takes a question and returns an answer, a fine-tuned model behind a bespoke endpoint, or simply the call_model(prompt) -> str callable that evalkit (10A.1, Part 6) used everywhere. An OpenAI-compatible endpoint is covered by openai-api/... (2.2). Anything else becomes a provider with @modelapi (the Model API extension page), and once it is a provider it gets everything this lesson describes for free: concurrency limits, retries with backoff, caching, usage in the log and the transcript of every request.

First, 10A.1's FakeTriageModel as a plain function, the shape of evalkit's CallModel:

python
# triage_call_model.py: 10A.1's FakeTriageModel as a plain call_model function (lesson 10B.12)
from fake_triage import RESPONSES
from triage import TICKETS


def fake_call_model(prompt: str) -> str:
    """Look the ticket text up in the prompt and return 10A.1's scripted answer."""
    for tid, text, _ref, _meta in TICKETS:
        if text and text in prompt:
            return RESPONSES[tid]
    return RESPONSES["T10"]                # the empty ticket matches nothing above

Then the provider. It keeps a registry of callables by name, so callmodel/<name> selects one:

python
# callmodel_api.py: an Inspect model provider that wraps any call_model(prompt) -> str (lesson 10B.12)
"""Register plain Python callables (evalkit's CallModel shape) as Inspect models.

    register_call_model("triage-fake", fake_call_model)
    eval(triage(), model="callmodel/triage-fake")

The callable runs in a worker thread, so a blocking HTTP client inside it does
not stall Inspect's event loop. ConnectionError and TimeoutError are reported
as transient, so Inspect's model layer retries them with backoff; anything else
fails the call at once and becomes a sample error.
"""
from __future__ import annotations

from collections.abc import Callable
from typing import Any

import anyio

from inspect_ai.model import (ChatMessage, GenerateConfig, ModelAPI, ModelCall,
                              ModelOutput, RetryDecision, modelapi)
from inspect_ai.tool import ToolChoice, ToolInfo

CallModel = Callable[[str], str]          # evalkit's seam, from lesson 10A.1
CALL_MODELS: dict[str, CallModel] = {}


def register_call_model(name: str, fn: CallModel) -> None:
    """Make `fn` available as the model `callmodel/<name>`."""
    CALL_MODELS[name] = fn


class CallModelAPI(ModelAPI):
    def __init__(self, model_name: str, base_url: str | None = None,
                 api_key: str | None = None, api_key_vars: list[str] = [],
                 config: GenerateConfig = GenerateConfig(), **model_args: Any) -> None:
        super().__init__(model_name, base_url, api_key, api_key_vars, config)
        if model_name not in CALL_MODELS:
            raise ValueError(f"no call_model registered as {model_name!r}; "
                             f"known: {sorted(CALL_MODELS)}")
        self.call_model = CALL_MODELS[model_name]

    async def generate(self, input: list[ChatMessage], tools: list[ToolInfo],
                       tool_choice: ToolChoice, config: GenerateConfig
                       ) -> tuple[ModelOutput, ModelCall]:
        # evalkit's call_model takes one string: flatten the conversation
        prompt = "\n\n".join(message.text for message in input)
        text = await anyio.to_thread.run_sync(self.call_model, prompt)
        call = ModelCall.create(request={"prompt": prompt}, response={"text": text})
        return ModelOutput.from_content(model=self.model_name, content=text), call

    def should_retry(self, ex: Exception) -> RetryDecision:
        # transient: retried with exponential backoff, without shrinking concurrency
        if isinstance(ex, (ConnectionError, TimeoutError)):
            return RetryDecision.transient()
        return RetryDecision.no()

    def max_connections(self) -> int:
        return 4                           # the static default for this provider

    def connection_key(self) -> str:
        return self.model_name             # one connection pool per registered callable


@modelapi(name="callmodel")
def callmodel() -> type[ModelAPI]:
    return CallModelAPI

What each piece is for:

Piece Why
super().__init__(...) Required; sets up the name, base URL, key handling and config
async def generate(...) The one required method: Inspect's messages in, a ModelOutput out. Returning (output, ModelCall) records the raw request and response in the transcript, which is invaluable when the integration misbehaves; ModelCall.create(..., filter=...) can redact fields (images, secrets) first
anyio.to_thread.run_sync call_model is synchronous; running it in a thread keeps the event loop free so other samples proceed. A native async client would be awaited directly
should_retry() Which exceptions the model layer retries (Part 5). Return RetryDecision.rate_limit() for 429-style errors so adaptive concurrency backs off, RetryDecision.transient() for blips, RetryDecision.no() for bugs. The default is "never retry". A RetryDecision can also carry the server's retry_after (pass it to rate_limit() or transient()), and the provider can override retry_wait() to change the backoff schedule: honouring a gateway's Retry-After header is the most useful thing a custom provider can do for a rate-limited run
max_connections() The static default when the user does not set one (Inspect's own default is 10)
connection_key() Which calls share a connection limit; the docs suggest the API key, so limits are per account
@modelapi(name=...) on a function that returns the class The indirection lets a package register many providers without importing their SDKs until one is used

Other optional overrides exist for default max_tokens, credential refresh after an authentication failure (is_auth_failure(), refresh_credentials()), message collapsing for APIs that reject consecutive user messages, token counting and more; the extension page lists them. To make the provider available by name to the CLI and to other people, ship it in a package with an inspect_ai entry point (10B.9, 8.8 shows the mechanism for tasks; providers use the same one).

Now use it, including a transient failure, keyless:

python
# r03_provider.py: evalkit's call_model as an Inspect provider; model-layer retries (lesson 10B.12)
import time

from inspect_ai import eval
from inspect_ai.model import get_model

from callmodel_api import register_call_model
from triage import triage
from triage_call_model import fake_call_model


FAILURES = {"left": 0}


def flaky_call_model(prompt: str) -> str:
    """Like fake_call_model, but the T05 request fails while FAILURES['left'] > 0."""
    if "standing desks" in prompt and FAILURES["left"] > 0:       # T05's ticket text
        FAILURES["left"] -= 1
        raise ConnectionError("connection reset by peer")
    return fake_call_model(prompt)


register_call_model("triage-fake", fake_call_model)
register_call_model("triage-flaky", flaky_call_model)

# 1. The bridge: the same numbers as 10B.8's scripted mock
log = eval(triage(), model="callmodel/triage-fake", log_dir="logs-r03", display="none")[0]
print("1 callmodel/triage-fake:", log.status, {s.name: round(list(s.metrics.values())[0].value, 3)
                                               for s in log.results.scores})

# 2. Memoization works for ordinary providers (mockllm is the exception)
print("2 memoized:", get_model("callmodel/triage-fake") is get_model("callmodel/triage-fake"))

# 3. A transient failure is retried inside the model layer: the sample never sees it
FAILURES["left"] = 1
start = time.perf_counter()
log = eval(triage(), model="callmodel/triage-flaky", log_dir="logs-r03", display="none")[0]
t05 = next(s for s in log.samples if s.id == "T05")
attempts = [e.error or "ok" for e in t05.events if e.event == "model"]   # one model event per attempt
print(f"3 one transient failure: status={log.status} | T05 sample error={t05.error} "
      f"| T05 attempts={attempts} | {time.perf_counter() - start:.1f}s")

# 4. With max_retries=0 the same failure escapes the model layer and becomes a sample error
FAILURES["left"] = 1
log = eval(triage(), model="callmodel/triage-flaky", max_retries=0,
           log_dir="logs-r03", display="none")[0]
print("4 max_retries=0:", log.status, "|", log.error.message if log.error else None)
bash
uv run python r03_provider.py
Output · real4 lines
1 callmodel/triage-fake: success {'triage_format': 0.917, 'triage_labels': 0.889}
2 memoized: True
3 one transient failure: status=success | T05 sample error=None | T05 attempts=["ConnectionError('connection reset by peer')", 'ok'] | 5.2s
4 max_retries=0: error | RetryError(<Future at 0x10b16ba50 state=finished raised ConnectionError>)
  1. The bridge measures the same thing. 0.917 and 0.889 are exactly 10B.8's numbers from the same answers, now produced by a call_model function through a real provider class. This is how you put an existing evalkit eval (or any in-house model client) under Inspect without rewriting the client.
  2. Memoization works for this provider: two identical get_model() calls return one object.
  3. The transient failure never reached the sample. T05's transcript has two model events: the first records the ConnectionError, the second succeeded. The sample has no error, the run is a success, and the scores are unchanged. The 5.2 seconds are almost all backoff: Inspect waits about three seconds plus random jitter before the first retry (5.1).
  4. With max_retries=0, the same blip fails the run. The model layer gives up, the exception (wrapped in tenacity's RetryError) becomes a sample error, and the default fail-fast policy turns that into a failed run. Three settings decided that outcome, one at each layer of 1.2.

2.8 Keys and environment: .env and INSPECT_EVAL_*#

A real run needs keys, and where they come from is the first thing that goes wrong. Five facts, from Inspect's own loader (inspect_ai/_util/dotenv.py, 0.3.292):

  1. Inspect searches upward for a .env. It starts at the current working directory and walks up the tree until it finds one, so which file is read depends on where you run the command, not where the task file lives.
  2. .env never overrides. load_dotenv leaves variables that already exist in the environment alone, so a stale OPENAI_API_KEY exported in your shell, or set by CI, beats the file. (Inside VS Code the extension reads the file first, so Inspect overrides there to make edits take effect.)
  3. A relative INSPECT_LOG_DIR in .env is resolved against the .env file's folder, not the current directory. The same variable set in the shell is resolved against the current directory.
  4. Every inspect eval option has an INSPECT_EVAL_<OPTION> variable (INSPECT_EVAL_MAX_RETRIES, INSPECT_EVAL_TIMEOUT, INSPECT_EVAL_MODEL, and so on), and inspect eval-set honours them too. They configure the CLI only, not Python eval(); the one exception is INSPECT_EVAL_MODEL, which eval() also reads when you pass no model.
  5. .env is a local convenience, not a deployment mechanism. Git-ignore it; CI should inject secrets as environment variables.

The precedence, highest first: a command-line flag, then a shell or CI variable, then .env, then Inspect's default.

text
# .env (git-ignored; never commit it)
OPENAI_API_KEY=sk-...
INSPECT_LOG_DIR=./logs-nightly
INSPECT_EVAL_MAX_RETRIES=5

The mechanics above come from reading the installed source; the keyless samples in this lesson need no .env, so there is no output to paste.


Part 3: GenerateConfig: what reaches the provider#

Deep-dive

GenerateConfig (from inspect_ai.model) holds every generation and request setting Inspect knows: 40 fields in 0.3.292, all defaulting to None, which means "the provider's default". 10B.9, 8.5 taught the general configuration layers and the run-config files; this part is about generation settings specifically, because they have one more layer and because what the log records is not always what was sent.

3.1 Five places a setting can come from, and which one wins#

A generation setting can be given on the Model itself (get_model(..., config=...) or a --model-spec), on the Task (Task(config=GenerateConfig(...))), to the run (eval(max_tokens=...), --max-tokens, --generate-config file.yaml), or per call (generate(max_tokens=...) as a solver, or await generate(state, max_tokens=...) inside one). To see which value the provider receives, the mock below records the config argument Inspect passes it:

python
# r02_config.py: which GenerateConfig reaches the provider, and what the log records (lesson 10B.12)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import GenerateConfig, ModelOutput, get_model
from inspect_ai.solver import generate

SEEN: list[tuple] = []


def recorder(input, tools, tool_choice, config: GenerateConfig) -> ModelOutput:
    SEEN.append((config.max_tokens, config.temperature, config.seed))   # what the "provider" received
    return ModelOutput.from_content(model="mockllm", content="ok")


def mock(config: GenerateConfig | None = None):
    return get_model("mockllm/model", custom_outputs=recorder, memoize=False,
                     config=config or GenerateConfig())


def run(label: str, task_config=None, model_config=None, per_call=None, **eval_kwargs) -> None:
    SEEN.clear()
    solver = generate(**(per_call or {}))
    task = Task(dataset=[Sample(input="hi", target="ok")], solver=solver,
                config=task_config or GenerateConfig(), name="cfg")
    log = eval(task, model=mock(model_config), log_dir="logs-r02", display="none", **eval_kwargs)[0]
    model_cfg = log.eval.model_generate_config            # the Model object's own config
    plan_cfg = log.plan.config                            # Task config merged with eval() settings
    event_cfg = next(e for e in log.samples[0].events if e.event == "model").config   # this call
    show = lambda c: (c.max_tokens, c.temperature, c.seed)
    print(f"{label:40} provider={SEEN[0]} | model event={show(event_cfg)} "
          f"| plan.config={show(plan_cfg)} | eval.model_generate_config={show(model_cfg)}")


print("(max_tokens, temperature, seed) as seen at each place:")
run("Task config only", GenerateConfig(max_tokens=100, temperature=0.2))
run("Task + eval(max_tokens=200)", GenerateConfig(max_tokens=100, temperature=0.2), max_tokens=200)
run("Task + eval + generate(max_tokens=300)", GenerateConfig(max_tokens=100, temperature=0.2),
    per_call={"max_tokens": 300}, max_tokens=200)
run("get_model(config) only", model_config=GenerateConfig(max_tokens=400, seed=7))
run("get_model(config) + eval(max_tokens=200)", model_config=GenerateConfig(max_tokens=400, seed=7),
    max_tokens=200)
run("get_model(config) + Task config", GenerateConfig(max_tokens=100),
    model_config=GenerateConfig(max_tokens=400, seed=7))
bash
uv run python r02_config.py
Output · real7 lines
(max_tokens, temperature, seed) as seen at each place:
Task config only                         provider=(100, 0.2, None) | model event=(100, 0.2, None) | plan.config=(100, 0.2, None) | eval.model_generate_config=(None, None, None)
Task + eval(max_tokens=200)              provider=(200, 0.2, None) | model event=(200, 0.2, None) | plan.config=(200, 0.2, None) | eval.model_generate_config=(None, None, None)
Task + eval + generate(max_tokens=300)   provider=(300, 0.2, None) | model event=(300, 0.2, None) | plan.config=(200, 0.2, None) | eval.model_generate_config=(None, None, None)
get_model(config) only                   provider=(400, None, 7) | model event=(400, None, 7) | plan.config=(None, None, None) | eval.model_generate_config=(400, None, 7)
get_model(config) + eval(max_tokens=200) provider=(200, None, 7) | model event=(200, None, 7) | plan.config=(200, None, None) | eval.model_generate_config=(400, None, 7)
get_model(config) + Task config          provider=(100, None, 7) | model event=(100, None, 7) | plan.config=(100, None, None) | eval.model_generate_config=(400, None, 7)

The precedence, lowest to highest, is field by field (a field you do not set at a higher layer keeps its lower value, as temperature 0.2 and seed 7 did):

flowchart LR
    M["1. The Model's own config: get_model(config=...), --model-spec"] --> T["2. Task(config=...) and task_with(config=...)"]
    T --> E["3. The run: eval(**config), CLI flags, --generate-config"]
    E --> G["4. Per call: generate(max_tokens=...) in a solver"]
    G --> P["Sent to the provider, recorded in the model event"]

And the three places the log records configuration answer three different questions:

Log field What it holds Trust it for
log.eval.model_generate_config Only the Model object's own config (layer 1) What the model was constructed with. It showed max_tokens=400 in the last two rows, while the provider received 200 and 100
log.plan.config The Task config merged with the run's settings (layers 2 and 3) What the run asked for, before solvers. It missed the per-call 300
The config of each model event in a sample's transcript The merged config of that one call What was actually sent. The only field that matched the provider in every row

What this means for you as an engineer: when you report or reproduce a run, read the generation settings from the model events (or from samples_df()'s model events, 10B.13), not from the header. When you design a task, set generation settings in one place: on the Task if they are part of what the task means (a max_tokens that the output format needs), or on the run if they are a property of the experiment (a reasoning effort you sweep). A per-call value inside a solver silently beats everything a user passes on the command line, so reserve it for calls whose settings must not change (a fixed-format extraction step, say) and document it.

3.2 The fields, group by group#

Every field of GenerateConfig in 0.3.292 (printed from the installed class), grouped by what it controls. "Provider support" is from the options page and the providers page as of November 2026; it changes, so check before relying on a field.

Group Field What it does Provider support and notes
Request control max_retries Retries per request after the first attempt (1 = two attempts) All; default unlimited, bounded by timeout (Part 5)
timeout Seconds for one request including its retries All; default none
attempt_timeout Seconds for one attempt; abandon and retry All
stream_idle_timeout Seconds of silence inside a streaming response before retrying; setting it turns streaming on Anthropic, Google, OpenAI, OpenAI-compatible (incl. Together), Grok, SageMaker; inert elsewhere
Concurrency max_connections Static cap on concurrent requests to this model; disables adaptive All (Part 4)
adaptive_connections True/None (default: adaptive, 10 to 100, start 20), False, an int (maximum), or AdaptiveConcurrency(...) All
Output size and shape max_tokens Maximum generated tokens All; default model-specific. Leave room for reasoning (3.4)
stop_seqs Stop sequences Most
num_choices Several completions per request OpenAI, Grok, Google, Together, vLLM
best_of Server-side best-of-n OpenAI only
system_message Overrides the default system message All
response_schema A ResponseSchema JSON schema for structured output (03.4); still validate the output OpenAI, Google, Mistral (and vLLM, SGLang per the reference)
modalities Extra output modalities, such as ["image"] OpenAI, Google
Sampling temperature, top_p Sampling controls (02.5) Dropped with a warning where the model rejects them: Anthropic always, OpenAI reasoning models while reasoning is on
top_k Top-k sampling Google, Hugging Face, vLLM
frequency_penalty, presence_penalty Repetition penalties OpenAI, Google, Grok, Groq, llama-cpp-python, vLLM
logit_bias Token biases OpenAI, Grok
seed A sampling seed OpenAI, Google, Groq, Mistral, Hugging Face, vLLM (and not the OpenAI Responses API, per 10B.11, 5.4)
Log probabilities logprobs, top_logprobs Token log probabilities OpenAI, Grok, Together, Hugging Face, llama-cpp-python (logprobs), vLLM
prompt_logprobs Log probabilities of the prompt vLLM (used by perplexity() scorers)
Tools parallel_tool_calls Allow several tool calls per turn OpenAI, Groq (10B.14)
internal_tools Map tools to provider-native ones (computer use) Provider-specific
max_tool_output Truncate tool output (bytes; default 16 KiB) All
Reasoning (02.8, Part 3) reasoning_effort none, minimal, low, medium, high, xhigh, max Defaults and accepted values vary by model
effort low to max: Claude's response-effort control Claude 4.5 to 4.7 per the options page
reasoning_tokens A reasoning token budget Anthropic Claude
reasoning_mode standard or pro OpenAI GPT-5.6 and later
reasoning_summary, reasoning_history Ask for reasoning summaries; how much reasoning to replay in later turns (none/all/last/auto) Provider-specific; auto uses each provider's recommendation
verbosity low/medium/high answer length GPT-5.x per the options page
Caching and batching cache Inspect's local response cache (Part 6) All
cache_prompt Provider prompt caching (auto/true/false) Anthropic (on by default), OpenRouter for Anthropic models; OpenAI's explicit cache marks are a content-level option (6.9)
batch Provider batch APIs (Part 7) OpenAI, Anthropic, Google, xAI, Together; ignored elsewhere
Refusals fail_on_refusal A refusal (stop_reason="content_filter") fails the sample (8.6) All; applies to role models too unless the role sets its own
fallback_models Retry a refused request on other Claude models Anthropic first-party API only
Pass-through extra_headers, extra_body Extra request headers or body fields (vLLM chat-template switches, Responses API metadata) Not all providers

Each field has a CLI flag of the same name with hyphens (--max-tokens, --reasoning-effort, --fail-on-refusal), and inspect eval --help is the authoritative list for the version you have installed.

3.3 What a provider honours, per course provider#

Illustrative settings for the same triage run on each provider (as of November 2026; check each provider's section of the providers page before relying on them):

python
# provider_configs.py: sensible generation settings per provider for a classification eval (lesson 10B.12)
# Illustrative: running these needs the provider SDKs and keys in .env.
from inspect_ai.model import GenerateConfig, get_model

# OpenAI: GPT-6 Luna reasons by default; temperature is dropped while it reasons.
# For a cheap classifier, turn reasoning off; then temperature is sent (seed is not,
# on the Responses API).
openai_model = get_model("openai/gpt-6-luna",
                         config=GenerateConfig(reasoning_effort="none", temperature=0,
                                               max_tokens=512))

# Anthropic: never set temperature/top_p/top_k (not sent since API 2026-10-21).
# Leave max_tokens room for any reasoning the model does before the JSON.
anthropic_model = get_model("anthropic/claude-haiku-5-5", config=GenerateConfig(max_tokens=1024))

# Gemini (optional): check the model page before adding temperature or seed; set a timeout,
# because the SDK default is one hour per request.
google_model = get_model("google/gemini-3.8-flash",
                         config=GenerateConfig(max_tokens=1024, timeout=120))

# OpenRouter (optional): the vendor's own rules apply behind the route; pin the route for comparability.
openrouter_model = get_model("openrouter/anthropic/claude-haiku-5.5",
                             config=GenerateConfig(max_tokens=1024),
                             provider={"order": ["anthropic"], "allow_fallbacks": False})

Example output (illustrative — your exact output will differ): constructing these models prints nothing; when you use one, any setting the model rejects appears as a warning such as a note that temperature was dropped, and the model events record what was sent.

The last call passes provider= as a model argument (the keyword arguments of get_model() beyond its own are model args), which is OpenRouter's routing option. On the command line the same runs are --model openai/gpt-6-luna --reasoning-effort none --temperature 0 --max-tokens 512 and so on.

3.4 Sampling settings on current models#

Three facts about current models change how you configure evals (02.5, Part 6 has the provider details):

  1. Many models reject sampling parameters. The models page says OpenAI reasoning models reject temperature and top_p while reasoning is on (the default for GPT-5.5 and later), Anthropic models reject them always, and "Inspect drops these options with a warning". The warning goes to the console and the log, the run continues, and the setting you think you used was never sent. Read the warnings of the first real run of any new configuration.
  2. Reasoning takes tokens from max_tokens. A reasoning model can spend most of a small max_tokens thinking and return a truncated or empty answer (stop_reason="max_tokens"), which your scorer then marks wrong. That is a configuration failure that looks like a model failure. Count stop_reason values per run (the CI gate in Part 13 could be extended to fail on them) and size max_tokens with headroom; 02.8, Part 5 covers reasoning budgets.
  3. Temperature 0 is not determinism, and seed is honoured by few APIs. Repeat runs of a hosted model at temperature 0 still differ. Epochs (10B.10, Part 7) measure that variance; configure the eval the way production is configured, and measure the spread instead of pretending it away.

3.5 Temperature is not random assignment#

The models page carries a note worth repeating as a rule: do not use model sampling as the source of randomness in an eval. Raising temperature makes outputs more variable, but it does not make two labels, two answer orders or two personas equally likely. If an eval needs randomization (which option comes first, which of two prompt variants a sample gets, which persona a simulated user takes), do it in the data or the solver with a recorded seed: shuffle choices at load time, assign variants by sample id, draw personas from a seeded generator (10B.9, 4.4). If the task asks the model to make a stochastic choice on purpose, run epochs and report the observed distribution (a categorical scorer with frequency(), 10B.10, 6.10) instead of assuming it.

3.6 Configuration files for generation settings#

For anything longer than two flags, keep generation settings in a file next to the task, reviewed like code. 10B.9, 8.6 shows --generate-config (individual flags still win over it) and --run-config (everything in one file, including model roles, and the right artefact to commit next to a published number). The one addition here: a run-config's model key can be left out, which turns the file into a "paper config" that applies the same settings to whatever --model you pass; that is the reproducible way to run "the March evaluation, on the new model".


Part 4: Concurrency: how many requests are in flight#

This part is the eval-run version of 03.9, Async, Concurrency and Batch Processing: the same ideas (bounded concurrency, backing off on rate limits), applied to an eval run in Inspect.

Inspect runs samples concurrently on one event loop (10B.8, 2.6): while one sample waits for the model, others proceed. How many requests are in flight at once decides how long a run takes and whether the provider starts rejecting you. 03.9, Part 4 and Part 5 teach bounded concurrency and rate-aware throughput in general; this part is what Inspect does about them.

4.1 Four knobs, four scopes#

Knob Scope Default (0.3.292) Limits
Connections (adaptive_connections / max_connections) Per model (per connection pool) Adaptive: start 20, floor 10, ceiling 100 Concurrent requests to that model's API
max_samples Per task Tracks the model's current connection limit Samples running at once, whatever they are doing (generating, running tools, being scored)
max_tasks Per eval() / eval set 1 for eval(); max(10, number of models) for eval_set() Tasks (task × model pairs) running at once
max_subprocesses, max_sandboxes Per eval CPUs available to the eval; twice that for sandboxes Local subprocesses and sandbox containers (10B.15)

Two more you will rarely touch: max_dataset_memory (MB of sample data held in memory per task before paging to disk, for very large datasets) and the HTTP client settings (INSPECT_HTTP_CONNECT_TIMEOUT default 60 s, INSPECT_HTTP_REQUEST_TIMEOUT default 600 s, INSPECT_HTTP_POOL_CONNECTIONS default 1000 and others on the concurrency page), which govern sockets rather than requests.

4.2 Adaptive connections, the default#

Since 0.3.221 (May 2026) Inspect tunes the connection limit itself (the feature arrived in 0.3.217; the floor rose from 4 to 10 in 0.3.240). The controller, per model:

  • starts at 20 requests in flight and, during "slow start", doubles the limit while requests succeed, up to the ceiling (default 100);
  • on a rate-limit retry (a 429, or what a provider's should_retry() classifies as rate_limit), multiplies the limit by decrease_factor (0.8), at most once per cooldown_seconds (15 s), never below the floor (10);
  • on a transient retry (5xx, timeouts, network errors) only pauses growth: lowering concurrency does not fix an upstream outage;
  • in steady state, grows by scale_up_percent (5%) per clean round;
  • records every change in log.stats.connection_limit_history with a reason (slow_start, steady_state_up, rate_limit).

Shape it from the CLI with --adaptive-connections 50 (ceiling), 5-50 (floor and ceiling) or 5-10-50 (floor, start, ceiling), or in Python with AdaptiveConcurrency(min=..., start=..., max=..., cooldown_seconds=..., decrease_factor=..., scale_up_percent=...) (the last three are Python-only). --adaptive-connections false switches to static mode with the provider's default.

4.3 Static connections#

--max-connections N (or max_connections=N) sets a hard cap and turns adaptive off; so does batch mode. The static default, when adaptive is off and you give no number, is the provider's max_connections() (10 for most built-in providers; the callmodel provider of 2.7 chose 4). Use a static cap when you know your tier's limit and want predictable load, when an eval shares a key with production traffic and must never take more than its share, or when you are debugging and want a small, fixed number.

4.4 Measured: what each setting does#

A 200-sample task against an async mock that takes 200 ms per request and counts how many requests are in flight at once:

python
# r04_concurrency.py: how many model calls are really in flight under each setting (lesson 10B.12)
import time

import anyio

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.util import AdaptiveConcurrency

STATE = {"now": 0, "peak": 0}


async def slow_model(input, tools, tool_choice, config) -> ModelOutput:
    STATE["now"] += 1
    STATE["peak"] = max(STATE["peak"], STATE["now"])
    await anyio.sleep(0.2)                       # a 200 ms "provider"
    STATE["now"] -= 1
    return ModelOutput.from_content(model="mockllm", content="ok")


def run(label: str, n: int = 200, **kwargs) -> None:
    STATE.update(now=0, peak=0)
    model = get_model("mockllm/model", custom_outputs=slow_model, memoize=False)
    task = Task(dataset=[Sample(id=i, input=f"q{i}", target="ok") for i in range(n)], name="conc")
    start = time.perf_counter()
    log = eval(task, model=model, log_dir="logs-r04", display="none", **kwargs)[0]
    history = log.stats.connection_limit_history or []
    limits = [f"{h.new_limit}:{h.reason}" for h in history]
    print(f"{label:44} peak in flight={STATE['peak']:3}  wall={time.perf_counter() - start:4.1f}s  "
          f"limit changes={limits[:4]}{' ...' if len(limits) > 4 else ''}")


run("default (adaptive: start 20, max 100)")
run("max_connections=5 (static)", max_connections=5)
run("max_samples=3", max_samples=3)
run("adaptive_connections=AdaptiveConcurrency(2-4-8)",
    adaptive_connections=AdaptiveConcurrency(min=2, start=4, max=8))
run("adaptive_connections=False (static default)", adaptive_connections=False)
bash
uv run python r04_concurrency.py
Output · real; wall times are from one laptop run5 lines
default (adaptive: start 20, max 100)        peak in flight= 80  wall= 1.6s  limit changes=['40:slow_start', '80:slow_start', '100:slow_start']
max_connections=5 (static)                   peak in flight=  5  wall= 9.1s  limit changes=[]
max_samples=3                                peak in flight=  3  wall=15.2s  limit changes=[]
adaptive_connections=AdaptiveConcurrency(2-4-8) peak in flight=  8  wall= 5.6s  limit changes=['8:slow_start']
adaptive_connections=False (static default)  peak in flight= 10  wall= 5.0s  limit changes=[]
  • Default: slow start doubled the limit 20 → 40 → 80 → 100 within a second and a half; 80 requests were in flight at the peak (the ceiling of 100 arrived as the 200 samples ran out). Against a provider with no rate limit, that is the fastest setting.
  • max_connections=5: exactly 5 in flight, no adaptive history, about 200 × 0.2 / 5 = 8 seconds plus overhead.
  • max_samples=3: the tighter of the two limits wins: only 3 samples exist at once, so only 3 requests can be in flight even though 20 connections are allowed.
  • Custom bounds: start 4, one doubling to the ceiling of 8.
  • Adaptive off: the mock provider's static default, 10.

What this means for you: the defaults ramp up fast, which is right against a big tier and wrong when the eval shares a key with production traffic or a small trial tier; that is when you set a ceiling (--adaptive-connections 20) or a static cap. max_samples is not a throughput knob for plain generation tasks (it can only lower concurrency), but it matters for recovery (4.6) and for agents (4.6 again).

4.5 Rate limits and the controller backing off#

The mock above never says no. A provider that does: the one below accepts at most 30 concurrent requests and answers anything beyond with a rate-limit error, which its should_retry() classifies as RetryDecision.rate_limit():

python
# r04b_rate_limit.py: adaptive concurrency backing off when the provider rate-limits (lesson 10B.12)
import time
from typing import Any

import anyio

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import (ChatMessage, GenerateConfig, ModelAPI, ModelOutput,
                              RetryDecision, modelapi)


class RateLimitError(Exception):
    pass


STATE = {"now": 0, "peak": 0, "429s": 0}
CAPACITY = 30          # the "provider" accepts at most 30 concurrent requests


class Limited(ModelAPI):
    def __init__(self, model_name: str, base_url: str | None = None, api_key: str | None = None,
                 api_key_vars: list[str] = [], config: GenerateConfig = GenerateConfig(),
                 **model_args: Any) -> None:
        super().__init__(model_name, base_url, api_key, api_key_vars, config)

    async def generate(self, input: list[ChatMessage], tools, tool_choice, config) -> ModelOutput:
        STATE["now"] += 1
        try:
            STATE["peak"] = max(STATE["peak"], STATE["now"])
            if STATE["now"] > CAPACITY:
                STATE["429s"] += 1
                raise RateLimitError("429 Too Many Requests")
            await anyio.sleep(0.2)
            return ModelOutput.from_content(model=self.model_name, content="ok")
        finally:
            STATE["now"] -= 1

    def should_retry(self, ex: Exception) -> RetryDecision:
        return RetryDecision.rate_limit() if isinstance(ex, RateLimitError) else RetryDecision.no()


@modelapi(name="limited")
def limited() -> type[ModelAPI]:
    return Limited


start = time.perf_counter()
task = Task(dataset=[Sample(id=i, input=f"q{i}", target="ok") for i in range(400)], name="ratelimited")
log = eval(task, model="limited/provider", log_dir="logs-r04b", display="none")[0]
print(f"status={log.status}  wall={time.perf_counter() - start:.1f}s  peak in flight={STATE['peak']}  "
      f"429s raised={STATE['429s']}")
for h in log.stats.connection_limit_history:
    print(f"  limit {h.old_limit:3} -> {h.new_limit:3}  ({h.reason})")
bash
uv run python r04b_rate_limit.py
Output · real3 lines
status=success  wall=5.7s  peak in flight=31  429s raised=2
  limit  20 ->  40  (slow_start)
  limit  40 ->  30  (rate_limit)

The controller doubled to 40, the provider rejected two requests above its capacity, the controller cut the limit to 30 and held it there, and the two rejected requests succeeded on retry. Every one of 400 samples succeeded; the cost was about three seconds of backoff on two requests. That is the behaviour you want from a long run against a real tier: find the ceiling, stay just under it, and never surface a 429 as a sample error.

Three caveats from the concurrency page:

  • Built-in providers classify a 429 as a rate limit and a 5xx as transient; a custom provider that returns a plain True from should_retry() is treated as transient, so the controller never backs off. Classify properly (2.7).
  • Do not set the floor too low for long agentic samples: with few connections and many samples, the gap between one sample's calls can exceed a provider's prompt-cache lifetime (Anthropic's default is five minutes), so every call pays full price for its prefix.
  • Set the ceiling above where you expect the controller to settle. If the history shows it pinned at the ceiling with no rate_limit entries, you have headroom.

4.6 max_samples, max_tasks and the recovery trade-off#

max_samples limits samples in progress per task. By default it tracks the connection limit (with adaptive connections it follows the controller). Two reasons to set it yourself:

  • Agents and tools. A sample that spends half its time running tools in a sandbox holds a sample slot but not a model connection. Set max_samples above the connection limit so the connections stay busy (10B.15).
  • Recovery. Completed samples are written to the log in batches (log_buffer; for .eval logs the default is min(samples / 3, 10), rounded down and at least 1) and kept in a local sample buffer database between writes. The more samples in flight when a process dies, the more in-progress work is lost and has to be re-run (9.4 shows the numbers). The eval-sets page's advice: a very large max_samples (100 in-flight samples on a 100-sample dataset) can leave very few recoverable samples after an interruption.

Task(max_samples=...) (keyword-only, new in 0.3.292) sets a per-task default; an eval() or CLI value overrides it.

max_tasks runs several tasks (or task × model pairs) at once. eval() runs one at a time by default, because a task with more samples than connections already saturates the model. Raise it when tasks are small (a suite of 20-sample tasks) or when you evaluate several models, each with its own connection pool. eval_set() defaults to the greater of 10 and the number of models, and its scheduler balances active tasks across models so one provider is not overloaded.

4.7 Several models, several pools#

Connection limits are enforced per model (more precisely, per provider and connection_key(), so two models on the same account can share a pool if the provider says so). Three consequences:

  • --model a,b,c runs three models in parallel without them competing for connections; evaluating several models in one run is cheaper in wall time than three separate runs.
  • A grader or other role model has its own pool, so heavy grading does not slow generation, but both count against the same provider account if they share a key. If your account's limit is the bottleneck, the controller will find it for each pool separately, and the two pools may oscillate; a static ceiling on the grader (--model-role 'grader={model: ..., max_connections: 10}') keeps the split predictable.
  • A provider's own SDK may retry inside its call (the openai and anthropic packages retry twice by default, per the concurrency page), on top of Inspect's retries. Inspect's max_retries bounds only its own outer loop.

4.8 Watching and retuning a live run#

Long runs need observation (illustrative; these commands talk to a running eval on your machine):

bash
inspect ctl config                               # each model's live limit, in-flight count and recent changes
inspect ctl config --max-connections 20          # throttle mid-run (lowering clamps immediately)
inspect ctl config --max-connections 200 --model gpt-6-luna
inspect ctl config --max-connections 20 --dry-run --reason "provider incident"   # preview a change; --reason is recorded
inspect trace http --failed                      # failed HTTP requests of the current or last run
inspect eval triage.py --model openai/gpt-6-luna --log-level http   # print every request and retry
inspect eval-set suite/ --log-dir logs-nightly --detach              # run in the background, then use inspect ctl

Example output (illustrative — your exact output will differ): inspect ctl config prints a table per model with its current limit, requests in flight, bounds and recent changes; the exact columns depend on your version.

The control channel (inspect ctl, docs) can also retune --timeout, --attempt-timeout and --max-retries mid-flight, pause, resume and cancel. It is the tool for "the provider is having a bad hour" without killing a six-hour run. Each applied change is recorded in the affected log with who, when and the old and new values, so a retuned run is auditable.

4.9 Spreading one task across processes: sharding#

When one machine is not enough (a dataset of 50,000 samples, or an agent eval limited by local CPU), run the same task as several shards, each a separate process with its own fixed sample selection, writing to numbered directories under <log name>.shards/, then merge them. Keyless, two shards of the six-sample orders task:

bash
# r12_shards.sh: one task split across two worker processes, then merged (lesson 10B.12)
NAME=2026-11-24T18-30-00-00-00_orders_shardDemo01
inspect eval orders_task.py --model mockllm/model --sample-id s01,s02,s03 \
  --log-dir logs-r12/$NAME.shards/0 --display none &
inspect eval orders_task.py --model mockllm/model --sample-id s04,s05,s06 \
  --log-dir logs-r12/$NAME.shards/1 --display none &
wait
echo "shard logs: $(ls logs-r12/$NAME.shards/*/*.eval | wc -l | tr -d ' ')"
echo "\$ inspect log merge-shards logs-r12/$NAME.eval --task orders_task.py"
inspect log merge-shards logs-r12/$NAME.eval --task orders_task.py
python -c "
from inspect_ai.log import read_eval_log
log = read_eval_log('logs-r12/$NAME.eval')
s = log.results.scores[0]
print('merged:', log.status, '| samples:', sorted(x.id for x in log.samples),
      '| accuracy', s.metrics['accuracy'].value, 'over', s.scored_samples)
"
Output · real; the absolute path in the second line is shortened5 lines
shard logs: 2
$ inspect log merge-shards logs-r12/2026-11-24T18-30-00-00-00_orders_shardDemo01.eval --task orders_task.py
Merged 2 shards into <work>/logs-r12/2026-11-24T18-30-00-00-00_orders_shardDemo01.eval
  status: success
merged: success | samples: ['s01', 's02', 's03', 's04', 's05', 's06'] | accuracy 1.0 over 6

The merge recomputes metrics and epoch reductions over all samples, exactly as an unsharded run would, using the task you pass, so pass the same -T, --model, --model-role and --epochs the workers used: a mismatch changes the recomputed numbers (the demo works because the defaults match). --delete-shards removes the shard directories after a successful merge (new in 0.3.292). The rules (from the sharding page, merge-shards arrived in 0.3.291): shard directories are named with digits only; selections must not overlap (--sample-id lists or --limit ranges, which cannot be combined); every worker runs the same task, arguments, model, scorers and epochs from the same working directory; logs must be .eval. An eval set refuses a log directory that contains a .shards directory until you merge and move it. Sharding is a big-batch tool; for most product evals, one process with adaptive concurrency is enough.

4.10 Choosing concurrency settings#

Situation Setting Why
A normal eval on your own key Defaults Adaptive finds the ceiling and backs off on 429s
The key is shared with production traffic --adaptive-connections 5-10-20 or a static --max-connections 10 Cap the eval's share; production first
A free or trial tier --max-connections 2, and --max-retries with a --timeout The tier's limits are tiny and backoff can take minutes
Many small tasks --max-tasks 5 One task cannot fill the connections
Several models --model a,b,c in one run Separate pools, parallel progress
Agents with tools or sandboxes max_samples above the connection limit Samples spend time outside the model
A run you might have to recover A moderate max_samples Fewer in-flight samples lost on a crash
A run too big for one machine Shards and merge-shards Each process gets its own share of samples
Debugging a single failure --max-connections 1 --limit 1 (and --sample-id) One request at a time, readable logs

Part 5: Model-call retries and timeouts#

Deep-dive

This part is the eval-run version of 03.8, Errors, Rate Limits, Timeouts and Retries: the same retry and timeout ideas, applied to the model layer of an Inspect run.

5.1 The retry loop#

Every generate() call goes through a retry loop in Inspect's model layer (built on tenacity, the library 03.8, Part 8 teaches). When the provider raises, Inspect asks the provider's should_retry() whether the exception is retryable. Built-in providers say yes for rate limits, server errors, timeouts and connection failures, and no for bad requests, authentication failures and content you sent wrong. A retryable failure waits and tries again:

  • Backoff: exponential with jitter, starting at about 3 seconds and capped at 30 minutes per wait (the concurrency page: the 10th retry waits about 25 minutes, the 11th and later 30). The demonstration in 2.7 took 3.6 to 5.2 seconds for one retry for exactly this reason.
  • How many: max_retries (default unlimited). Since 0.3.248, max_retries=N means N retries, N+1 attempts; before that it counted total attempts, so max_retries=1 never retried. Older advice about this setting may be off by one.
  • How long: timeout bounds the whole call including retries and waits (default: none). attempt_timeout abandons one slow attempt and retries it. stream_idle_timeout abandons a streaming attempt that goes silent (see 3.2 for the providers it covers).
  • Where it shows: each attempt is a separate model event in the sample's transcript, the failed ones carrying their error; the progress display counts "HTTP retries"; --log-level http prints each request; inspect trace http --failed lists failures afterwards.

What exhaustion looks like: the last exception, wrapped in tenacity's RetryError, escapes generate() into your solver, and from there becomes a sample error (Part 8). Run 4 in 2.7 shows exactly that.

5.2 Settings for two kinds of run#

Setting A CI run (minutes, must finish or fail fast) A long research or release run (hours, must finish)
max_retries 5 Default (unlimited)
timeout 300 (five minutes per call, including retries) 1800 or unset
attempt_timeout Above your slowest healthy call (for a reasoning model, minutes) Same
stream_idle_timeout 60 for streaming providers 60 to 120
Connections A static cap below the CI key's limit Adaptive (the default)
Error policy Fail fast, then a gate (Part 13) Eval set with task retries (Part 11)

A CI job that hangs is worse than one that fails: set a timeout on the job itself too (GitHub Actions' timeout-minutes).

5.3 Errors that are not retried#

Some failures should never be retried, and Inspect's providers do not: a malformed request (400), a missing or invalid key (401/403), a context-length overflow, a model that does not exist. They fail on the first attempt and become sample errors, usually on every sample, so with the default fail-fast policy the run stops in seconds. That is the right behaviour: read the error and fix the configuration. A run that tolerates errors (fail_on_error=False) with a wrong key produces a log full of errored samples and a metric computed over nothing; the CI gate in Part 13 refuses it. Inspect does handle one auth case specially: when a provider's is_auth_failure() recognizes an authentication error, Inspect calls its refresh_credentials() to pick up new credentials, for keys that rotate during long runs (the Model API extension page describes which built-in providers implement it).


Part 6: The response cache#

Deep-dive

This part is the eval-run version of caching as taught in 03.7, Token Counting, Cost Tracking and Prompt Caching and 11B.4, Token Caching in Depth: Inspect adds a response cache for repeated eval runs.

6.1 Three different caches#

"Caching" means three different things around an Inspect run, and mixing them up causes most caching mistakes:

Cache Where it lives What it saves Controlled by
Inspect's response cache Files on your machine (the user cache directory, or INSPECT_CACHE_DIR) The whole request: an identical request is answered from disk, the provider is not called cache=True / CachePolicy on eval(), generate(), get_model(config=...), --cache
Provider prompt caching The provider's servers Part of the price and latency of a long, repeated prompt prefix; the model still generates cache_prompt (and per-block marks), the provider's own rules (03.7, Part 6)
evalkit's record/replay cache A JSON file per suite The whole call, like Inspect's CallCache in 10A.8, 3.2

This part is about the first. The caching page is the reference.

6.2 Turning it on, and what a hit looks like#

The run below sends the triage task through the counting callmodel provider of 2.7, so the number of calls that reach the "provider" is visible, and counts each model event's cache field, which records "write" (stored after a real call) or "read" (served from disk):

python
# r05_cache.py: Inspect's response cache: hits, misses, the key, epochs and model instances (lesson 10B.12)
import os

os.environ["INSPECT_CACHE_DIR"] = os.path.abspath("cache-r05")   # keep this demo's cache here

from collections import Counter

from inspect_ai import eval
from inspect_ai.model import CachePolicy

from callmodel_api import register_call_model
from triage import triage
from triage_call_model import fake_call_model

CALLS = Counter()


def counting_call_model(prompt: str) -> str:
    CALLS["provider"] += 1                 # every call that reaches the "provider"
    return fake_call_model(prompt)


register_call_model("triage-counted", counting_call_model)
MODEL = "callmodel/triage-counted"


def run(label: str, **kwargs) -> None:
    before = CALLS["provider"]
    log = eval(triage(), model=MODEL, log_dir="logs-r05", display="none", **kwargs)[0]
    # each model event records whether it was served from the cache ("read") or stored ("write")
    events = Counter(e.cache or "none" for s in log.samples for e in s.events if e.event == "model")
    print(f"{label:46} provider calls={CALLS['provider'] - before:3}  model events by cache={dict(events)}")


run("1 cache=True, first run", cache=True)
run("2 cache=True, identical second run", cache=True)
run("3 no cache argument")
run("4 cache=True, max_tokens=500 (config changed)", cache=True, max_tokens=500)
run("5 CachePolicy(scopes={'prompt': 'v2'})", cache=CachePolicy(scopes={"prompt": "v2"}))
run("6 epochs=3, cache=True (per_epoch default)", cache=True, epochs=3)
run("7 epochs=3, same again", cache=True, epochs=3)
run("8 epochs=3, CachePolicy(per_epoch=False)", cache=CachePolicy(per_epoch=False), epochs=3)
bash
uv run python r05_cache.py
Output · real8 lines
1 cache=True, first run                        provider calls= 12  model events by cache={'write': 12}
2 cache=True, identical second run             provider calls=  0  model events by cache={'read': 12}
3 no cache argument                            provider calls= 12  model events by cache={'none': 12}
4 cache=True, max_tokens=500 (config changed)  provider calls= 12  model events by cache={'write': 12}
5 CachePolicy(scopes={'prompt': 'v2'})         provider calls= 12  model events by cache={'write': 12}
6 epochs=3, cache=True (per_epoch default)     provider calls= 24  model events by cache={'read': 12, 'write': 24}
7 epochs=3, same again                         provider calls=  0  model events by cache={'read': 36}
8 epochs=3, CachePolicy(per_epoch=False)       provider calls= 20  model events by cache={'write': 20, 'read': 16}

Rows 1 to 3: the first cached run calls the provider twelve times and writes twelve entries; an identical run calls it zero times; a run without cache ignores the cache entirely (it neither reads nor writes). The log tells you which answers came from disk, sample by sample, so a reader can always distinguish a fresh measurement from a replay.

6.3 What is in the key, and what is not#

Rows 4 and 5 changed one thing each and missed the cache completely. The key, per the caching page and the runs:

In the key (a change means a miss) Not in the key (a change still hits)
Model name and base URL The snapshot behind a model alias (6.7)
Model constructor arguments that are plain JSON values (hashed; api_key and aws_* excluded) api_key, aws_region, aws_profile: two Bedrock regions share entries
The full message history sent (system prompt, few-shot, the input) Your scorers, the dataset's targets, sample metadata the prompt does not use
The generation config (row 4: max_tokens alone was enough) The task name or version, the Inspect version
Active tools and tool_choice Anything the provider changed on its side
The epoch, unless per_epoch=False
scopes you add to a CachePolicy (row 5)

Two practical uses of that table. Scopes let you partition the cache on purpose: CachePolicy(scopes={"prompt": "v2"}) gives a prompt experiment its own cache, so a re-run of v1 does not serve v2's answers and vice versa, even if the rendered messages happened to match. Scorer iteration is free: because scorers are not in the key, you can change a scorer and re-run the whole task with cache=True without paying for generation. (Re-scoring a saved log with inspect score, 10B.11, 11.2, is the other way, and needs no cache at all.)

6.4 Caching and epochs#

Row 6 ran three epochs with cache=True: 24 calls, 12 reads. The reads are epoch 1, whose key matched row 1's entries (row 1 was a one-epoch run, so it was epoch 1). Epochs 2 and 3 are separate keys and were called fresh. That is the default per_epoch=True doing its job: each epoch is a new draw from the model, so epochs still measure run-to-run variance (10B.10, 7.11). Row 7 repeated row 6 and was served entirely from disk.

Row 8 is the trap. CachePolicy(per_epoch=False) drops the epoch from the key, which is meant to mean "one call per sample, replayed into every epoch". It made 20 calls, not 12. The reason is concurrency: all 36 sample-epochs were scheduled at once, the first 20 (the starting connection limit) went out before any answer had been written to the cache, so every one of them missed, including second and third epochs of the same sample; only the 16 that started later found an entry. Two lessons:

  • With per_epoch=False, epochs are not independent draws (most are replays of whichever call finished first), so the epoch spread is meaningless, and the number of real calls depends on timing. Never use it for anything you report as variance; the "warm cache" trap of 10A.8, 2.2 in Inspect form.
  • More generally, the cache is not a lock. Two identical requests in flight at the same time both miss. If you need exactly one call per key (to control cost), run the first pass with one epoch, then the later passes from the cache.

6.5 Models built from Python objects cache per instance#

The scripted mock of 10B.8 passes a Python function as a model argument. The caching page warns that constructor arguments that are not plain JSON values (a callable, an HTTP client object) have no stable identity, so Inspect "scopes caching to the current model instance". Measured with 10B.8's fake_triage wrapped in a counter:

python
# r05b_cache_instances.py: a model built with a Python callable caches per instance only (lesson 10B.12)
import os

os.environ["INSPECT_CACHE_DIR"] = os.path.abspath("cache-r05")

from collections import Counter

from inspect_ai import eval
from inspect_ai.model import get_model

from fake_triage import fake_triage
from triage import triage

CALLS = Counter()


def counting(input, tools, tool_choice, config):
    CALLS["n"] += 1
    return fake_triage(input, tools, tool_choice, config)


same = get_model("mockllm/model", custom_outputs=counting, memoize=False)
for label, model in [("run 1, instance A", same), ("run 2, instance A again", same),
                     ("run 3, new instance B", get_model("mockllm/model", custom_outputs=counting,
                                                         memoize=False))]:
    before = CALLS["n"]
    eval(triage(), model=model, cache=True, log_dir="logs-r05", display="none")
    print(f"{label:26} provider calls = {CALLS['n'] - before}")
Output · real3 lines
run 1, instance A          provider calls = 12
run 2, instance A again    provider calls = 0
run 3, new instance B      provider calls = 12

The same instance hits; a new instance with an identical function misses, and so would the same script in a new process. The callmodel provider of 2.7 avoids this because its only constructor argument is a model name (a string), which is why row 2 of 6.2 hit across eval() calls. If you want cross-process caching for a custom model, make its constructor arguments plain JSON and look the heavy objects up by name, as that provider does. Real providers built from strings (openai/..., anthropic/...) cache across processes by default.

6.6 Managing the cache#

The cache is a directory of files per model. With INSPECT_CACHE_DIR pointed at a scratch folder:

bash
inspect cache path
inspect cache list
inspect cache list --pruneable
inspect cache clear --model callmodel/triage-counted
inspect cache list
Output · real; the path is shortened26 lines
$ inspect cache path
<work>/cache-r05/generate
$ inspect cache list
              Cache Sizes
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Model                    ┃     Size ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━┩
│ callmodel/triage-counted │ 58.22 KB │
│ mockllm/model            │ 23.81 KB │
└──────────────────────────┴──────────┘
$ inspect cache list --pruneable
No expired cache entries.
$ inspect cache clear --model callmodel/triage-counted
     Clearing the following caches
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Model                    ┃     Size ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━┩
│ callmodel/triage-counted │ 58.22 KB │
└──────────────────────────┴──────────┘
$ inspect cache list
        Cache Sizes
┏━━━━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Model         ┃     Size ┃
┡━━━━━━━━━━━━━━━╇━━━━━━━━━━┩
│ mockllm/model │ 23.81 KB │
└───────────────┴──────────┘

inspect cache prune removes expired entries (all models, or --model). Entries expire after one week by default; --cache 1D, --cache 4W or CachePolicy(expiry="3h") change that (units s, m, h, D, W, M, Y), and expiry=None never expires. Without INSPECT_CACHE_DIR, the cache lives in the system's user cache directory (on macOS, under ~/Library/Caches/inspect_ai/generate). In CI, point INSPECT_CACHE_DIR at a directory the CI system caches between jobs (for example actions/cache keyed on the model id and the dataset hash) if you want cached smoke runs; never share a cache between people or machines whose model access or data you would not share.

One upgrade note from the caching page: caches written by Inspect versions before constructor arguments were part of the key can serve an answer written for a custom-argument model to a default one. After upgrading from such a version, run inspect cache clear --all (or --model per affected model).

6.7 Stale answers: aliases and silent upgrades#

The key contains the model name. If the name is an alias and the provider moves it to a new snapshot, every cached answer from the old snapshot is still served for up to a week (or forever, with expiry=None), and the log records read events from a model that no longer exists behind that name. Three rules: use dated snapshot ids with --cache (2.6); clear the model's cache when you change models or providers; and never let a release number come from cache reads you did not intend (count read events in the gate or the report, the same way row 2 counted them).

6.8 When to cache#

Situation Cache? Why
Iterating on scorers or the report over fixed outputs Yes, or better, re-score the saved log Generation is unchanged; only scoring changes
A CI smoke run on a fixed small set Yes, with a dated model id and a short expiry Cheap, fast, catches plumbing breaks; record it as a replay
Developing a prompt, re-running unchanged samples Yes, with a scopes entry per prompt variant Saves money without cross-contaminating variants
Measuring run-to-run variance (epochs) Only with per_epoch=True (the default), and never per_epoch=False Replays have zero variance
A release or model-comparison number No, or only if every read is from the same snapshot in the same release window, and you say so A measurement should be a measurement
Model-graded scoring with the default templates Pointless The nonce makes every grading prompt unique (10B.11, 8.3)
An agent with tools Rarely useful Any variation in a tool result changes the message history, so later turns miss

6.9 Provider prompt caching is a different thing#

Provider prompt caching does not skip generation; it bills a repeated prompt prefix at a discount. Inspect turns it on by default where the provider supports switching it: Anthropic (cache_prompt defaults on; breakpoints on the system prompt, the last tool definition and the recent history) and OpenRouter's Anthropic routes. OpenAI caches automatically; for GPT-5.6 and later you can place explicit ContentText(text=..., cache_breakpoint=True) marks, which also work for Anthropic (at most four per Anthropic request). When provider caching is active, the token line in the results panel shows four numbers, I (input), CW (cache writes), CR (cache reads) and O (output). For an eval:

  • Single-turn evals with a shared long system prompt or few-shot block benefit: every sample reuses the prefix.
  • Single-turn evals with no shared prefix pay a premium: cache writes cost more than plain input (about 1.25 times for Anthropic's five-minute writes), with no reads to offset them. The providers page recommends --cache-prompt=false for those workloads on OpenRouter's Anthropic routes; measure it for direct Anthropic too.
  • Agents benefit most, as long as the gap between a sample's calls stays under the cache lifetime (4.5 on why the adaptive floor matters).

03.7, Part 10 shows how to measure whether caching paid off; the same numbers are in the log's model usage.


Part 7: Batch mode#

Reference

This part is the eval-run version of the batch material in 03.9, Async, Concurrency and Batch Processing: the same provider batch APIs, used for an eval run.

The provider batch APIs (03.9, Part 6) trade latency for price: requests are submitted in bulk, processed within (typically) hours, and billed at a discount, typically half the normal price, with separate and higher rate limits. Inspect can route an eval's requests through them transparently.

bash
# illustrative: needs a provider key; batches can take up to 24 hours to complete
inspect eval triage.py --model openai/gpt-6-luna --batch               # defaults
inspect eval triage.py --model openai/gpt-6-luna --batch 1000          # target batch size
inspect eval triage.py --model anthropic/claude-haiku-5-5 --batch batch.yml
python
# batch_run.py: the same from Python (lesson 10B.12). Illustrative: needs a key and may take hours.
from inspect_ai import eval
from inspect_ai.model import BatchConfig

from triage import triage

if __name__ == "__main__":
    eval(triage(), model="openai/gpt-6-luna",
         batch=BatchConfig(size=200, send_delay=60))   # 200 requests per batch; send a partial batch after 60 s

Example output (illustrative — your exact output will differ): the usual results panel, but only after the provider has processed every batch, which can take from minutes to many hours.

BatchConfig field Documented default Meaning
size 100 Target requests per batch
send_delay 15 s Longest wait before sending a partly filled batch
tick 15 s How often to check for new requests and finished batches
max_batches 50 Batches in flight per provider
max_size, max_consecutive_check_failures (not documented on the batch page) A hard size cap; how many failed status checks to tolerate

Supported (as of November 2026): OpenAI, Anthropic, Google, xAI and Together AI; for other providers batch is silently ignored. Batch mode uses static concurrency (adaptive is off). Anthropic's refusal fallback and Google's web search and thinking are not available in batch mode.

When it fits, and when it does not. The deciding number is how many sequential model calls each sample makes, because every one of them waits for a whole batch to finish:

Eval shape Sequential calls per sample Batch mode
Classification or QA with a code scorer (the triage task) 1 A good fit: one round of batches
QA with a model grader 2 (answer, then grade) Usually fine: two rounds
Multi-turn conversations, self-critique 3 to 10 Slow: each turn waits for a batch
Agents with tools Tens, and variable A bad fit: days of wall time, and samples wait on each other

For the nightly, large, single-turn suites, batch mode can halve the cost. For anything in the CI path, or any agent, it is the wrong tool. 03.9, Part 14 has a provider-neutral worked example of the choice, including flex tiers, which are often the better middle ground for evals (-M service_tier=flex on OpenAI).


Part 8: The sample error policy#

8.1 Errors, failures and what this part decides#

A sample error is an exception that escapes a sample's solver chain or scorer: a tool that times out, a parser that throws on a malformed reply, model retries that ran out, a scorer that crashes on an unexpected output. It is different from a wrong answer (the model answered and the scorer said I) and from an unscored sample (the scorer deliberately returned Score.unscored() or None), both covered by the scoring policy in 10B.10, Part 4. An errored sample has sample.error set, no scores (unless score_on_error), and is left out of the metric's denominator.

The settings in this part answer four questions about errors: how many to tolerate before the run counts as failed (fail_on_error), whether to stop at once or finish first (continue_on_fail), whether to try a failed sample again (retry_on_error), and whether to score it anyway (score_on_error). Each can be set on the Task (the author's default), overridden on eval() and the CLI (--fail-on-error, --no-fail-on-error, --continue-on-fail, --retry-on-error[=N], --score-on-error), and is recorded in log.eval.config.

8.2 fail_on_error: a boolean, a proportion or a count#

The task below has ten samples and an "order lookup" step that fails on demand. Two samples (s03, s07) fail every time, like a bug that only certain inputs trigger:

python
# r06_errors.py: the sample error policy, threshold by threshold (lesson 10B.12)
from collections import Counter

from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver

ATTEMPTS: Counter = Counter()
PLAN: dict[str, int] = {}          # sample id -> how many attempts fail before one succeeds


@solver
def lookup_order() -> Solver:
    """Stands in for a tool call (an order-service lookup) that can fail."""
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        sid = str(state.sample_id)
        ATTEMPTS[sid] += 1
        if ATTEMPTS[sid] <= PLAN.get(sid, 0):
            raise RuntimeError(f"order service timed out ({sid}, attempt {ATTEMPTS[sid]})")
        return state
    return solve


def task() -> Task:
    return Task(dataset=[Sample(id=f"s{i:02}", input="Say: default output", target="default output")
                         for i in range(1, 11)],
                solver=[lookup_order(), generate()], scorer=includes(), name="orders")


def run(label: str, plan: dict[str, int], **kwargs) -> None:
    ATTEMPTS.clear(); PLAN.clear(); PLAN.update(plan)
    log = eval(task(), model="mockllm/model", log_dir="logs-r06", display="none", **kwargs)[0]
    samples = log.samples or []
    errored = sorted(str(s.id) for s in samples if s.error)
    retried = sorted(str(s.id) for s in samples if s.error_retries)
    res = log.results.scores[0] if log.results and log.results.scores else None
    acc = f"{res.metrics['accuracy'].value:.3f}" if res else "-"
    print(f"{label:38} status={log.status:7} logged={len(samples):2} errored={errored} retried={retried} "
          f"scored={res.scored_samples if res else '-'} accuracy={acc} attempts={sum(ATTEMPTS.values())}")


ALWAYS = 99                                  # a persistent failure (a bug, not a blip)
if __name__ == "__main__":
    two_bugs = {"s03": ALWAYS, "s07": ALWAYS}    # 2 of 10 samples fail every time

    run("fail_on_error=True (default)", two_bugs)
    run("fail_on_error=False", two_bugs, fail_on_error=False)
    run("fail_on_error=0.1 (10% or more)", two_bugs, fail_on_error=0.1)
    run("fail_on_error=0.3", two_bugs, fail_on_error=0.3)
    run("fail_on_error=1 (1 or more samples)", two_bugs, fail_on_error=1)
    run("fail_on_error=3", two_bugs, fail_on_error=3)
    run("fail_on_error=1, continue_on_fail=True", two_bugs, fail_on_error=1, continue_on_fail=True)
    print()
    blips = {"s03": 1, "s07": 1}                 # 2 samples fail once, then succeed
    run("transient blips, no retry", blips, fail_on_error=False)
    run("transient blips, retry_on_error=1", blips, retry_on_error=1)
    run("persistent bugs, retry_on_error=3", two_bugs, retry_on_error=3, fail_on_error=False)
bash
uv run python r06_errors.py
Output · real11 lines
fail_on_error=True (default)           status=error   logged=10 errored=['s03', 's07'] retried=[] scored=- accuracy=- attempts=10
fail_on_error=False                    status=success logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10
fail_on_error=0.1 (10% or more)        status=error   logged=10 errored=['s03', 's07'] retried=[] scored=- accuracy=- attempts=10
fail_on_error=0.3                      status=success logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10
fail_on_error=1 (1 or more samples)    status=error   logged=10 errored=['s03', 's07'] retried=[] scored=- accuracy=- attempts=10
fail_on_error=3                        status=success logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10
fail_on_error=1, continue_on_fail=True status=error   logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10

transient blips, no retry              status=success logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10
transient blips, retry_on_error=1      status=success logged=10 errored=[] retried=['s03', 's07'] scored=10 accuracy=1.000 attempts=12
persistent bugs, retry_on_error=3      status=success logged=10 errored=['s03', 's07'] retried=['s03', 's07'] scored=8 accuracy=1.000 attempts=16

Read the first block row by row:

Setting Meaning (as implemented in 0.3.292) Here (2 of 10 failed)
True (the default) Fail on the first error error, no results computed
False Never fail because of errors success, accuracy 1.000 over the 8 samples that ran
0.1 Fail once errors reach 10% of the samples (a value below 1 is a proportion) 20% ≥ 10%: error
0.3 Fail once errors reach 30% 20% < 30%: success
1 Fail once errors reach 1 sample (a value of 1 or more is a count), so the same as True error
3 Fail once errors reach 3 samples success
1 with continue_on_fail=True Keep running, then decide error, but every sample ran and results were computed

The docs describe the threshold as "more than": "fail_on_error=0.1 | Fail if more than 10% of total samples have errors", "fail_on_error=5 | Fail eval if more than 5 samples have errors". The installed source compares with >= (_eval/task/error.py), and the boundary confirms it:

python
# r06c_boundary.py: is the fail_on_error threshold "more than" or "at least"? (lesson 10B.12)
from r06_errors import ALWAYS, run

print("boundary cases, 10 samples:")
run("1 error,  fail_on_error=0.1", {"s03": ALWAYS}, fail_on_error=0.1)
run("1 error,  fail_on_error=0.11", {"s03": ALWAYS}, fail_on_error=0.11)
run("2 errors, fail_on_error=2", {"s03": ALWAYS, "s07": ALWAYS}, fail_on_error=2)
run("2 errors, fail_on_error=3", {"s03": ALWAYS, "s07": ALWAYS}, fail_on_error=3)
Output · real5 lines
boundary cases, 10 samples:
1 error,  fail_on_error=0.1            status=error   logged=10 errored=['s03'] retried=[] scored=- accuracy=- attempts=10
1 error,  fail_on_error=0.11           status=success logged=10 errored=['s03'] retried=[] scored=9 accuracy=1.000 attempts=10
2 errors, fail_on_error=2              status=error   logged=10 errored=['s03', 's07'] retried=[] scored=- accuracy=- attempts=10
2 errors, fail_on_error=3              status=success logged=10 errored=['s03', 's07'] retried=[] scored=8 accuracy=1.000 attempts=10

One error in ten (exactly 10%) fails fail_on_error=0.1, and two errors fail fail_on_error=2. So the threshold is "at least", not "more than": to tolerate up to N errors, set N + 1, and to tolerate up to 10%, set a proportion slightly above 0.1. (r06_errors.py guards its demonstration runs with if __name__ == "__main__":, so the boundary script can import its run() helper without re-running them.)

Three things to notice:

  • Every tolerated row reports accuracy 1.000 over 8. The two failing samples are not in the denominator. If those two inputs are exactly the ones your system cannot handle (here, a lookup that breaks on certain orders), the tolerated run reports a perfect score for a system that fails 20% of the time. This is the most common way an Inspect number overstates quality, and the reason 10B.10, 4.6 insists on reporting coverage next to every metric.
  • "Fail fast" did not stop the run early here. All ten samples were already running concurrently when the first error arrived, so all ten were logged. With more samples than connections, fail-fast does cancel the rest (10B.8, 9.6 logged 2 of 4); either way, the completed samples are kept for eval_retry().
  • continue_on_fail changes when the threshold is applied, not whether: without it the run stops when the threshold is crossed; with it every sample runs (so you see the full extent of the problem and get results), and the status is still error at the end. Use it for diagnosis runs, where you want to know how many samples are affected.

8.3 Which threshold to use#

Run Setting Why
Development, a new task fail_on_error=False or --continue-on-fail See every failure in one run, fix them all
CI on a fixed regression set Default (True), then the gate Any error means the eval or the system is broken; never gate on a partial run
Long runs against a flaky tool or sandbox infrastructure A small proportion (0.02) with retry_on_error Tolerate rare infrastructure noise, fail on systematic breakage
Release numbers Default, or a tolerance you report, with the error count next to the metric A reader must know what the number excludes

The docs' own advice matches: tolerate errors during development, but "ensure there are never errors when running in production", which eval(..., fail_on_error=False) on the command line of a release run quietly defeats.

8.4 retry_on_error and distribution shift#

The second block of the output separates two kinds of failure:

  • Transient blips (s03 and s07 fail once, then succeed). Without retries, they are errors and leave the denominator. With retry_on_error=1, both re-ran from scratch and succeeded: 12 attempts, 10 scored, nothing missing, and each retried sample records the original exception in sample.error_retries.
  • Persistent bugs (s03 and s07 fail every time). retry_on_error=3 ran each of them four times (16 attempts in total), then gave up; they are still errors. Retries cost money and fixed nothing.

So sample retries are the right tool for infrastructure blips that the model-call retries of Part 5 cannot see: a sandbox that failed to start, a tool backend that timed out, a solver step that depends on a flaky service. They are the wrong tool for bugs. And they carry a measurement risk the handling-errors page spells out: if the failures are correlated with the input (an agent that crashes on a certain kind of task), retried samples get several chances to succeed while the others get one, which shifts the distribution of what you measure. The page's instruction is to check, after the fact, that retried samples do not score differently from the rest. A check you can run on any log:

python
# retry_shift.py: do samples that needed a retry score differently? (lesson 10B.12)
"""Usage: python retry_shift.py LOG_FILE SCORER"""
import sys

from inspect_ai.log import read_eval_log
from inspect_ai.scorer import value_to_float

log = read_eval_log(sys.argv[1])
scorer = sys.argv[2]
to_float = value_to_float()
groups: dict[bool, list[float]] = {True: [], False: []}
for sample in log.samples:
    if sample.error or scorer not in (sample.scores or {}):
        continue
    groups[bool(sample.error_retries)].append(to_float(sample.scores[scorer].value))
for retried, values in groups.items():
    label = "retried" if retried else "first try"
    mean = sum(values) / len(values) if values else float("nan")
    print(f"{label:10} n={len(values):4}  mean={mean:.3f}")

Run on the retry_on_error=1 log from the run above (two blips, both retried):

bash
uv run python retry_shift.py logs-r06/<the retry_on_error=1 log>.eval includes
Output · real2 lines
retried    n=   2  mean=1.000
first try  n=   8  mean=1.000

Here the blips were genuinely transient (the mock fails twice regardless of input), and the two groups look the same. With a handful of retried samples, as here, the comparison is noisy; what you are looking for is a gross difference (retried samples passing at 95% when the rest pass at 60%), or a concentration of retries in one slice of the data (group by metadata), either of which says the "transient" errors are not transient. The CI gate in Part 13 warns whenever retried samples exist, so a person looks.

8.5 score_on_error#

score_on_error=True scores an errored sample on whatever state it reached, after any retries are exhausted, so the failure counts against the system instead of leaving the denominator. The errors still count toward fail_on_error (so --score-on-error --fail-on-error=0.1 scores everything but still marks the log error above 10%), and in an eval set, errored-but-scored samples are re-run on task retries. Your scorer must cope with a partial state (no output, a truncated history). 10B.10, 4.3 works through when this is the right policy (the system's own crashes are failures a user would see) and the related trap of a TimeoutError that is silently scored instead of erroring.

8.6 Refusals: an output or an error?#

A refusal is a provider declining to answer (a safety classifier, a content filter), surfaced as stop_reason="content_filter". By default it is not an error: the sample continues with whatever (usually empty) output it got and is scored. fail_on_refusal (added in 0.3.264) turns refusals into sample errors (ModelRefusalError) instead:

python
# r06b_refusals.py: refusals are not errors unless you say so; scorer crashes are (lesson 10B.12)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import Score, Target, accuracy, includes, scorer
from inspect_ai.solver import TaskState


def replies(input, tools, tool_choice, config) -> ModelOutput:
    if "refund" in input[-1].text:          # the provider's safety filter declines this one
        return ModelOutput.from_content(model="mockllm", content="", stop_reason="content_filter")
    return ModelOutput.from_content(model="mockllm", content="ok, done")


DATA = [Sample(id="r1", input="Close my ticket", target="ok"),
        Sample(id="r2", input="Process my refund", target="ok"),
        Sample(id="r3", input="Reset my password", target="ok")]


def run(label: str, scorer_=None, **kwargs) -> None:
    model = get_model("mockllm/model", custom_outputs=replies, memoize=False)
    log = eval(Task(dataset=DATA, scorer=scorer_ or includes(), name="refusals"), model=model,
               log_dir="logs-r06b", display="none", **kwargs)[0]
    r2 = next(s for s in log.samples if s.id == "r2")
    stop = r2.output.choices[0].stop_reason if r2.output.choices else "(no output)"
    error = r2.error.message[:42] if r2.error else None
    res = log.results.scores[0] if log.results and log.results.scores else None
    metric = f"accuracy={res.metrics['accuracy'].value:.3f} over {res.scored_samples}" if res else "no results"
    print(f"{label:42} status={log.status:7} | r2 stop_reason={stop} error={error} | {metric}")


run("default (a refusal is just an output)")
run("fail_on_refusal=True", fail_on_refusal=True)
run("fail_on_refusal=True, fail_on_error=False", fail_on_refusal=True, fail_on_error=False)


@scorer(metrics=[accuracy()])
def brittle():
    async def score(state: TaskState, target: Target) -> Score:
        return Score(value="C" if state.metadata["expected"] in state.output.completion else "I")
    return score


run("a scorer that raises KeyError", scorer_=brittle(), fail_on_error=False)
bash
uv run python r06b_refusals.py
Output · real4 lines
default (a refusal is just an output)      status=success | r2 stop_reason=content_filter error=None | accuracy=0.667 over 3
fail_on_refusal=True                       status=error   | r2 stop_reason=(no output) error=ModelRefusalError('Model refusal (mockllm/ | no results
fail_on_refusal=True, fail_on_error=False  status=success | r2 stop_reason=(no output) error=ModelRefusalError('Model refusal (mockllm/ | accuracy=1.000 over 2
a scorer that raises KeyError              status=success | r2 stop_reason=content_filter error=KeyError('expected') | no results

The same refused sample gives three different numbers:

  • Default: the empty answer is scored and fails: accuracy 0.667 over 3. The refusal counts as a wrong answer.
  • fail_on_refusal=True with the default error policy: the refusal is an error and fails the run.
  • fail_on_refusal=True, fail_on_error=False: the refusal is an error, tolerated, and leaves the denominator: accuracy 1.000 over 2.

Neither 0.667 nor 1.000 is wrong; they answer different questions. If refusals are a product failure (a support bot that will not process refunds), count them as wrong answers, the default. If they are an artefact of the eval (a red-team prompt that is supposed to be refused is in a different eval; a provider classifier that misfires on synthetic data), make them errors and report the refusal count next to the metric. What you must not do is let the choice happen by accident. The setting applies to role models too (a grader that refuses), unless the role sets its own; Anthropic's fallback_models (2.2) is the alternative that retries a refused request on another model, and changes what you are measuring accordingly. Refusals in safety evaluations are Module 12's subject (12).

8.7 Errors raised by scorers#

The last row of the refusals run used a scorer that reads state.metadata["expected"], a key the samples do not have. Every sample errored with KeyError('expected'), the run (tolerating errors) still said success, and there were no results at all. A scorer exception is a sample error like any other: it follows the same policy, the sample has no score, and with fail_on_error=False a scorer bug produces a "successful" run with an empty or partial results table. That is the scorer-side version of the 1.000-over-8 trap, and the reason to unit-test scorers before running them (10B.10, 5.2) and to gate on coverage per scorer, which the gate in Part 13 does.

8.8 Debugging an error#

Flag Effect Use
--debug-errors (debug_errors=True, INSPECT_DEBUG_ERRORS) Raise the first sample error instead of logging it, so a debugger or a plain traceback stops at the cause Reproducing one failure locally, usually with --sample-id and --max-connections 1
--traceback-locals Include local variables in tracebacks Hard bugs; the docs warn it can leak secrets such as API keys into logs, so never in CI
--log-level debug / http / trace More console output; http shows every request and retry Provider problems
The VS Code extension's Debug Task Runs with --limit 1 under the debugger Stepping through a solver (10B.8, 6.3)

Every sample error is also in the log with its traceback (sample.error.traceback), and Inspect View shows it next to the transcript, which is usually enough.


Part 9: Recovering work: eval_retry and crash recovery#

9.1 eval_retry(): what it re-runs and where the new log goes#

A task log with status error (or started, after a crash) can be finished instead of re-run. orders_task.py is a six-sample task whose order lookup fails on sample s03 while a flag file says so, and which appends every attempt to a file so the retry can be audited:

python
# orders_task.py: an import-safe task whose tool step fails while a flag file says so (lesson 10B.12)
"""Each attempt is appended to attempts.txt, so a retry can be audited from outside.

fail.flag holds the number of failures still to inject into sample s03.
"""
from pathlib import Path

from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver

HERE = Path(__file__).parent
FLAG, ATTEMPTS = HERE / "fail.flag", HERE / "attempts.txt"


@solver
def lookup_order() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        with ATTEMPTS.open("a") as f:
            f.write(f"{state.sample_id}\n")
        left = int(FLAG.read_text()) if FLAG.exists() else 0
        if state.sample_id == "s03" and left > 0:
            FLAG.write_text(str(left - 1))
            raise RuntimeError("order service timed out")
        return state
    return solve


@task
def orders(n: int = 6) -> Task:
    return Task(dataset=[Sample(id=f"s{i:02}", input="Say: default output", target="default output")
                         for i in range(1, n + 1)],
                solver=[lookup_order(), generate()], scorer=includes())
python
# r07_retry.py: eval_retry(): what it re-runs, where the new log goes, what it needs (lesson 10B.12)
import os
import shutil
from collections import Counter

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

from orders_task import ATTEMPTS, FLAG, orders, lookup_order

for d in ("logs-r07", "logs"):
    shutil.rmtree(d, ignore_errors=True)


def attempts() -> Counter:
    return Counter(ATTEMPTS.read_text().split()) if ATTEMPTS.exists() else Counter()


# 1. A run that fails (default fail_on_error=True): s03 errors
ATTEMPTS.unlink(missing_ok=True); FLAG.write_text("1")
first = eval(orders(), model="mockllm/model", log_dir="logs-r07", display="none")[0]
ok = [str(s.id) for s in first.samples if not s.error]
print("1 first run:", first.status, "| completed samples kept in the log:", ok)

# 2. Retry it: only the failed sample runs again
ATTEMPTS.unlink()
retried = eval_retry(first.location, display="none")[0]
print("2 eval_retry:", retried.status, "| samples re-run:", dict(attempts()),
      "| samples in new log:", len(retried.samples))
print("  same file?", retried.location == first.location,
      "| same task_id?", retried.eval.task_id == first.eval.task_id,
      "| same eval_id?", retried.eval.eval_id == first.eval.eval_id)
print("  new log written to:", os.path.relpath(os.path.dirname(retried.location.replace("file://", ""))))
print("  logs-r07 still holds:", [read_eval_log(i, header_only=True).status
                                   for i in list_eval_logs("logs-r07")])

# 3. Keep the retry next to the original with log_dir=
FLAG.write_text("1")
first = eval(orders(), model="mockllm/model", log_dir="logs-r07", display="none")[0]
retried = eval_retry(first.location, log_dir="logs-r07", display="none")[0]
print("3 with log_dir='logs-r07':", retried.status, "| logs-r07 now holds:",
      [read_eval_log(i, header_only=True).status for i in list_eval_logs("logs-r07")])

# 4. A Task built without @task cannot be rebuilt from the log
FLAG.write_text("1")
adhoc = Task(dataset=orders().dataset, solver=[lookup_order()], name="adhoc")
log = eval(adhoc, model="mockllm/model", log_dir="logs-r07", display="none")[0]
try:
    eval_retry(log.location, log_dir="logs-r07", display="none")
except Exception as ex:
    print("4 retry of an undecorated Task ->", type(ex).__name__ + ":", str(ex)[:60])
FLAG.unlink(missing_ok=True)
bash
uv run python r07_retry.py
Output · real7 lines
1 first run: error | completed samples kept in the log: ['s01', 's02', 's04', 's05', 's06']
2 eval_retry: success | samples re-run: {'s03': 1} | samples in new log: 6
  same file? False | same task_id? True | same eval_id? False
  new log written to: logs
  logs-r07 still holds: ['error']
3 with log_dir='logs-r07': success | logs-r07 now holds: ['success', 'error', 'error']
4 retry of an undecorated Task -> FileNotFoundError: Task 'adhoc' not found.
  1. The failed run keeps its completed samples. Five of six samples are in the errored log.
  2. The retry re-ran only s03. The attempts file shows one attempt, for s03; the other five samples were copied from the errored log into a new, complete log of six. This is sample preservation, and it is what makes retrying a 2,000-sample run after a failure at sample 1,800 cheap. It depends on stable sample ids (11.6).
  3. A new file, the same task. The retry writes a new log with a new eval_id but the same task_id (the log file name ends in the same id, so the two are easy to pair), and leaves the errored log where it was.
  4. The new log went to ./logs, not to logs-r07 where the original was. eval_retry() uses the default log directory unless you pass log_dir= (run 3), and the docs do not mention this; a CI job that looks for the retried log next to the original finds only the error. Always pass log_dir.
  5. Only @task tasks can be retried. A Task(...) built inline has no registered name, so the retry cannot rebuild it: FileNotFoundError: Task 'adhoc' not found. The registry (10B.8, 2.2) is what records how to rebuild a task: its file, its @task name and its arguments.

eval_retry() accepts the run-level options of eval() (concurrency, error policy, max_retries, timeout, logging), so the common pattern for a rate-limit failure is to retry with less concurrency: eval_retry(log, log_dir=..., max_connections=5).

9.2 Task files must be import-safe#

Because the retry re-imports the task file, a file that both defines a task and runs an eval at import time breaks it. bad_runner.py has no if __name__ == "__main__": guard:

python
# bad_runner.py: a task file that also runs the eval when imported (the anti-pattern, lesson 10B.12)
from pathlib import Path

from inspect_ai import Task, eval, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, TaskState, generate, solver

FLAG = Path(__file__).parent / "bad.flag"


@solver
def flaky():
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        if state.sample_id == 2 and FLAG.exists():
            raise RuntimeError("order service timed out")
        return await generate(state)
    return solve


@task
def bad_orders() -> Task:
    return Task(dataset=[Sample(id=i, input="hi", target="default") for i in (1, 2, 3)],
                solver=flaky(), scorer=includes())


# No `if __name__ == "__main__":` guard: this runs on every import of the file.
log = eval(bad_orders(), model="mockllm/model", log_dir="logs-r07b", display="none")[0]
print("bad_runner ran an eval at import time:", log.status)
python
# r07b_retry_import.py: retrying a log whose task file runs an eval at import time (lesson 10B.12)
from pathlib import Path

from inspect_ai import eval_retry
from inspect_ai.log import list_eval_logs

Path("bad.flag").unlink(missing_ok=True)
errored = list_eval_logs("logs-r07b")[0]
try:
    eval_retry(errored, log_dir="logs-r07b", display="none")
except Exception as ex:
    print("eval_retry ->", type(ex).__name__ + ":", str(ex)[:70])
bash
touch bad.flag && uv run python bad_runner.py   # an errored run
uv run python r07b_retry_import.py             # try to retry it
Output · real4 lines
$ python bad_runner.py
bad_runner ran an eval at import time: error
$ python r07b_retry_import.py
eval_retry -> RuntimeError: Already running asyncio in this thread

The retry imported bad_runner.py, which started a second eval() inside the retry's running event loop, and Inspect refused. The same happens with inspect eval-retry, with eval sets (which import task files to pair them with logs) and with inspect score. The fix is the convention 10B.8 set for triage.py: task files define, scripts run. Put eval() calls under if __name__ == "__main__": or in a separate file.

9.3 From the command line#

bash
echo 1 > fail.flag      # make s03 fail once
inspect eval orders_task.py --model mockllm/model --log-dir logs-r07c --display plain
inspect eval-retry logs-r07c/<the errored log>.eval --log-dir logs-r07c --display plain
inspect log list --log-dir logs-r07c --status error
inspect log list --log-dir logs-r07c --status success
Output · real; the progress display and the traceback panel are trimmed17 lines
$ inspect eval orders_task.py --model mockllm/model --log-dir logs-r07c --display plain
inspect eval-retry
logs-r07c/2026-11-24T17-59-23-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval
Log: logs-r07c/2026-11-24T17-59-23-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval
---------------------------------------------------------
$ inspect eval-retry logs-r07c/2026-11-24T17-59-23-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval --log-dir logs-r07c --display plain
total time:               0:00:00
mockllm/model             222 tokens [I: 24, O: 198]
includes
accuracy  1.000
stderr    0.000
Log: logs-r07c/2026-11-24T17-59-24-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval
---------------------------------------------------------
$ inspect log list --log-dir logs-r07c --status error
logs-r07c/2026-11-24T17-59-23-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval
$ inspect log list --log-dir logs-r07c --status success
logs-r07c/2026-11-24T17-59-24-00-00_orders_j5X3UwjTeWLrcSM9dLSNro.eval

The first run ends with Inspect's own suggestion to run inspect eval-retry. The retry reports tokens for one sample (the mock's 222 tokens are its synthetic count for one reply) and accuracy over all six, because five came from the first log. Notice the two log names: same task id (j5X3...), new timestamp. inspect log list --status is the quickest way to find what still needs retrying in a directory. inspect eval-retry accepts several logs at once, and the same options as eval_retry().

9.4 Crash recovery: when the process dies#

An exception produces a log with status error and every completed sample. A crash (out of memory, kill -9, a laptop lid, a CI runner pre-empted) never gets to write the final log: the file is left with status started, and samples completed since the last write are not in it. Inspect keeps them anyway, in a sample buffer database in its data directory (on macOS under ~/Library/Application Support/inspect_ai/samplebuffer), kept for three days after the process exits. A crash, recovered:

python
# slow_task.py: a 20-sample task whose tool step takes half a second (lesson 10B.12)
from pathlib import Path

import anyio

from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver

ATTEMPTS = Path(__file__).parent / "slow_attempts.txt"


@solver
def slow_lookup() -> Solver:
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        with ATTEMPTS.open("a") as f:
            f.write(f"{state.sample_id}\n")
        await anyio.sleep(0.5)
        return state
    return solve


@task
def slow_orders() -> Task:
    return Task(dataset=[Sample(id=f"o{i:02}", input="Say: default output", target="default output")
                         for i in range(1, 21)],
                solver=[slow_lookup(), generate()], scorer=includes())
bash
# r09_crash.sh: kill an eval mid-run with SIGKILL, then recover and finish it (lesson 10B.12)
rm -rf logs-r09 slow_attempts.txt
inspect eval slow_task.py --model mockllm/model --max-samples 2 --log-dir logs-r09 --display none &
PID=$!
sleep 4 && kill -9 $PID && echo "killed the eval process after 4 seconds"
wait $PID 2>/dev/null
echo "attempts before the crash: $(wc -l < slow_attempts.txt | tr -d ' ')"
echo '$ inspect log list --log-dir logs-r09 --status started'
inspect log list --log-dir logs-r09 --status started
echo '$ inspect log recover --list --log-dir logs-r09'
inspect log recover --list --log-dir logs-r09
LOG=$(ls logs-r09/*.eval | head -1)
echo "\$ inspect log recover $LOG"
inspect log recover "$LOG"
: > slow_attempts.txt
REC=$(ls logs-r09/*-recovered.eval | head -1)
echo "\$ inspect eval-retry $REC --log-dir logs-r09 --display plain"
inspect eval-retry "$REC" --log-dir logs-r09 --display plain | tail -7
echo "samples re-run by the retry: $(wc -l < slow_attempts.txt | tr -d ' ')"
bash
uv run bash r09_crash.sh
Output · real26 lines
killed the eval process after 4 seconds
attempts before the crash: 12
$ inspect log list --log-dir logs-r09 --status started
logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ.eval
$ inspect log recover --list --log-dir logs-r09

log: logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ.eval
  source: database
  (20 total, 6 flushed, 4 completed, 2 in-progress)

$ inspect log recover logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ.eval
Recovered 12 samples to logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ-recovered.eval
  status: error

To re-run the 2 failed/cancelled samples:
  inspect eval-retry logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ-recovered.eval
$ inspect eval-retry logs-r09/2026-11-24T18-00-32-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ-recovered.eval --log-dir logs-r09 --display plain
Monitor from another shell: inspect ctl task list   (inspect ctl --help)
mockllm/model               740 tokens [I: 80, O: 660]
includes
accuracy  1.000
stderr    0.000
Log: logs-r09/2026-11-24T18-00-38-00-00_slow-orders_4NjYiLgVGhwhPE858B5xqJ.eval
---------------------------------------------------------

samples re-run by the retry: 10

Read it as an incident timeline:

  1. The crash. Twelve sample attempts had started when the process was killed (with max_samples=2 and a half-second step, roughly two per half second).
  2. The log says started. inspect log list --status started finds crashed runs; that status never appears on a run that ended normally.
  3. The buffer had more than the file. Of 20 samples, 6 had been flushed to the log file (the .eval default buffer for 20 samples is floor(20 / 3) = 6), 4 more had completed but were only in the buffer, and 2 were in progress.
  4. Recovery wrote a new log (...-recovered.eval) with 12 samples: 10 complete, plus the 2 in progress recorded as cancelled errors, with status error and a ready-made eval-retry command.
  5. The retry re-ran 10 samples: the 2 cancelled and the 8 that had never started. The 10 completed ones were reused.

Without the buffer, the 4 completed-but-unflushed samples would have been lost. Two settings change those numbers: a smaller max_samples means fewer samples in progress at any moment, and a smaller log_buffer writes to the file more often (at some I/O cost). For runs where a crash is expensive (a long agent eval on a pre-emptible machine), lower both.

You rarely have to do this by hand: eval_retry() and eval sets recover crashed logs automatically before retrying, so re-running the same eval-set command after a crash picks up the buffered samples. Do it by hand when you want to inspect what happened (inspect log recover <log> --output <elsewhere> keeps the eval-set directory untouched) or when the crash happened on another machine (recover_eval_log(..., allow_no_buffer=True) in Python recovers from the flushed samples alone; only use it on a run you know has ended). The Python API is recoverable_eval_logs() and recover_eval_log() in inspect_ai.log.

9.5 Stalled samples: incomplete_action#

Agent evals have a failure mode that plain recovery makes worse: a few samples hang, the process is eventually killed, recovery marks them as cancelled, the retry runs them again, and they hang again. --incomplete-action error (on inspect log recover, inspect eval-retry and inspect eval-set, or incomplete_action="error" in Python) records in-progress samples as operator terminations instead, and if every expected sample is then final, finalizes the log with status success so nothing retries it. --incomplete-max guards against hiding a systemic failure: a count (≥ 1) or a proportion (< 1) of in-progress samples above which recovery refuses (manual) or falls back to retrying (automatic). Treat it like fail_on_error=False: the terminated samples are errors that leave the denominator, so report them.


Part 10: Logging options for long runs#

Reference

Everything a run records goes into its log; 10B.13 teaches reading and analysing logs. For running at scale, a handful of settings control what is written and when:

Option Default What it changes When to change it
--log-dir / INSPECT_LOG_DIR ./logs Where logs go Always set it for real runs; one directory per eval set
--log-format eval .eval (compressed) or .json Keep .eval; sharding requires it
--log-buffer N .eval: min(samples / 3, 10), so small runs flush often; 10 for local .json; 100 for remote .json Samples buffered before each write to the log file Lower for crash-prone runs, higher for very fast ones on slow storage
--log-shared [N] Off Sync sample events to the log directory every N seconds (10 with True) so others can watch live A shared directory (S3) watched by a team
--no-log-realtime Realtime on Live event logging for watching a running sample Very large runs where the overhead matters
--no-log-samples Samples logged Keep only the header and results Almost never: without samples you cannot audit, retry with reuse or compare paired
--no-log-images Images logged Drop images and media from the log Multimodal evals with huge logs
--tags, --metadata key=value None Recorded on the run (merged with the task's) Always: record the commit, the dataset hash, the snapshot id, the purpose
--display full full, conversation, rich, plain, log, none plain or log in CI, none in scripts
INSPECT_EVAL_LOG_FILE_PATTERN {timestamp}_{task}_{id} The log file name (can add {model}) Many models in one directory

Logs and eval-set directories can live on S3 or other fsspec filesystems (--log-dir s3://bucket/evals/nightly), which is the usual setup for shared CI runs. Remember that logs record your git remote and revision (10B.8, 6.4) and every prompt and answer: they are as sensitive as the data in them.


Part 11: Eval sets: the unit of a real run#

Deep-dive

11.1 What an eval set is#

An eval set is a run of several task × model pairs that owns a log directory and keeps working on it until every pair has a successful log. It bundles everything in Parts 8 and 9 into one command: automatic task retries, sample reuse, crash recovery, cleanup of failed logs, and an exit code that means something. inspect eval-set and eval_set() take the same arguments as inspect eval and eval() plus a few of their own, and eval_set() returns (success, logs), where logs are headers only (no samples; read the files for those).

Option Default Meaning
log_dir INSPECT_LOG_DIR or ./logs (since 0.3.262; earlier it was required) The scope of the set: give each set its own directory
retry_attempts 10 Task retries before giving up
retry_immediate True (since 0.3.218) Retry each failed task as soon as it fails, reusing its completed samples
retry_wait 30 s, doubling Wait between rounds, only with retry_immediate=False
retry_connections 1.0 Factor to shrink max_connections per round, only with retry_immediate=False
retry_cleanup True Delete failed logs once their task succeeds (--no-retry-cleanup keeps them)
max_tasks max(10, number of models) Tasks in parallel, balanced across models
log_dir_allow_dirty False Allow logs in the directory that do not belong to the set
bundle_dir, bundle_overwrite None Write a static Inspect View site for the set (11.8)
incomplete_action, incomplete_max retry Stalled samples after a crash (9.5)

11.2 A first set, with a failure#

Two tasks (orders with six and with three samples, which are different tasks because their arguments differ), one transient failure, then the same call repeated and amended:

python
# r08_eval_set.py: eval sets: retries, sample reuse, no-op re-runs, amendments, identity (lesson 10B.12)
import json
import shutil
from collections import Counter
from pathlib import Path

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

from orders_task import ATTEMPTS, FLAG, orders

DIR = "logs-r08"
shutil.rmtree(DIR, ignore_errors=True)


def attempts() -> dict:
    counts = Counter(ATTEMPTS.read_text().split()) if ATTEMPTS.exists() else Counter()
    ATTEMPTS.unlink(missing_ok=True)
    return dict(sorted(counts.items()))


def logs_in_dir() -> list[str]:
    out = []
    for info in list_eval_logs(DIR):
        h = read_eval_log(info, header_only=True)
        out.append(f"{h.eval.task}(n={h.eval.task_args.get('n')}) {h.eval.model} "
                   f"epochs={h.eval.config.epochs} {h.status}")
    return sorted(out)


def run(label: str, tasks, **kwargs) -> None:
    ok, logs = eval_set(tasks, log_dir=DIR, display="none", **kwargs)
    print(f"{label}\n  success={ok} | attempts this call={attempts()}")
    for line in logs_in_dir():
        print("   ", line)


# 1. s03 of orders(n=6) fails once: the set retries the task and reuses the 5 good samples
ATTEMPTS.unlink(missing_ok=True); FLAG.write_text("1")
run("1 first call (one transient failure)", [orders(n=6), orders(n=3)], model="mockllm/model")
print("  files:", sorted(p.name if not p.name.endswith(".eval") else "*.eval" for p in Path(DIR).iterdir()))

# 2. The same call again: nothing left to do
run("2 identical second call", [orders(n=6), orders(n=3)], model="mockllm/model")

# 3. Amend: a second model
run("3 add a model", [orders(n=6), orders(n=3)], model=["mockllm/model", "mockllm/other"])

# 4. Amend: more epochs
run("4 epochs=2", [orders(n=6), orders(n=3)], model=["mockllm/model", "mockllm/other"], epochs=2)

# 5. What the set records about itself
spec = json.loads(Path(DIR, "eval-set.json").read_text())
print("5 eval-set.json keys:", sorted(spec), "| tasks:", len(spec["tasks"]),
      "| task keys:", sorted(spec["tasks"][0]))
bash
uv run python r08_eval_set.py
Output · real22 lines
1 first call (one transient failure)
  success=True | attempts this call={'s01': 2, 's02': 2, 's03': 3, 's04': 1, 's05': 1, 's06': 1}
    orders(n=3) mockllm/model epochs=1 success
    orders(n=6) mockllm/model epochs=1 success
  files: ['*.eval', '*.eval', '.eval-set-id', 'eval-set.json', 'logs.json']
2 identical second call
  success=True | attempts this call={}
    orders(n=3) mockllm/model epochs=1 success
    orders(n=6) mockllm/model epochs=1 success
3 add a model
  success=True | attempts this call={'s01': 2, 's02': 2, 's03': 2, 's04': 1, 's05': 1, 's06': 1}
    orders(n=3) mockllm/model epochs=1 success
    orders(n=3) mockllm/other epochs=1 success
    orders(n=6) mockllm/model epochs=1 success
    orders(n=6) mockllm/other epochs=1 success
4 epochs=2
  success=True | attempts this call={'s01': 4, 's02': 4, 's03': 4, 's04': 2, 's05': 2, 's06': 2}
    orders(n=3) mockllm/model epochs=2 success
    orders(n=3) mockllm/other epochs=2 success
    orders(n=6) mockllm/model epochs=2 success
    orders(n=6) mockllm/other epochs=2 success
5 eval-set.json keys: ['eval_set_id', 'tasks'] | tasks: 4 | task keys: ['model', 'model_args', 'name', 'sequence', 'task_args', 'task_file', 'task_id']

The attempt counts need one piece of context: the six-sample and three-sample tasks share the ids s01 to s03, and both write to the same attempts file. Then:

  1. First call. orders(n=6) failed on s03, the set retried it immediately, and the retry re-ran only s03 (three attempts for s03: the failure, the retry, and once in orders(n=3); one each for s04 to s06). success=True. The failed log was cleaned up, so the directory holds exactly one log per task, plus three bookkeeping files.
  2. Identical second call. No attempts at all: the set was complete, so the call was a no-op. This is the property that makes eval sets safe to put in a loop, a cron job or a CI retry: re-running the command is always correct.
  3. Adding a model ran both tasks for mockllm/other only (two attempts each for s01 to s03, one each for s04 to s06) and left the existing logs alone.
  4. Adding epochs (epochs=2) re-ran all four task × model pairs, but each pair reused its completed epoch 1 and ran only epoch 2: four attempts for s01 to s03 (two tasks × two models × one new epoch) and two for s04 to s06. Every log now says epochs=2.

So "amending" a set means re-issuing the command with a superset: more tasks, more models, more epochs. The next section shows what happens when the command changes in other ways.

11.3 The bookkeeping files#

Line 5 of the output lists what the set writes besides logs:

File Contents Use
eval-set.json The set's eval_set_id and one entry per task × model: name, task_id, task_file, task_args, model, model_args, sequence The manifest: what the set is supposed to contain. The CI gate checks completeness against it
logs.json An index of the log headers Fast listing for Inspect View and tools
.eval-set-id The set's id Ties the directory to the set

11.4 Task identity and dirty directories#

An eval set pairs work with logs by task identity: the @task name and its arguments, the model, the model's generation config and model args (not base_url or credentials). Anything else in the directory is a foreign log, and the set refuses to run beside it:

python
# r08b_identity.py: what counts as "the same task" in an eval set, and dirty directories (lesson 10B.12)
import shutil

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

from orders_task import FLAG, orders

DIR = "logs-r08b"
shutil.rmtree(DIR, ignore_errors=True)
FLAG.unlink(missing_ok=True)


def call(label: str, tasks, **kwargs) -> None:
    try:
        ok, logs = eval_set(tasks, log_dir=DIR, model="mockllm/model", display="none", **kwargs)
        print(f"{label:40} success={ok} | logs in dir={len(list_eval_logs(DIR))}")
    except Exception as ex:
        msg = str(ex).replace("[bold]", "").replace("[/bold]", "")
        print(f"{label:40} {type(ex).__name__}: {msg[:400] if label.startswith('2') else msg[:90]}")


call("1 orders(n=6)", [orders(n=6)])
call("2 same, max_tokens=100", [orders(n=6)], max_tokens=100)
call("3 back to the original call", [orders(n=6)])
call("4 orders(n=4) instead", [orders(n=4)])
# a log from an unrelated eval() lands in the same directory
eval(orders(n=2), model="mockllm/model", log_dir=DIR, display="none")
call("5 after a stray eval() log", [orders(n=6)])
call("6 same, log_dir_allow_dirty=True", [orders(n=6)], log_dir_allow_dirty=True)
bash
uv run python r08b_identity.py
Output · real; long lines trimmed after the first6 lines
1 orders(n=6)                            success=True | logs in dir=1
2 same, max_tokens=100                   PrerequisiteError: ERROR: Existing log file '2026-11-24T18-00-06-00-00_orders_n29G6dVJ82HbDNcfgdmVex.eval' in log_dir is not associated with a task passed to eval_set (you must run eval_set in a fresh log directory). You can use the `--log-dir-allow-dirty` option to allow logs from other eval sets to be present in the log directory.
3 back to the original call              success=True | logs in dir=1
4 orders(n=4) instead                    PrerequisiteError: ERROR: Existing log file '2026-11-24T18-00-06-00-00_orders_n29G6dVJ82HbDNcfgdmVex.eval' in
5 after a stray eval() log               PrerequisiteError: ERROR: Existing log file '2026-11-24T18-00-06-00-00_orders_dEiEdVYszRj4rAY4imYViX.eval' in
6 same, log_dir_allow_dirty=True         success=True | logs in dir=2
  • Changing a generation setting (row 2) makes a different task identity, so the existing log "is not associated with a task passed to eval_set", and the set stops before running anything. The same happens for different task arguments (row 4) and for a log written by a plain eval() into the set's directory (row 5).
  • Going back to the original command (row 3) works: nothing in the directory was changed by the refused calls.
  • log_dir_allow_dirty=True (row 6) lets the set run beside foreign logs. Use it rarely; it mixes runs in one directory, which is exactly what the dedicated directory is meant to prevent.

What this means for you: an eval-set directory is the identity of an experiment. To compare a new setting, start a new directory (logs-2026-11-24-reasoning-high), never edit the command of an existing one. Dynamic tasks passed as objects must come from @task functions with plain-typed arguments (strings, numbers, lists), so their identity can be recorded and compared; a solver passed as an argument must come from a @solver function.

11.5 Exit codes: the one command whose exit code you can gate on#

inspect eval exits 0 even when the run failed (10B.8, 9.6). inspect eval-set does not:

bash
echo 99 > fail.flag     # s03 fails on every attempt
inspect eval-set orders_task.py --model mockllm/model --log-dir logs-r08c --retry-attempts 2 --display plain
echo "exit code: $?"
rm fail.flag            # the order service is back
inspect eval-set orders_task.py --model mockllm/model --log-dir logs-r08c --retry-attempts 2 --display plain
echo "exit code: $?"
inspect eval-set orders_task.py --model mockllm/model --log-dir logs-r08c --display plain
echo "exit code: $?"
Output · real; the traceback panel and progress display are trimmed23 lines
RuntimeError: order service timed out
Task interrupted (5 of 6 total samples logged before interruption). Resume task
with:

inspect eval-retry
logs-r08c/2026-11-24T18-00-16-00-00_orders_Zr7k4CmbkGTwoiEWwR9Dqh.eval
Log: logs-r08c/2026-11-24T18-00-16-00-00_orders_Zr7k4CmbkGTwoiEWwR9Dqh.eval
---------------------------------------------------------

Did not successfully complete all tasks in 'logs-r08c'.
exit code: 1
total time:                 0:00:00
mockllm/model               37 tokens [I: 4, O: 33]
includes
accuracy  1.000
stderr    0.000
Log: logs-r08c/2026-11-24T18-00-17-00-00_orders_Zr7k4CmbkGTwoiEWwR9Dqh.eval
---------------------------------------------------------

Completed all tasks in 'logs-r08c' successfully
exit code: 0
Completed all tasks in 'logs-r08c' successfully
exit code: 0

The first command tried three times (the attempt and two retries), gave up, printed "Did not successfully complete all tasks" and exited 1. The second, once the cause was gone, retried only the missing sample (the token line counts one reply) and exited 0. The third was a no-op and exited 0. So in CI, inspect eval-set is the right command: a non-zero exit code really means "the set is incomplete". It still does not mean "the numbers are good"; that is the gate's job (Part 13), and the gate should also check completeness itself rather than trust a step that a careless || true can neutralize.

11.6 Sample preservation needs stable ids#

Every reuse in this part (eval-set retries, eval_retry, epochs added later) matches completed samples to the new run by sample id (and epoch). With explicit ids, as every dataset in this course has, that is exact. With auto-assigned ids (1, 2, 3 in load order, 10B.9, 2.4), it is correct only if the order never changes: Inspect detects a dataset.shuffle() call, warns and refuses to reuse samples, but any other reordering (a file regenerated in a different order, a filter added) silently pairs the wrong samples. Give every sample an explicit, stable id before the first real run.

11.7 Suites: directories, attributes and filters#

An eval set takes files, directories and registered names, and a directory is scanned recursively for @task functions (skipping names starting with . or _, and folders called env, venv and tests; files without tasks are not executed). Attributes on the decorator mark tiers:

python
# suite/triage_tasks.py: tasks tagged by tier (lesson 10B.12)
from inspect_ai import Task, task, task_with

from triage import triage, triage_samples


@task(light=True)
def triage_smoke() -> Task:
    """Four tickets: the per-commit smoke tier."""
    return task_with(triage(), dataset=triage_samples()[:4], name="triage_smoke")


@task(nightly=True)
def triage_full() -> Task:
    return triage()

From Python, list_tasks() with a filter feeds eval_set() directly:

python
# run_light.py: the light tier from Python (lesson 10B.12)
from inspect_ai import eval_set, list_tasks

if __name__ == "__main__":
    light = list_tasks("suite", filter=lambda t: t.attribs.get("light") is True)
    print("light tier:", [f"{t.file}@{t.name}" for t in light])
    ok, logs = eval_set(light, log_dir="logs-smoke", model="mockllm/model", display="none")
    print("success:", ok, "|", [(log.eval.task, log.results.total_samples) for log in logs])

From the command line, inspect list tasks -F prints file@task lines that xargs passes on:

bash
inspect list tasks suite
inspect list tasks suite -F light=true
uv run python run_light.py
Output · real8 lines
$ inspect list tasks suite
suite/triage_tasks.py@triage_full
suite/triage_tasks.py@triage_smoke
$ inspect list tasks suite -F light=true
suite/triage_tasks.py@triage_smoke
$ python run_light.py
light tier: ['suite/triage_tasks.py@triage_smoke']
success: True | [('triage_smoke', 4)]
bash
inspect list tasks suite -F light=true | xargs inspect eval-set --log-dir logs-smoke2 --model mockllm/model --display plain
export PYTHONPATH=$PWD     # make triage.py, one folder up, importable from suite/
inspect list tasks suite -F light=true | xargs inspect eval-set --log-dir logs-smoke2 --model mockllm/model --display plain
Output · real; the traceback and the progress display are trimmed16 lines
$ inspect list tasks suite -F light=true | xargs inspect eval-set --log-dir logs-smoke2 --model mockllm/model --display plain
ModuleNotFoundError: No module named 'triage'
$ export PYTHONPATH=$PWD   # make triage.py importable from suite/
$ (same command)
max_tasks: 10, dataset: (samples)

total time:              0:00:00
mockllm/model            1,274 tokens [I: 1,142, O: 132]
triage_format         triage_labels
accuracy       0.000  mean           0.000
stderr         0.000  stderr         0.000
Log:
logs-smoke2/2026-11-24T18-12-43-00-00_triage-smoke_Z5quVhQRXDtspXM7qe2J6W.eval
---------------------------------------------------------

Completed all tasks in 'logs-smoke2' successfully

The first CLI attempt failed with ModuleNotFoundError: No module named 'triage', although the Python run worked. The inspect command loads each task file from its own folder, so a task in suite/ cannot import a helper module that lives one level up; the Python script worked because its own folder (which holds triage.py) was on the import path. Fix it by making shared code importable (an installed package is best, 10B.9, 8.8; PYTHONPATH works for a repository layout), not by copying helpers into every folder. (The 0.000 scores are the default mock's null run: the plumbing works.)

list_tasks() and inspect list tasks parse task files rather than run them, so an attribute used for filtering must be a literal constant (light=True, not light=is_light("triage")). Tiers map directly onto 10A.8, 3.1: a light tier per commit, a nightly tier on real models, a release tier with more samples and epochs.

11.8 Publishing a set#

--bundle-dir site/ (with --bundle-overwrite) writes a static Inspect View site for the whole set when it finishes, the eval-set equivalent of inspect view bundle (10B.8, 6.4); upload it as a CI artefact or to a static host your team can reach. The same caution applies: the logs carry prompts, answers and your git remote.

11.9 Beyond eval sets: Inspect Flow#

For sweeps across many tasks, models and parameters, with a store of logs that is reused across directories and runs, Meridian Labs publishes Inspect Flow, a companion package built on eval sets (declarative specs, matrix sweeps, inherited defaults, post-run steps to validate and promote logs). It is a separate package with its own release cadence; this lesson does not cover it. For a product team, eval sets plus a small script (like 10B.9, 8.10's grid) are usually enough.


Part 12: Early stopping, and what it needs#

Deep-dive

12.1 The idea#

Running every sample for every epoch is wasteful when the answer is already clear: a sample answered correctly in its first two epochs out of five will very likely stay correct. Early stopping lets a component you write skip sample-epochs based on results so far. Task(early_stopping=...) takes an object implementing the EarlyStopping protocol from inspect_ai.util:

Method Called Returns
start_task(task, samples, epochs) Once, at the start The manager's name, for the log
schedule_sample(id, epoch) Before each sample-epoch is scheduled EarlyStop(id, epoch, reason, metadata) to skip it, or None to run it
complete_sample(id, epoch, scores) When a sample-epoch finishes, with its scores Nothing
complete_task() At the end Metadata recorded in the log

The summary lands in log.results.early_stopping (the manager's name, every EarlyStop, the metadata). For serious adaptive testing, the UK AISI's Optstop package implements optimal-stopping algorithms on this protocol.

12.2 A manager, and the concurrency catch#

A simple manager: skip a sample's remaining epochs once its first two epochs scored the same.

python
# r10_early_stopping.py: skip the remaining epochs of a sample once it has answered consistently (lesson 10B.12)
from collections import defaultdict

from pydantic import JsonValue

from inspect_ai import Epochs, eval, task_with
from inspect_ai.dataset import Sample
from inspect_ai.log import EvalSpec
from inspect_ai.scorer import SampleScore
from inspect_ai.util import EarlyStop, EarlyStopping

from fake_triage import scripted_model
from triage import triage


class StopWhenConsistent(EarlyStopping):
    """After `k` finished epochs with identical scores, skip the sample's later epochs."""

    def __init__(self, k: int = 2) -> None:
        self.k = k
        self.seen: dict[str | int, list[tuple]] = defaultdict(list)
        self.skipped = 0

    async def start_task(self, task: EvalSpec, samples: list[Sample], epochs: int) -> str:
        return f"stop_when_consistent(k={self.k})"

    async def schedule_sample(self, id: str | int, epoch: int) -> EarlyStop | None:
        history = self.seen[id]
        if len(history) >= self.k and len(set(history[: self.k])) == 1:
            self.skipped += 1
            return EarlyStop(id=id, epoch=epoch, reason=f"first {self.k} epochs agreed")
        return None

    async def complete_sample(self, id: str | int, epoch: int,
                              scores: dict[str, SampleScore]) -> None:
        self.seen[id].append(tuple(sorted((k, str(v.score.value)) for k, v in scores.items())))

    async def complete_task(self) -> dict[str, JsonValue]:
        return {"skipped": self.skipped}


for max_samples in (None, 1):
    stopper = StopWhenConsistent(k=2)
    task = task_with(triage(), epochs=Epochs(5), early_stopping=stopper)
    log = eval(task, model=scripted_model(), max_samples=max_samples, log_dir="logs-r10", display="none")[0]
    es = log.results.early_stopping
    print(f"max_samples={max_samples}: sample-epochs run={len(log.samples)} of 60 | "
          f"early stops={len(es.early_stops)} | manager={es.manager} | metadata={es.metadata} | "
          f"triage_format accuracy={log.results.scores[0].metrics['accuracy'].value:.3f}")
bash
uv run python r10_early_stopping.py
Output · real2 lines
max_samples=None: sample-epochs run=60 of 60 | early stops=0 | manager=stop_when_consistent(k=2) | metadata={'skipped': 0} | triage_format accuracy=0.917
max_samples=1: sample-epochs run=24 of 60 | early stops=36 | manager=stop_when_consistent(k=2) | metadata={'skipped': 36} | triage_format accuracy=0.917

With default concurrency, the manager skipped nothing: all 60 sample-epochs (12 tickets × 5 epochs) ran. The reason is the same as the cache race of 6.4: every sample-epoch was scheduled before any had completed, so schedule_sample() was always asked before there was any evidence. With max_samples=1, samples run one at a time, the first two epochs of each sample finished before the third was scheduled, and 36 of 60 sample-epochs were skipped, for the same headline accuracy (this mock is deterministic, so every pair of epochs agreed).

What this means for you:

  • Early stopping needs scheduling that lets evidence arrive. With a real provider and long requests, some evidence arrives during the run, but how much depends on timing, so the savings (and which samples were skipped) vary from run to run. Lower max_samples to make it effective, at a cost in wall time; a manager can also make its own decisions conservative when it has no data yet.
  • It changes the estimator. Skipped epochs are not scored, so a sample's reduced score comes from fewer epochs, and samples are no longer measured equally. For mean over epochs that is mostly harmless when skipped samples are the stable ones; for pass_at_k or pass_k_k reducers (10B.10, 7.5), it changes the meaning of k. Record the manager and its stops (the log does), and never compare an early-stopped run with a full one without saying so.
  • "Stop when the result is significant" is optional stopping. Stopping the whole evaluation as soon as a comparison crosses a significance threshold inflates false positives, the sequential-testing problem of 10A.8, 2.6. Use a method designed for sequential decisions (which is what Optstop is for), or fix the sample size in advance.

12.3 Per-sample limits and cost limits#

Long runs also need ceilings on individual samples: message_limit, token_limit (which also accepts strings such as "500k"), turn_limit, time_limit, working_limit and cost_limit on the Task, eval() or the CLI. A sample that hits one stops, is scored on its state, and records which limit it hit (sample.limit). They matter most for agents and are 10B.15's subject. One running note: cost_limit, cost accounting in the log, and --model-cost-config all need prices for the model, which Inspect looks up in its model database; prices for a model it does not know cannot be set:

python
# r14_cost.py: model prices must match a model Inspect knows (lesson 10B.12)
from inspect_ai import eval
from inspect_ai.model import ModelCost

from fake_triage import scripted_model
from triage import triage

PRICES = {"mockllm/model": ModelCost(input=1.0, output=4.0, input_cache_write=1.25, input_cache_read=0.1)}
try:
    eval(triage(), model=scripted_model(), model_cost_config=PRICES, log_dir="logs-r14", display="none")
except ValueError as ex:
    print("model_cost_config for the mock ->", type(ex).__name__ + ":", ex)
Output · real1 line
model_cost_config for the mock -> ValueError: Model 'mockllm/model' not found.

For a hosted model, put its prices (per million tokens: input, output, input_cache_write, input_cache_read) in a YAML or JSON file and pass --model-cost-config prices.yaml, or call set_model_cost("openai/gpt-6-luna", ModelCost(...)) before the run; then the log's model usage carries total_cost and cost_limit can stop runaway samples. Keep the price file under version control and dated, like 03.7, Part 4's price table, because provider prices change. Without prices, Inspect reports tokens, not money.


Part 13: A CI gate that cannot go green on a broken eval#

Deep-dive

13.1 What the gate must check#

10B.8, 9.6 showed the problem (inspect eval exits 0 on a failed run) and a minimal gate over one log: status, coverage, one metric. 10B.10, 8.8 set the rules for gating on Inspect numbers: fail on failed runs, hard floors for must-pass checks, non-regression judged on a paired interval, reliability floors with reducers, and a record of what was gated. Running for real adds three more things to check: that the eval set is complete (every task × model it was meant to run has a successful log), that errors, retries and refusals were not hidden by the error policy, and that the baseline is comparable (same task version). The production gate below checks all of them over an eval-set directory, and uses evalkit's 10A.8 gate for the statistics instead of re-implementing them.

13.2 ci_gate.py#

python
# ci_gate.py: the release gate over an Inspect eval-set directory (lesson 10B.12)
"""Usage: python ci_gate.py LOG_DIR GATE_SPEC.json [--baseline BASELINE_LOG_DIR]

Exit code 0 only when ALL of these hold:
  1. completeness: every task in LOG_DIR/eval-set.json has a log with status "success"
  2. coverage:     every gated scorer scored every sample (errors, refusals and
                   unscored samples are counted and reported, never silently dropped)
  3. comparability: task version matches the baseline's (same task, arguments and model)
  4. quality:      each gated metric passes evalkit's 10A.8 gate: a hard floor, and a
                   paired non-regression check against the baseline (bootstrap CI)
Warnings (retried samples, CI dipping below a floor) are printed but do not fail.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from inspect_ai.log import EvalLog, list_eval_logs, read_eval_log

from evalkit.compare import GateThresholds, evaluate_gate, paired_diffs, summarise_metric


def newest_logs(log_dir: str) -> dict[str, EvalLog]:
    """The newest full log per task identity. list_eval_logs() returns newest first.

    Keyed by eval.task_id, not by task name: an eval set may hold several tasks with the
    same name (different arguments, models or generation settings).
    """
    out: dict[str, EvalLog] = {}
    for info in list_eval_logs(log_dir):
        header = read_eval_log(info, header_only=True)
        if header.eval.task_id not in out:
            out[header.eval.task_id] = read_eval_log(info)
    return out


def identity(log: EvalLog) -> tuple[str, str, str]:
    """What makes two logs the same measurement across directories: task, arguments, model."""
    return (log.eval.task, json.dumps(log.eval.task_args, sort_keys=True), log.eval.model)


def label(log: EvalLog) -> str:
    args = ", ".join(f"{k}={v}" for k, v in sorted(log.eval.task_args.items()))
    return f"{log.eval.task}({args}) @ {log.eval.model}" if args else f"{log.eval.task} @ {log.eval.model}"


def per_sample(log: EvalLog, scorer: str) -> dict[str, float]:
    """The reduced value each sample contributed to the scorer's metric, keyed by sample id."""
    reduction = next((r for r in (log.reductions or []) if r.scorer == scorer), None)
    if reduction is None:
        return {}
    return {str(s.sample_id): float(s.value) for s in reduction.samples}


def gate(log_dir: str, spec: dict, baseline_dir: str | None) -> int:
    failures: list[str] = []
    warnings: list[str] = []

    # 1. Completeness: the eval set's own record of what should exist
    manifest = Path(log_dir, "eval-set.json")
    logs = newest_logs(log_dir)
    if manifest.exists():
        expected = json.loads(manifest.read_text())["tasks"]
        done = {tid for tid, log in logs.items() if log.status == "success"}
        missing = [t["name"] for t in expected if t["task_id"] not in done]
        if missing:
            failures.append(f"eval set incomplete: no successful log for {missing}")
    else:
        warnings.append("no eval-set.json: completeness not checked")
    if not logs:
        failures.append(f"no logs in {log_dir}")

    baseline = {identity(b): b for b in newest_logs(baseline_dir).values()} if baseline_dir else {}

    for log in sorted(logs.values(), key=label):
        tag = label(log)
        if log.status != "success":
            failures.append(f"{tag}: status={log.status} ({log.error.message if log.error else ''})")
            continue

        # 2. Coverage, errors, retries, refusals
        samples = log.samples or []
        errors = [s.id for s in samples if s.error]
        retried = [s.id for s in samples if s.error_retries]
        refused = [s.id for s in samples
                   if s.output.choices and s.output.choices[0].stop_reason == "content_filter"]
        total = log.results.total_samples
        if errors:
            failures.append(f"{tag}: {len(errors)} errored sample(s) {errors}")
        if retried:
            warnings.append(f"{tag}: {len(retried)} sample(s) passed only after a retry {retried}: "
                            "compare them with the rest before trusting the number")
        if refused:
            warnings.append(f"{tag}: {len(refused)} refusal(s) {refused}")
        if total < spec.get("min_samples", 1):
            failures.append(f"{tag}: only {total} samples (spec requires {spec['min_samples']})")

        # 3. Comparability with the baseline
        base = baseline.get(identity(log))
        if base is None and baseline:
            warnings.append(f"{tag}: no baseline log for this task, arguments and model: "
                            "paired comparison skipped, floors still apply")
        if base is not None and base.eval.task_version != log.eval.task_version:
            failures.append(f"{tag}: task version {log.eval.task_version} != baseline "
                            f"{base.eval.task_version}; refusing to compare")
            base = None

        # 4. Quality, metric by metric, with evalkit's gate
        for scorer, rule in spec["metrics"].items():
            result = next((s for s in log.results.scores if s.name == scorer), None)
            if result is None:
                failures.append(f"{tag}: scorer {scorer} missing")
                continue
            if result.scored_samples != total:
                failures.append(f"{tag}: {scorer} scored {result.scored_samples} of {total}")
            values = per_sample(log, scorer)
            summary = summarise_metric(list(values.values()))
            diffs, base_mean = None, None
            if base is not None and rule.get("max_drop") is not None:
                base_values = per_sample(base, scorer)
                diffs = paired_diffs(base_values, values)          # current - baseline, same ids
                base_mean = sum(base_values.values()) / len(base_values)
            verdict = evaluate_gate(summary, diffs, GateThresholds(
                min_overall=rule.get("min_overall"), max_drop=rule.get("max_drop"),
                min_cases=spec.get("min_samples", 1)), baseline_mean=base_mean)
            if rule.get("max_overall") is not None and summary.mean > rule["max_overall"]:
                failures.append(f"{tag}: {scorer}: mean {summary.mean:.3f} > ceiling "
                                f"{rule['max_overall']} (a null run must not score)")
            failures += [f"{tag}: {scorer}: {f}" for f in verdict.failures]
            warnings += [f"{tag}: {scorer}: {w}" for w in verdict.warnings]
            vs = f" vs baseline {base_mean:.3f}" if base_mean is not None else ""
            print(f"  {tag}: {scorer} = {summary.mean:.3f} "
                  f"[{summary.ci_lo:.3f}, {summary.ci_hi:.3f}] over {summary.n}{vs}")

    for w in warnings:
        print("WARN:", w)
    for f in failures:
        print("FAIL:", f)
    print("GATE:", "FAIL" if failures else "PASS")
    return 1 if failures else 0


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("log_dir")
    parser.add_argument("spec")
    parser.add_argument("--baseline")
    args = parser.parse_args()
    sys.exit(gate(args.log_dir, json.loads(Path(args.spec).read_text()), args.baseline))

The rules live in a reviewed file next to the task, not in the CI script:

json
{
  "min_samples": 12,
  "metrics": {
    "triage_format": {"min_overall": 0.9},
    "triage_labels": {"min_overall": 0.85, "max_drop": 0.05}
  }
}

Design decisions worth copying:

  • Completeness comes from the set's own manifest (eval-set.json), not from the exit code of a previous step. A gate that trusts "the eval step passed" is one continue-on-error: true away from gating on nothing.
  • Values come from log.reductions, the exact per-sample numbers the metric used, keyed by sample id, so the paired comparison with the baseline joins on ids (10B.10, 8.3), never on position.
  • Failures and warnings are different. An errored sample fails the gate; a retried or refused sample is a warning that a person reads, because it may be legitimate. evalkit.compare.evaluate_gate() makes the same split for statistics: a confident regression fails, an interval that straddles the tolerance warns (10A.8, 2.5).
  • Logs are keyed by task identity (eval.task_id), not by task name. An eval set may hold several tasks with the same name: orders(n=6) and orders(n=3) from 11.2, or one task under two generation settings (11.4). Keyed by name, the gate kept one log per name and reported a complete set as "incomplete" (the first version of this script did exactly that on the orders set). The baseline is matched on task, arguments and model, never on name alone; a candidate with no matching baseline log gets a warning and floors only, not a silent comparison with another model's numbers.
  • A max_overall ceiling exists for the null run. A metric rule may carry "max_overall": the smoke job's null run (the default mock reply) must score at or below it, normally 0, so a task that passes garbage cannot go green.
  • Task versions must match before any comparison (10B.9, 8.7): a gate that compares a v2 dataset with a v1 baseline compares two different measurements.

13.3 Four candidates, judged#

The script below produces a baseline and four candidate eval sets: the same system again, a regressed one (a worse prompt that gets four priorities wrong), one whose upstream fails on one ticket with errors tolerated, and one that fails on that ticket with the default policy:

python
# r11_ci_runs.py: four candidate eval sets for the CI gate to judge (lesson 10B.12)
import json
import shutil

from inspect_ai import eval_set
from inspect_ai.model import ModelOutput, get_model

from fake_triage import RESPONSES, fake_triage, scripted_model
from triage import TICKETS, triage

for d in ("ci-baseline", "ci-same", "ci-regressed", "ci-errors", "ci-incomplete"):
    shutil.rmtree(d, ignore_errors=True)

# Answers a worse prompt might produce: four tickets get the wrong priority.
WORSE = {"T01": "P3", "T05": "P3", "T06": "P3", "T12": "P2"}


def regressed(input, tools, tool_choice, config) -> ModelOutput:
    out = fake_triage(input, tools, tool_choice, config)
    for tid, text, _ref, _meta in TICKETS:
        if text and text in input[-1].text and tid in WORSE:
            answer = json.loads(RESPONSES[tid])
            answer["priority"] = WORSE[tid]
            return ModelOutput.from_content(model="mockllm", content=json.dumps(answer))
    return out


def broken(input, tools, tool_choice, config) -> ModelOutput:
    if "Thanks for the quick fix" in input[-1].text:           # T07
        raise RuntimeError("upstream returned malformed JSON")
    return fake_triage(input, tools, tool_choice, config)


def mock(fn):
    return get_model("mockllm/model", custom_outputs=fn, memoize=False)


runs = {
    "ci-baseline": dict(model=scripted_model()),
    "ci-same": dict(model=scripted_model()),
    "ci-regressed": dict(model=mock(regressed)),
    "ci-errors": dict(model=mock(broken), fail_on_error=False),
    "ci-incomplete": dict(model=mock(broken), retry_attempts=1),
}
for log_dir, kwargs in runs.items():
    ok, _ = eval_set([triage()], log_dir=log_dir, display="none", **kwargs)
    print(f"{log_dir:14} eval_set success={ok}")
bash
uv run python r11_ci_runs.py
Output · real5 lines
ci-baseline    eval_set success=True
ci-same        eval_set success=True
ci-regressed   eval_set success=True
ci-errors      eval_set success=True
ci-incomplete  eval_set success=False

Note that eval_set() reported success for ci-errors: with fail_on_error=False the errored sample is tolerated, the log's status is success, and so is the set. Now the gate, against the baseline:

bash
for d in ci-same ci-regressed ci-errors ci-incomplete; do
  uv run python ci_gate.py $d gate_spec.json --baseline ci-baseline; echo "exit code: $?"
done
Output · real32 lines
$ python ci_gate.py ci-same gate_spec.json --baseline ci-baseline
  triage @ mockllm/model: triage_format = 0.917 [0.750, 1.000] over 12
  triage @ mockllm/model: triage_labels = 0.889 [0.722, 1.000] over 12 vs baseline 0.889
WARN: triage @ mockllm/model: triage_format: mean 0.917 passes floor 0.900 but CI [0.750, 1.000] dips below it
WARN: triage @ mockllm/model: triage_labels: mean 0.889 passes floor 0.850 but CI [0.722, 1.000] dips below it
GATE: PASS
exit code: 0
$ python ci_gate.py ci-regressed gate_spec.json --baseline ci-baseline
  triage @ mockllm/model: triage_format = 0.917 [0.750, 1.000] over 12
  triage @ mockllm/model: triage_labels = 0.778 [0.639, 0.917] over 12 vs baseline 0.889
WARN: triage @ mockllm/model: triage_format: mean 0.917 passes floor 0.900 but CI [0.750, 1.000] dips below it
WARN: triage @ mockllm/model: triage_labels: possible drop 0.111 near tolerance 0.044; CI [-0.194, -0.028] too wide to be sure — investigate
FAIL: triage @ mockllm/model: triage_labels: mean 0.778 < floor 0.850
GATE: FAIL
exit code: 1
$ python ci_gate.py ci-errors gate_spec.json --baseline ci-baseline
  triage @ mockllm/model: triage_format = 0.909 [0.727, 1.000] over 11
  triage @ mockllm/model: triage_labels = 0.879 [0.697, 1.000] over 11 vs baseline 0.889
WARN: triage @ mockllm/model: triage_format: mean 0.909 passes floor 0.900 but CI [0.727, 1.000] dips below it
WARN: triage @ mockllm/model: triage_labels: mean 0.879 passes floor 0.850 but CI [0.697, 1.000] dips below it
FAIL: triage @ mockllm/model: 1 errored sample(s) ['T07']
FAIL: triage @ mockllm/model: triage_format scored 11 of 12
FAIL: triage @ mockllm/model: triage_format: only 11 cases scored; gate requires >= 12
FAIL: triage @ mockllm/model: triage_labels scored 11 of 12
FAIL: triage @ mockllm/model: triage_labels: only 11 cases scored; gate requires >= 12
GATE: FAIL
exit code: 1
$ python ci_gate.py ci-incomplete gate_spec.json --baseline ci-baseline
FAIL: eval set incomplete: no successful log for ['triage']
FAIL: triage @ mockllm/model: status=error (RuntimeError('upstream returned malformed JSON'))
GATE: FAIL
exit code: 1
  • ci-same passes, with warnings: both point estimates clear their floors, but on twelve tickets the bootstrap intervals dip below them. That is the honest state of a 12-sample suite, and the warnings say so instead of hiding it (10B.10, 8.7 on how many samples a floor needs).
  • ci-regressed fails, on the floor: triage_labels fell from 0.889 to 0.778. The paired non-regression check, on its own, only warned: the drop of 0.111 is larger than the 0.044 tolerance (5% of 0.889), but with 12 pairs the interval's upper end (−0.028) does not exclude the tolerance. That is evaluate_gate() refusing to call a confident regression from twelve tickets; the floor caught it instead. With a few hundred tickets the paired check would be decisive.
  • ci-errors fails on coverage although its metrics look fine (0.909 and 0.879 over 11) and eval_set() said success: T07 errored, so each scorer scored 11 of 12, below the minimum of 12. This is the 1.000-over-8 trap of 8.2 caught in CI.
  • ci-incomplete fails on completeness and status, with the cause from the log.

Two more cases, each run for real. First, a set that holds two tasks with the same name (orders(n=6) and orders(n=3), from orders_task.py) must pass when both succeeded. Second, the null run: the default mock reply, gated with a spec whose rules are "max_overall": 0.0.

python
# r11b_two_orders.py: an eval set with two tasks that share a name (lesson 10B.12)
import shutil

from inspect_ai import eval_set

from orders_task import FLAG, orders

FLAG.unlink(missing_ok=True)
shutil.rmtree("ci-two-orders", ignore_errors=True)
ok, _ = eval_set([orders(n=6), orders(n=3)], log_dir="ci-two-orders", display="none",
                 model="mockllm/model")
print(f"ci-two-orders  eval_set success={ok}")
python
# r11c_null_run.py: the null run: the default mock reply must score zero (lesson 10B.12)
import shutil

from inspect_ai import eval_set

from triage import triage

shutil.rmtree("ci-null", ignore_errors=True)
ok, _ = eval_set([triage()], log_dir="ci-null", display="none", model="mockllm/model")
print(f"ci-null        eval_set success={ok}")
json
{"min_samples": 3, "metrics": {"includes": {"min_overall": 0.9}}}

(That is gate_spec_orders.json; gate_spec_null.json is the triage spec with "max_overall": 0.0 on both scorers and min_samples 12.)

bash
uv run python r11b_two_orders.py
uv run python ci_gate.py ci-two-orders gate_spec_orders.json; echo "exit code: $?"
uv run python r11c_null_run.py
uv run python ci_gate.py ci-null gate_spec_null.json; echo "exit code: $?"
Output · real10 lines
ci-two-orders  eval_set success=True
  orders(n=3) @ mockllm/model: includes = 1.000 [1.000, 1.000] over 3
  orders(n=6) @ mockllm/model: includes = 1.000 [1.000, 1.000] over 6
GATE: PASS
exit code: 0
ci-null        eval_set success=True
  triage @ mockllm/model: triage_format = 0.000 [0.000, 0.000] over 12
  triage @ mockllm/model: triage_labels = 0.000 [0.000, 0.000] over 12
GATE: PASS
exit code: 0

The first version of the gate keyed its logs on (task, model) and failed the two-orders set with FAIL: eval set incomplete: no successful log for ['orders'], because the second orders log overwrote the first in its dictionary. Keying on eval.task_id fixed it.

13.4 The workflow#

Two jobs: a keyless smoke run on every pull request (the plumbing, with the scripted mock and the null run), and a real-model gate on a schedule and on release branches. Illustrative (needs your repository layout and secrets):

yaml
# .github/workflows/evals.yml (lesson 10B.12). Illustrative.
name: evals
on:
  pull_request:
  schedule:
    - cron: "0 2 * * *"          # nightly, 02:00 UTC
  workflow_dispatch:

jobs:
  smoke:                          # keyless: the task loads, renders, scores; the gate logic works
    runs-on: ubuntu-latest
    timeout-minutes: 15
    env:
      INSPECT_DISABLE_MODEL_API: "1"   # any non-mock model call raises: a PR job can never reach a hosted API
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv sync
      - name: Null run (default mock reply)
        run: uv run inspect eval-set evals/triage.py --model mockllm/model --log-dir logs-null --display plain
      - name: Null run must score zero
        run: uv run python evals/ci_gate.py logs-null evals/gate_spec_null.json   # "max_overall": 0.0
      - name: Scripted run and gate
        run: |
          uv run python evals/run_scripted.py --log-dir logs-smoke
          uv run python evals/ci_gate.py logs-smoke evals/gate_spec.json

  nightly:
    if: github.event_name != 'pull_request'
    runs-on: ubuntu-latest
    timeout-minutes: 120
    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      INSPECT_LOG_DIR: logs-nightly
      INSPECT_EVAL_MAX_RETRIES: "5"          # CLI-only variables: they configure `inspect`, not eval()
      INSPECT_EVAL_TIMEOUT: "300"
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv sync
      - name: Baseline from the last release
        run: gh release download eval-baseline --pattern 'baseline.tar.gz' && mkdir baseline && tar xzf baseline.tar.gz -C baseline
        env:
          GH_TOKEN: ${{ github.token }}
      - name: Eval set (exit code 1 if incomplete after retries)
        run: >
          uv run inspect eval-set evals/
          --model openai/gpt-6-luna
          --model-role grader=anthropic/claude-haiku-5-5
          --retry-attempts 3 --adaptive-connections 5-10-40
          --tags nightly --metadata commit=${{ github.sha }}
          --bundle-dir site --display plain
      - name: Gate
        if: always()                         # gate even if the eval step failed, so the report says why
        run: uv run python evals/ci_gate.py logs-nightly evals/gate_spec.json --baseline baseline
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: eval-logs
          path: |
            logs-nightly
            site

Example output (illustrative — your exact output will differ): on a pull request only the smoke job runs and ends with GATE: PASS from the scripted run; the nightly job uploads the logs and the bundle whether or not the gate passes.

evals/run_scripted.py is the r11_ci_runs.py pattern: it calls eval_set() with the scripted mock (scripted_model()) into the --log-dir it is given. INSPECT_DISABLE_MODEL_API (0.3.292, verify_model_apis in the model layer) makes every model call except mockllm raise, which is exactly what a keyless job wants.

Points that matter more than the YAML syntax:

  • The gate runs even when the eval step fails (if: always()), and fails on its own if the set is incomplete. Never gate on the exit code alone, and never let a failed eval step skip the gate silently.
  • Logs are artefacts. A gate failure must be debuggable from the logs and the bundle without re-running anything; 10B.13 shows how to read them.
  • The baseline is a pinned artefact, produced by the same task version and promoted deliberately (on release), not "whatever main produced yesterday" (10A.8, 1.2).
  • The grader is bound explicitly to a pinned model, so a model comparison never uses the model under test as its own judge.
  • INSPECT_EVAL_* variables configure the CLI only. If a step calls eval() from Python, pass the settings as arguments (10B.9, 8.5).
  • Secrets stay out of logs. Never enable --traceback-locals in CI; review what a bundle publishes.

13.5 Cost control in CI#

The levers below are specific to running evals. Budgets in general (what a feature may cost, per tenant or per run) belong to cost management: see 11B.1, Cost and Latency Optimization and, for what an eval run costs and how to budget it, 11B.8, Part 6.

Lever How Trade-off
Tiers Smoke tier per PR (scripted mock or 10 to 20 real samples), full suite nightly, release tier with epochs Small tiers catch breakage, not small regressions (10A.8, 3.1)
Cache on smoke runs INSPECT_CACHE_DIR on a CI cache keyed by model id and dataset hash Replays: count read events and never report them as fresh measurements (6.8)
Batch for big nightly suites --batch on supported providers Hours of latency; single-turn tasks only (Part 7)
Flex tier -M service_tier=flex (OpenAI) Slower, occasionally unavailable
Per-sample ceilings --token-limit, --cost-limit with model prices Truncated samples are scored on partial work (12.3)
A budget check in the gate Sum log.stats.model_usage[...].total_cost (with prices configured) and fail above a cap, as GateThresholds(max_cost_usd=...) does in evalkit Needs prices kept current

13.6 From evalkit's cli.py gate to this gate#

10A.8, 6.1 built python -m evalkit.cli gate over evalkit's own result store. ci_gate.py is the same gate over Inspect's logs: the run store is an eval-set directory, the per-case values are log.reductions, the run status and error counts come from the log instead of status_counts(), and the statistics are literally the same function, evaluate_gate(). If your team already gates with evalkit, porting the eval to Inspect changes where the numbers come from, not how the decision is made.


Part 14: Methodology: running for real, and defending the number#

14.1 The pre-flight ladder#

Never start a real run at full size. Climb a ladder in which each rung is cheap and catches a different class of failure:

flowchart TB
    A["1. Null run: --model mockllm/model (scores must be near zero)"] --> B["2. Scripted or oracle run: known answers give known scores"]
    B --> C["3. --limit 5 on the real model: read every transcript and warning"]
    C --> D["4. --limit 50: latency, stop reasons, retries, refusals, cost per sample"]
    D --> E["5. Full eval set in a fresh directory, settings frozen in a run config"]
    E --> F["6. Gate: completeness, coverage, errors, floors, paired comparison"]
Rung What it catches Inspect tools
1. Null run A task that passes garbage (empty targets, a scorer that always says C) --model mockllm/model (10B.8, 10.2)
2. Scripted run Scorer and reduction bugs, on answers whose scores you know A mockllm script or a callmodel provider (2.7)
3. Five real samples Wrong model string, missing SDK or key, dropped settings (warnings), prompts that render wrong, a provider that ignores your settings Read the transcripts in Inspect View; check model events' config (3.1)
4. Fifty real samples Timeouts too tight for slow samples, truncation (stop_reason="max_tokens"), refusals, rate-limit behaviour, cost per sample, so you can estimate the full run stats.model_usage, connection_limit_history, sample error_retries, stop reasons
5. Full run Everything at scale, recoverably eval_set() with its own directory, a committed --run-config
6. Gate A run that should not be quoted ci_gate.py (Part 13)

Rung 4 is the one teams skip and regret: it is where you learn the latency distribution (so you can set attempt_timeout safely, 5.2), the truncation rate (so you can size max_tokens), and the cost (so the full run has a budget).

14.2 The reproducibility record#

A number from a real run is reproducible only if someone can rebuild the run. The log records most of it (10B.13 lists the fields); the rest is your job:

What Recorded by Inspect? What to add
Task name, file, arguments, version Yes (eval.task_*) Bump version on every meaning change
Dataset name, location, sample ids, shuffle Yes A content hash in metadata (10B.9, 8.7)
Solver chain and scorer arguments Yes (plan, eval.scorers)
Model name, base URL, model args, roles Yes The snapshot id if the name is an alias (2.6); the route for OpenRouter or a gateway
Generation settings actually sent Yes, per model event Read them from there, not the header (3.1)
Error policy, limits, epochs, reducers Yes (eval.config)
Mid-run retunes Yes, per log (inspect ctl config, with who, when, old and new values) Check for them before quoting the run, mainly --time-limit and --token-limit, which change what samples can do
Errors, retries, refusals, cache reads Yes, per sample Report the counts with the metric
Git revision and dirty flag, Inspect version Yes (eval.revision, eval.packages) Your other package versions (the provider SDK version is not recorded)
The realized configuration as a file inspect log export-config (10B.9, 8.6) Commit it next to the published number
Prices used for cost Only if configured The dated price file

14.3 Defending the number: questions a reviewer will ask#

  1. Is the run complete? Every task × model has a successful log; the eval-set manifest says so.
  2. What is the denominator? Samples scored out of samples in the dataset, per scorer; errors, refusals, unscored and limit-stopped samples listed separately.
  3. Did recovery change what was measured? How many samples needed retry_on_error, and do they score like the rest (8.4)? Were any answers cache reads, and from which snapshot (6.7)? Was early stopping on (12.2)?
  4. Was the configuration what you think? The settings in the model events, the warnings about dropped settings, the model snapshot.
  5. Is a difference real? A paired comparison on the same sample ids and task version, with an interval (10B.10, 8.3), not two point estimates.
  6. Is the grader trustworthy? For model-graded scores, the grader was bound explicitly, pinned, and validated (10B.11, Part 10).
Symptom Cause Fix
A new key in .env has no effect An exported variable of the same name wins; .env never overrides unset it, or print os.environ in the run (2.8)
fail_on_error=5 failed a run with exactly 5 errors The threshold is "at least" in 0.3.292; the docs say "more than" Set N + 1 to tolerate N (8.2)
A perfect score that nobody believes Errors tolerated with fail_on_error=False left the denominator Report coverage; gate on scored = total (8.2)
A "successful" run with no results A scorer raised on every sample, and errors were tolerated Unit-test scorers; gate on results per scorer (8.7)
CI green, eval crashed inspect eval exits 0 on status error Use inspect eval-set and a gate that checks completeness (11.5, Part 13)
The retried log is nowhere to be found eval_retry() writes to ./logs unless given log_dir Pass log_dir / --log-dir (9.1)
RuntimeError: Already running asyncio in this thread on retry The task file runs an eval when imported Guard with if __name__ == "__main__": (9.2)
FileNotFoundError: Task 'x' not found on retry The task was built without @task Build tasks in @task functions (9.1)
ModuleNotFoundError from the CLI for a helper that imports fine in Python inspect loads task files from their own folder Make shared code an installed package or set PYTHONPATH (11.7)
"Existing log file ... is not associated with a task passed to eval_set" The set's command changed (a setting, an argument), or a foreign log is in the directory A new directory per experiment; amend only with supersets (11.4)
Retried samples score suspiciously well retry_on_error re-rolled input-correlated failures Compare retried and first-try samples; fix the bug (8.4)
A refused sample counted as wrong in one run and missing in another fail_on_refusal differs between runs Decide the policy and report the refusal count (8.6)
temperature=0 "had no effect" The model rejects sampling settings; Inspect dropped it with a warning Read the warnings; configure per provider (3.4)
The log header says max_tokens=400 but answers are short A Task, run or per-call setting overrode the model's own config Read the model event's config (3.1)
Empty or truncated answers from a reasoning model Reasoning used the max_tokens budget Count stop_reason="max_tokens"; raise the budget (3.4)
The run crawls with many HTTP retries Concurrency above the rate limit, or a static cap set too high Adaptive connections, or a lower ceiling (4.5)
A run hangs for half an hour on one sample Unlimited retries with 30-minute backoff against a dead endpoint, or no attempt_timeout Set timeout, attempt_timeout, stream_idle_timeout (5.2)
Hard samples fail with timeouts, easy ones pass attempt_timeout below the slowest healthy call Size timeouts from rung 4 of the ladder (14.1)
A run with max_retries=0 fails on one network blip No model-layer retries, so the blip became a sample error Keep model retries on (5.1)
The same eval returns last week's answers after a model update The cache key holds the alias, not the snapshot Dated model ids; inspect cache clear --model (6.7)
per_epoch=False made more calls than samples, and epochs agree perfectly Concurrent epochs race the cache; the rest are replays Do not use it for variance (6.4)
A re-run in a new process ignores the cache The model was built from a Python callable, so its cache is per instance Plain-JSON constructor arguments (6.5)
Early stopping skipped nothing Every sample-epoch was scheduled before any finished Lower max_samples (12.2)
A crash lost more samples than expected Many samples in flight, large log buffer Moderate max_samples, smaller log_buffer; recover from the buffer (9.4)
A 24-hour wait for an agent eval Batch mode on a multi-turn task Batch only single-turn tasks (Part 7)
The grader graded its own model in a multi-model run An unset role falls back to the model being run Bind --model-role grader=... explicitly (2.3)
model_cost_config raises Model '...' not found Prices can only be set for models Inspect knows Use a known model id; tokens only for custom models (12.3)

14.5 Decision table#

Decision Choose When
How to run inspect eval Development, one task, interactive
inspect eval-set / eval_set() Anything you will quote, anything in CI, anything that runs longer than a coffee
eval() in a script Keyless tests, sweeps you post-process, notebooks
Concurrency Defaults (adaptive) Your own key, a normal tier
A ceiling or a static cap Shared keys, small tiers, debugging
Retries Model retries (default unlimited) plus a timeout Always
retry_on_error=1..2 Known flaky infrastructure (sandboxes, tool backends), with the shift check
Eval-set task retries Long runs; outages and crashes
Error policy Fail fast (default) CI and release runs
Tolerate with a small proportion Long runs with rare infrastructure noise, reported
Tolerate everything / continue_on_fail Diagnosis only
Refusals Count as wrong (default) Refusing is a product failure
fail_on_refusal and report the count Refusals are an artefact of the eval
Cache On Development, scorer iteration, smoke tiers
Off Release numbers, variance measurements
Cost Batch Large single-turn nightly suites
Flex tier Large suites that can tolerate slower responses
Neither Agents, CI-path runs
Model A dated snapshot, a pinned route Always for anything you compare
Custom system openai-api/... It speaks the OpenAI protocol
@modelapi provider Anything else, including evalkit's call_model; package it for the CLI and eval_retry (10B.13, 10.3)

14.6 A checklist before you quote a number from a real run#

  1. The eval set is complete, and the gate passed (or its failures are explained).
  2. Coverage per scorer: scored out of total, with errors, refusals, unscored and limit-stopped samples listed.
  3. Retried samples counted and compared with first-try samples; cache reads counted and justified; early stopping disclosed.
  4. The model snapshot (and grader snapshot) pinned and written down; the generation settings read from the model events; dropped-setting warnings checked.
  5. The run configuration exported and committed (inspect log export-config), with the dataset hash and task version.
  6. Comparisons are paired, on the same task version and sample ids, with an interval.
  7. The cost and wall time of the run recorded, so the next run can be budgeted.

Part 15: evalkit ↔ Inspect for running#

Deep-dive

15.1 The mapping#

evalkit (10A.1, 10A.8) Inspect What differs
CallModel = Callable[[str], str], injected into run_eval A model string resolved at run time; get_model() in solvers and scorers The model is not wired into the task. Wrap an existing call_model as a provider with @modelapi (2.7); package it to use it from the CLI or eval_retry (10B.13, 10.3)
Provider adapters for call_model (10A.4, 5.3) Built-in providers for 20+ APIs, openai-api/... for compatible endpoints Inspect handles message shapes, settings and usage per provider
RunConfig(workers=4), a fixed thread pool Adaptive connections per model (start 20, 10 to 100), max_connections, max_samples, max_tasks Inspect's limit adapts to rate limits and is per model, not per run
_is_infra() classifying exceptions as infrastructure A provider's should_retry() returning RetryDecision.rate_limit() / transient() / no() Inspect retries infrastructure failures inside the model call, and uses the classification to steer concurrency
Row-level error capture in run_eval Sample errors, fail_on_error, retry_on_error, score_on_error Inspect's default is fail-fast; evalkit recorded and continued
status_counts() (10A.8) log.status, sample.error, sample.error_retries, results.completed_samples Three levels: run, sample, retry history
CallCache / cached_call record/replay (10A.8, 3.2) cache=True / CachePolicy (key includes epoch, config, tools; one-week expiry) Inspect's key is broader; per-epoch by default; per-instance for callable-built models
repeats=k with the run index in the cache key Epochs with per_epoch=True The same idea; per_epoch=False is the warm-cache trap
Budget(max_calls, max_cost_usd) cost_limit and token_limit per sample, cost from model prices Inspect's limits are per sample; a run-level budget is a gate check (13.5)
Re-running a suite after a failure eval_retry() and eval sets, reusing completed samples by id Inspect resumes; evalkit re-ran
A results directory per run An eval-set log directory with eval-set.json Identity rules: one directory per experiment
cli.py gate inspect eval-set (exit 1 if incomplete) plus ci_gate.py over the logs, with the same evaluate_gate() The decision logic is shared; the data source differs (13.6)

Part 16: Older code and tutorials#

Reference

Inspect's running options changed a lot during 2026. When you read older code, blog posts or the docs of an older release:

You may see What changed Use now
--max-connections 10 as the throughput setting Adaptive connections arrived in 0.3.217 and became the default in 0.3.221; the floor rose from 4 to 10 in 0.3.240 Defaults, or --adaptive-connections with bounds; --max-connections only for a hard cap
max_retries=1 "to retry once" Before 0.3.248 it counted total attempts, so 1 never retried max_retries=N is N retries now
eval_set(..., log_dir=...) as a required argument Optional since 0.3.262 (defaults to INSPECT_LOG_DIR or ./logs) Still pass it: one directory per set
Eval-set retries that wait 30, 60, 120 s between rounds retry_immediate=True is the default since 0.3.218; the waits apply only with --no-retry-immediate Defaults
Errors on refusals handled by custom scorers fail_on_refusal (0.3.264) --fail-on-refusal with an explicit policy
inspect ctl tasks, ctl limits Removed in favour of noun groups (inspect ctl task list, inspect ctl config) inspect ctl --help
cf/... model strings for Cloudflare Renamed to cloudflare/... in 0.3.248 cloudflare/...
Task(epochs_reducer=...), Task(plan=...), max_messages= Deprecated task arguments (10B.9, Part 12) Epochs(n, reducer), solver=, message_limit=
A custom provider whose should_retry() returns True Still accepted, but treated as a transient retry, so adaptive concurrency never backs off Return RetryDecision.rate_limit() for rate limits
Merging shard logs by hand inspect log merge-shards (0.3.291) and merge_eval_log_shards() The built-in merge

Common misconceptions#

Misconception Reality
"inspect eval failing makes the CI job fail." It exits 0 on a failed run. inspect eval-set exits 1 when tasks remain incomplete, and a gate must still read the logs (11.5)
"fail_on_error=False keeps the number honest, it just skips bad samples." Skipped samples leave the denominator; the remaining score can be perfect while 20% of inputs fail (8.2)
"Retrying failed samples is always safe." Sample retries re-roll input-correlated failures and can shift the distribution; check retried against first-try samples (8.4)
"The default concurrency is 10." Adaptive: start 20, up to 100, down to 10 on rate limits (4.2)
"Lowering max_samples speeds things up." It can only lower concurrency; it matters for recovery and for agents, not throughput (4.4)
"The log header tells me which settings were used." The header holds the model's own config or the run's; the per-call model event is what was sent (3.1)
"Temperature 0 makes the eval deterministic, and temperature randomizes fairly." Many models drop temperature; hosted models vary at 0; and temperature is not random assignment (3.4, 3.5)
"With cache=True, a re-run is a re-measurement." It is a replay, possibly of an older snapshot behind the same alias (6.7)
"per_epoch=False means one call per sample." Concurrent epochs race the cache; 20 calls for 12 samples in the run here (6.4)
"Batch mode halves the cost of any eval." It halves the price per token, and turns multi-turn and agent evals into multi-day runs (Part 7)
"eval_retry() overwrites the failed log." It writes a new log (same task id), to ./logs unless you pass log_dir (9.1)
"A crash loses everything since the last log write." The sample buffer keeps completed samples for three days; recovery and eval sets use it (9.4)
"I can change a setting and re-run the eval set in the same directory." Changed identities are refused as foreign logs; amend only with supersets, otherwise use a new directory (11.4)
"Early stopping saves calls automatically." Under default concurrency it may skip nothing (12.2)
"get_model() always returns a cached object for the same arguments." Except for mockllm, which is never memoized (2.4)

Key takeaways#

  • A real run differs from a demo in five ways: which model exactly, which settings reach it, throughput against rate limits, failure, and cost. The task does not change; the run does.
  • Failures are handled at three layers: model-call retries (invisible, harmless), sample retries (retry_on_error, can bias), and task retries (eval_retry, eval sets, reuse completed samples by id). The error threshold sits between them.
  • Pin dated model snapshots and routes; the log records the name you passed, and the cache keys on it.
  • Generation settings combine field by field: the model's own config, then the Task, then the run, then the call. Read what was sent from the model events.
  • Adaptive concurrency is the default (20 to 100, backing off to 10); use a ceiling or a static cap for shared keys and small tiers. Classify rate limits correctly in custom providers.
  • Set timeout and attempt_timeout above your slowest healthy call; unlimited retries with long backoff can hang a run.
  • The response cache keys on model name, constructor args, messages, epoch, config and tools. It is per instance for callable-built models, not a lock, and stale across alias upgrades. Cache development, not release numbers.
  • Batch mode fits single-turn, large, non-urgent suites only.
  • Tolerated errors and refusals leave the denominator; report coverage and choose the refusal policy on purpose.
  • eval_retry() needs @task, import-safe task files and an explicit log_dir; crash recovery uses the sample buffer.
  • Eval sets are the unit of a real run: one directory per experiment, automatic retries, no-op re-runs, superset amendments, and an exit code you can use.
  • Gate on the logs: completeness, coverage, errors, retries, refusals, task version, floors and paired non-regression; evalkit's evaluate_gate() does the statistics.

Terms introduced in this lesson#

Term Meaning
Model string provider/model-name, the identifier that selects an Inspect provider and the vendor's model
Model spec One model with its own settings on the command line (--model-spec '{model: ..., ...}')
Model args Provider constructor options that are not generation settings (-M key=value)
Model snapshot A dated, immutable model version, as opposed to an alias that moves
Custom provider (@modelapi) Your own ModelAPI subclass registered by name, so any system can be evaluated as name/model
RetryDecision What a provider's should_retry() returns: rate_limit, transient or no
Adaptive connections Inspect's default concurrency control: start 20, grow to a ceiling, back off on rate limits
Connection pool The set of in-flight requests one model (provider and connection key) may have
max_samples The number of samples a task runs at once
Sharding Splitting one task's samples across worker processes and merging their logs
Model-call retry A retry of one provider request inside the model layer, with backoff
Sample error An exception that escapes a sample's solver or scorer; the sample is logged unscored
Error threshold (fail_on_error) How many sample errors (boolean, proportion or count) make the run fail
Sample retry (retry_on_error) Re-running an errored sample from scratch, in the same run
Distribution shift (from retries) Bias introduced when retried samples get more chances to succeed than others
Refusal A provider declining to answer, stop_reason="content_filter"
Response cache Inspect's local store of model responses keyed on the request
CachePolicy Expiry, per-epoch keying and extra scopes for the response cache
Batch mode Routing requests through a provider's batch API for lower prices and higher latency
eval_retry Finishing a failed task in a new log, reusing its completed samples
Sample preservation Reusing completed samples, matched by id and epoch, when a task is retried
Sample buffer Inspect's local database of samples not yet written to the log, used for crash recovery
Crash recovery Rebuilding a started log from its file and the sample buffer
Eval set A set of task × model runs that owns a log directory and retries until complete
Task identity What makes two runs "the same task" in an eval set: name, arguments, model, generation config, model args
Dirty log directory An eval-set directory containing logs that do not belong to the set
Early stopping Skipping sample-epochs based on results so far, via the EarlyStopping protocol
.env loading Inspect finds a .env by searching up from the working directory; it never overrides variables already in the environment
Pre-flight ladder Null run, scripted run, 5 samples, 50 samples, full set, gate

Exercises#

All exercises are keyless. Use the files from this lesson's samples.

  1. Precedence. Extend r02_config.py with a row that passes max_tokens through a --generate-config-style file (eval(..., **yaml.safe_load(...)) or the CLI with --generate-config) and a per-call generate(max_tokens=...). Predict the provider's value first, then run it.
  2. A rate-limited provider with a static cap. Run r04b_rate_limit.py with max_connections=40 (static). How many rate-limit errors occur, how long does it take, and why does the static cap behave worse than adaptive here?
  3. Thresholds. In r06_errors.py, make three samples fail persistently and find the smallest proportion and the smallest count for fail_on_error that still let the run succeed. What accuracy is reported, over how many samples?
  4. The shift check. Change r06_errors.py so that the samples that fail once are also the ones the mock answers wrongly, run with retry_on_error=1, and use retry_shift.py on the log. What does the comparison show, and how would you tell a reviewer?
  5. Recovery. Run r09_crash.sh with --max-samples 10 instead of 2. How many samples were flushed, buffered and in progress at the kill, and how many did the retry re-run?
  6. Eval-set identity. In a fresh directory, run eval_set([orders(n=6)], ...), then try to amend it by adding orders(n=3) and, separately, by changing max_tokens. Which works, which is refused, and why?
  7. Gate a slice. Extend ci_gate.py and gate_spec.json so that triage_labels must be at least 0.9 on tickets whose metadata["edge"] is "outage" or "security", using GateThresholds(slice_floors=...) and the sample metadata. Run it on ci-regressed.
  8. Your own provider. Add a max_tokens behaviour to callmodel_api.py: truncate the callable's reply to config.max_tokens words when it is set, return stop_reason="max_tokens" when truncated, and show the effect on the triage scorers with --max-tokens 5.
Answers
  1. Field by field, highest wins: a per-call generate(max_tokens=...) beats the run (file or flag), which beats the Task, which beats the model's own config. The generate-config file is one of the "run" sources, and an explicit CLI flag beats the file (10B.9, 8.6). The model event records the per-call value; log.plan.config records the run's.
  2. With a static cap of 40 above the capacity of 30, about ten requests at a time are rejected for as long as the queue is full, each retried after a three-second (and growing) backoff, so the run is much slower and the logs show many retries. Adaptive found 30 after one cut; static never learns.
  3. Three of ten is 30%, and the threshold fails once errors reach it (>= in 0.3.292, although the docs say "more than"): a proportion must be above 0.3 (for example 0.31), a count at least 4. The reported accuracy is 1.000 over 7, which is why coverage must be reported.
  4. Retried samples would show a lower (or, with a different construction, higher) mean than first-try samples, with very few samples in the retried group. Report the counts and both means, say that the retried group is too small for a test, and investigate why those inputs fail rather than relying on retries.
  5. Your numbers will vary with timing. With 10 in flight, more samples are in progress at the kill (up to 10), so recovery records more cancelled samples and the retry re-runs more. The lesson: max_samples trades throughput for recoverable work.
  6. Adding orders(n=3) is a superset (a new task alongside the old one) and runs only the new task. Changing max_tokens changes the identity of orders(n=6), so its existing log is foreign and the set refuses: use a new directory.
  7. Build per-slice value lists by joining log.reductions values to each sample's metadata by id, pass them to summarise_metric(values, slices={"outage+security": [...]}), and set GateThresholds(slice_floors={"outage+security": 0.9}). The slice is T02, T04 and T09. Its mean is 0.778 in both the baseline and ci-regressed, because the scripted model already gets T02 wrong and the regression changed other tickets. So the slice floor fails on every run, including ci-same: a slice floor exposes a weakness the overall mean hides, and evaluate_gate() also warns that a 3-case slice floor is noisy. Deciding whether to fix T02 or lower the floor is the point of the exercise.
  8. Use config.max_tokens inside generate(), cut the text, and return ModelOutput.from_content(model=..., content=text, stop_reason="max_tokens"). With 5 words, every JSON answer is cut, triage_format falls to 0 and triage_labels to 0, and counting stop_reason per sample shows the cause, the "truncation looks like a model failure" trap of 3.4.

Check yourself#

  1. Name the three retry layers in an Inspect run and what each one retries.
  2. A run with fail_on_error=0.1 has 100 samples and 10 errors. Does it fail? With 11? And what does fail_on_error=1 mean?
  3. Why can a tolerated-error run report a higher score than the system deserves?
  4. What does continue_on_fail=True change, and what does it not change?
  5. Which GenerateConfig value reaches the provider when the model's config says max_tokens=400, the Task says 100 and eval() says 200? Where in the log is the value that was really sent?
  6. What is the default concurrency behaviour in 0.3.292, and what turns it off?
  7. Why does max_samples=3 slow a 200-sample generation task, and when would you set max_samples above the connection limit?
  8. List four things in the response cache key and two that are not.
  9. Why did CachePolicy(per_epoch=False) make 20 calls for 12 samples × 3 epochs?
  10. When is batch mode a good fit, and when is it a bad one?
  11. Where does eval_retry() write its log by default, and what does it need from the task file?
  12. What does a log with status started mean, and how do you recover it?
  13. What makes two tasks "the same" for an eval set, and what happens if you change a generation setting and re-run in the same directory?
  14. Which Inspect command's exit code can a CI job rely on, and why is a gate still needed?
  15. Why did the early-stopping manager skip nothing under default concurrency?

Further resources#


← 10B.11: Model Grading in Inspect, and Validating the Grader (optional) | Module 10B overview | 10B.13: Inspect Logs, Analysis and Extending Inspect (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