# inspect-evals-utils Runtime helpers for [Inspect AI](https://inspect.aisi.org.uk/) evaluations, moved out of [inspect_evals](https://github.com/UKGovernmentBEIS/inspect_evals) so that a standalone eval repo can use them without depending on the whole registry. inspect_evals will depend on this package and re-export everything under its old `inspect_evals.utils` paths, so existing imports keep working. Documentation, including an API reference generated from the docstrings: . For agents, [`llms.txt`](https://inspect-evals-utils.generality.org/llms.txt) indexes the site in the [llms.txt](https://llmstxt.org) convention, [`llms-full.txt`](https://inspect-evals-utils.generality.org/llms-full.txt) is every page concatenated, and each page's Markdown is served at its path with a `.md` suffix (for example `reference/ids.md`). ## Install ```bash uv add inspect-evals-utils # or, for the Hugging Face wrappers: uv add "inspect-evals-utils[huggingface]" ``` ## Modules - [`inspect_evals_utils.ids`](reference/ids.md): `create_stable_id`, `filter_duplicate_ids`, `drop_known_broken`, `require_optional_dependency`, `DuplicateIdError`, `KnownBrokenSampleError`. - [`inspect_evals_utils.datasets`](reference/datasets.md): `load_json_dataset` and `load_csv_dataset`, which cache remote files and retry transient errors, plus `cache_dataset_loader`, `is_remote_url`, `get_cached_fname`, `is_transient_error`. - [`inspect_evals_utils.huggingface`](reference/huggingface.md) (needs the `huggingface` extra): `hf_dataset`, `load_dataset`, `get_dataset_split_names`, `snapshot_download`, `hf_hub_download`, `sentence_transformer`, `transformers_pipeline`, `auto_model_for_sequence_classification`, `auto_tokenizer`. Each retries on rate limits and transient errors and requires a `revision=` keyword, so datasets are pinned. `set_backoff_config` changes the retry policy for later calls (the default is `CI_BACKOFF_CONFIG` when the `CI` environment variable is set, otherwise `STANDARD_BACKOFF_CONFIG`). `set_hf_call_recorder` and `set_backoff_recorder` register callbacks that test sessions use to count calls and retries; both default to doing nothing. - [`inspect_evals_utils.code`](reference/code.md): `extract_code_blocks`, `extract_code_block`, `strip_json_fence`, `defines`. - [`inspect_evals_utils.scorers`](reference/scorers.md): the `ScoreReason` constants (`GRADER_FAILED`, `SCORING_FAILED`, `NO_RESPONSE`, `REFUSAL`, `INVALID_RESPONSE_FORMAT`) and `GraderFailureMode` with its constants, moved from `inspect_evals.utils.scorers`; and the free-text verdict parser `find_verdict`, `parse_verdict`, `VerdictMatch`, `VerdictParseFailure`, with `VERDICT_LABEL` and `verdict_instruction` for prompts an eval words itself. The parser reads one value (yes/no, a letter, one number) from a labelled line or a leading token, with a required `position` and no fallback verdict. - [`inspect_evals_utils.messages`](reference/messages.md): `message_content_text`, `reasoning_to_text`. - [`inspect_evals_utils.metadata`](reference/metadata.md): `load_eval_version`, which reads the `version` field of the `eval.yaml` beside a task module. Call it as `load_eval_version(__file__)`. - [`inspect_evals_utils.prompts`](reference/prompts.md): `Prompt`, a dataclass recording a prompt with its provenance. - [`inspect_evals_utils.shuffle`](reference/shuffle.md): `shuffle_and_seed`. - [`inspect_evals_utils.cache`](reference/cache.md): `cache_path()` and `INSPECT_EVALS_CACHE_PATH`. The most-used names are also importable from the top level, for example `from inspect_evals_utils import create_stable_id`. The Hugging Face module is not, so the base package imports without the extra. ## Cache directory Downloads land in `INSPECT_EVALS_CACHE_PATH`, which defaults to the platform user cache directory for `inspect_evals`. Set `INSPECT_EVALS_CACHE_DIR` to move it or point it at a pre-populated directory. It must be absolute or start with `~`, and it is read once when the package is imported. inspect_evals reads the same variable and default, so one machine has one cache. ## README generation The `inspect-evals-readmes` command rewrites the generated sections of each eval's README (Contributors, Usage, Options and Parameters) from its `eval.yaml` and `@task` signatures. It finds evals as `//eval.yaml` (default `src`), imports each package to read the task parameters, and writes between the `` style tag pairs. ```bash uv run inspect-evals-readmes generate # rewrite the sections uv run inspect-evals-readmes generate --check # exit 1 if any README is out of date; writes nothing uv run inspect-evals-readmes generate --eval my_eval --create-missing uv run inspect-evals-readmes add-section --key Parameters --insert-after Options ``` `add-section` inserts a missing tag pair after the first listed section it finds, or at the end of the file. ## Private inspect_ai APIs `inspect_evals_utils.datasets` uses `inspect_ai._util.file.file` to open local and remote files through one interface. There is no public equivalent yet, so a future inspect_ai release could break it. ## Development ```bash uv sync uv run pre-commit install # optional: run the lint stack on every commit uv run pytest uv run basedpyright src ``` Each pull request adds a changelog fragment rather than editing `CHANGELOG.md`, so concurrent PRs don't conflict. Run `uv run scriv create`, uncomment the sections that apply in the new file under `changelog.d/`, and commit it with the change, or delete it if the change needs no entry. To release, run the **Prepare release** workflow from the Actions tab. It bumps `version` in `pyproject.toml`, collects the fragments into `CHANGELOG.md`, and opens a release pull request, whose CI starts once you click **Approve workflows to run** on it; merging it tags the release. It needs _Settings → Actions → General_ → **Allow GitHub Actions to create and approve pull requests**. By hand, the same is `uv version --bump minor` and `uv run scriv collect`. The documentation site is built by mkdocs with [mkdocstrings](https://mkdocstrings.github.io/): `mkdocs_hooks.py` generates every page at build time (the front page from this README, one reference page per public module), so a new module or docstring needs no docs change. A new module needs a module docstring, whose first line is its summary in the reference index. `uv run --group docs mkdocs serve` previews the site, and `.github/workflows/docs.yml` publishes it to GitHub Pages from main. Linting (ruff, [zizmor](https://docs.zizmor.sh/), mdformat) runs via [pre-commit](https://pre-commit.com); CI runs the same stack plus basedpyright and pytest via the shared [`python-ci`](https://github.com/Generality-Labs/python-project-template) reusable workflow. ## Releasing See [RELEASING.md](https://github.com/Generality-Labs/inspect-evals-utils/blob/main/RELEASING.md). --- # `inspect_evals_utils.cache` The cache directory shared by inspect_evals and standalone evals. Set INSPECT_EVALS_CACHE_DIR to move it or point it at a pre-populated directory. ## `cache_path` ```python def cache_path() -> Path ``` Resolve the cache directory, rejecting a value that depends on the cwd. ## `INSPECT_EVALS_CACHE_PATH` ```python INSPECT_EVALS_CACHE_PATH = cache_path() ``` --- # `inspect_evals_utils.code` Helpers for extracting generated code and JSON from Markdown responses. ## `extract_code_blocks` ```python def extract_code_blocks(completion: str, language: str = 'python') -> list[str] ``` Return the language-labelled code blocks, or else the unlabelled ones. Blocks are in the order they appear. Unlabelled blocks are returned only when no block carries one of the language's labels. Labels are matched case-insensitively and both LF and CRLF line endings are accepted. Fences labelled for another language are not treated as unlabelled code, and empty blocks are skipped. A labelled fence that is never closed runs to the end of the text. ## `extract_code_block` ```python def extract_code_block(completion: str, language: str = 'python', accept: Callable[[str], bool] | None = None) -> str | None ``` Return the first block from `extract_code_blocks`, or None if there is none. Language-labelled blocks are preferred over unlabelled blocks even when an unlabelled block appears earlier in the response. When `accept` is given, the first block it accepts is returned instead. If it accepts none, the first block is returned as without it. Pass `defines(name)` to take the block that implements the function the task asks for, rather than a usage example or a draft that does not parse. ## `strip_json_fence` ```python def strip_json_fence(text: str) -> str ``` Return the JSON inside one code fence wrapping the whole text, else the text unchanged. The fence may be labelled `json` or unlabelled. Use it before parsing a reply that should be bare JSON, such as one requested with a `response_schema`: some providers accept the schema without enforcing it and return the JSON in a fence. Text with prose around the fence, or more than one fence, is returned unchanged, so it still fails validation. ## `defines` ```python def defines(name: str) -> Callable[[str], bool] ``` Accept Python code that parses and defines `name` at the top level. --- # `inspect_evals_utils.datasets` Load JSON and CSV datasets, caching remote files and retrying transient download errors. Remote files are downloaded once into the shared cache directory (see :mod:`inspect_evals_utils.cache`) and read from there on later runs. ## `DatasetLoader` ```python DatasetLoader = Callable[..., Dataset] ``` ## `SUPPORTED_REMOTE_URL_PROTOCOLS` ```python SUPPORTED_REMOTE_URL_PROTOCOLS = {'https', 'http', 's3', 'gs', 'gcs', 'az', 'abfs'} ``` ## `LOCAL_PROTOCOL` ```python LOCAL_PROTOCOL = {'', 'c', 'd', 'e', 'file'} ``` ## `TRANSIENT_ERRORS` ```python TRANSIENT_ERRORS = {408, 429, 500, 502, 503, 504} ``` ## `is_remote_url` ```python def is_remote_url(file_path: str) -> bool ``` ## `get_cached_fname` ```python def get_cached_fname(url: str, tag: str = '') -> str ``` Generate cache filename with optional tag prefix and URL hash. Args: url: The URL to hash tag: Optional human-readable tag prefix (empty string for no tag) Returns: Filename in format: {tag}_{hash}.{ext} or {hash}.{ext} ## `is_transient_error` ```python def is_transient_error(e: Exception) -> bool ``` Check if error is transient and should be retried. Handles both HTTP errors from requests and network errors from fsspec. ## `cache_dataset_loader` ```python def cache_dataset_loader() -> Callable[[Callable[Concatenate[str, P], Dataset]], Callable[Concatenate[str, P], Dataset]] ``` Decorator factory that adds caching functionality to dataset loader functions. The cache directory is inferred from the format_extension parameter. Returns: A decorator that wraps dataset loaders with caching logic ## `load_json_dataset` ```python def load_json_dataset(file_path: str, eval_name: str, sample_fields: Any = None, auto_id: bool = False, shuffle: bool = False, seed: int | None = None, limit: int | bool | None = None, epoch: int | None = None, name: str = '', fs_options: dict[str, Any] | None = None, *, encoding: str = 'utf-8', refresh: bool = False, cache_tag: str | None = None, **reader_kwargs: Any) -> Dataset ``` Load a JSON or JSONL dataset with caching support for remote URLs. Args: file_path: Local path or remote URL to the JSON/JSONL file (extension auto-detected) eval_name: Evaluation name (organizes cache directory) sample_fields: Field specification or converter function for samples auto_id: Automatically generate sample IDs shuffle: Shuffle the dataset seed: Random seed for shuffling limit: Maximum number of samples to load epoch: Epoch number for sampling name: Dataset name fs_options: Filesystem options for remote URLs encoding: Text encoding of the source file. Remote files are cached as UTF-8. refresh: Force re-download of cached remote files cache_tag: Optional human-readable tag for cache filename reader_kwargs: Optional JSON reader options. Returns: Dataset object ## `load_csv_dataset` ```python def load_csv_dataset(file_path: str, eval_name: str, sample_fields: Any = None, auto_id: bool = False, shuffle: bool = False, seed: int | None = None, limit: int | bool | None = None, epoch: int | None = None, name: str = '', fieldnames: list[str] | None = None, dialect: str = 'unix', delimiter: str | None = None, encoding: str = 'utf-8', fs_options: dict[str, Any] | None = None, shuffle_choices: bool | int = False, *, refresh: bool = False, cache_tag: str | None = None) -> Dataset ``` Load a CSV dataset with caching support for remote URLs. Args: file_path: Local path or remote URL to the CSV file (extension auto-detected) eval_name: Evaluation name (organizes cache directory) sample_fields: Field specification or converter function for samples auto_id: Automatically generate sample IDs shuffle: Shuffle the dataset seed: Random seed for shuffling limit: Maximum number of samples to load epoch: Epoch number for sampling name: Dataset name fieldnames: CSV field names dialect: CSV dialect delimiter: CSV delimiter character encoding: Text encoding of the source file. Remote files are cached as UTF-8. fs_options: Filesystem options for remote URLs shuffle_choices: Shuffle multiple choice options. An int is used as the shuffle seed (as in inspect_ai's ``csv_dataset``); True shuffles unseeded. refresh: Force re-download of cached remote files cache_tag: Optional human-readable tag for cache filename Returns: Dataset object --- # `inspect_evals_utils.huggingface` Hugging Face wrappers that retry on rate limits and transient errors, and require a pinned ``revision=``. Needs the ``huggingface`` extra: ``uv add "inspect-evals-utils[huggingface]"``. ## `Jitterer` ```python Jitterer = Callable[[float], float] ``` ## `BackoffConfig` ```python class BackoffConfig(TypedDict) ``` ### `max_tries` ```python max_tries: int ``` ### `initial_wait_mins` ```python initial_wait_mins: int ``` ### `max_wait_mins` ```python max_wait_mins: int ``` ### `jitter` ```python jitter: Jitterer | None ``` ## `HF_RATE_LIMIT_WINDOW_MINS` ```python HF_RATE_LIMIT_WINDOW_MINS = 5 ``` ## `STANDARD_BACKOFF_CONFIG` ```python STANDARD_BACKOFF_CONFIG: BackoffConfig = {'max_tries': 3, 'initial_wait_mins': 1, 'max_wait_mins': HF_RATE_LIMIT_WINDOW_MINS, 'jitter': backoff.full_jitter} ``` ## `CI_BACKOFF_CONFIG` ```python CI_BACKOFF_CONFIG: BackoffConfig = {'max_tries': 5, 'initial_wait_mins': 1, 'max_wait_mins': HF_RATE_LIMIT_WINDOW_MINS, 'jitter': backoff.full_jitter} ``` ## `BACKOFF_CONFIG` ```python BACKOFF_CONFIG = _default_backoff_config() ``` ## `set_backoff_config` ```python def set_backoff_config(config: BackoffConfig | None) -> None ``` Set the retry policy every wrapper uses from its next call on. Pass None to go back to the default: CI_BACKOFF_CONFIG when the CI environment variable is set, otherwise STANDARD_BACKOFF_CONFIG. ## `get_backoff_config` ```python def get_backoff_config() -> BackoffConfig ``` The retry policy the wrappers will use for their next call. ## `set_hf_call_recorder` ```python def set_hf_call_recorder(recorder: Callable[[str], None] | None) -> None ``` Register a callback told the wrapper name before each Hugging Face call. Test sessions use this to count calls per test. Pass None to remove it. ## `set_backoff_recorder` ```python def set_backoff_recorder(recorder: Callable[[Details], None] | None) -> None ``` Register a callback given the `backoff` details dict on each retry wait. The dict has the keys `backoff.on_exception` passes to `on_backoff`, such as `wait` (seconds) and `tries`. Pass None to remove it. ## `record_hf_call` ```python def record_hf_call(func_name: str) -> None ``` ## `TRANSIENT_ERROR_CODES` ```python TRANSIENT_ERROR_CODES = {429: 'Too many requests... likely the HF rate limit policy has been violated', 502: 'Bad gateway... likely a transient server-side / network issue', 503: 'Service unavailable... likely a transient server overload or maintenance', 504: 'Gateway time-out... likely a transient upstream server delay'} ``` ## `hf_backoff_policy` ```python def hf_backoff_policy(max_tries: int, initial_wait_mins: int, max_wait_mins: int, jitter: Jitterer | None) -> Callable[[Callable[P, R]], Callable[P, R]] ``` Add retries to functions that interact with HF servers. See HF rate limits: https://huggingface.co/docs/hub/rate-limits#rate-limit-tiers See `Adding Jitter`: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ ## `should_retry` ```python def should_retry(err: Exception) -> bool ``` Check if the exception should be retried. `huggingface_hub.errors.HfHubHTTPError` could signal that the rate limit policy has been violated, or that there is a temporary server side issue for 429, 502, 503, and 504 responses respectively. `huggingface_hub.errors.LocalEntryNotFoundError` should be retried because once the rate limit is applied, HF function(s) attempt to check in the local cache when the internet is not working (because of the rate limit). `FileNotFoundError` should be retried if it relates to internet being down (due to rate limit) and not finding in local cache. See: https://github.com/huggingface/datasets/blob/0ec4d87dfe0a3545308a8c69459b5ed9aff440fb/src/datasets/load.py#L1032 In rare circumstances, `ValueError` can be raised from a non-huggingface module, which does not get caught and handled by any huggingface modules. So it should also be retried. `requests.exceptions.ReadTimeout` should be retried as it can be raised when the huggingface servers are temporarily unavailable. `httpx.TimeoutException` and `httpx.HTTPStatusError` are the equivalent failure modes for the httpx-based HTTP layer that `huggingface_hub` 1.x and `datasets` use internally for downloads. These slip past the `requests.exceptions.ReadTimeout` / `HfHubHTTPError` checks because they come from a different exception hierarchy. ## `get_dataset_split_names` ```python def get_dataset_split_names(*args: Any, **kwargs: Any) -> list[str] ``` Call `datasets.get_dataset_split_names` with exponential backoff and retry ## `hf_dataset` ```python def hf_dataset(*args: Any, **kwargs: Any) -> inspect_ai.dataset.Dataset ``` Call `inspect_ai.dataset.hf_dataset` with exponential backoff and retry ## `load_dataset` ```python def load_dataset(*args: Any, **kwargs: Any) -> datasets.Dataset ``` Call `datasets.load_dataset` with exponential backoff and retry ## `snapshot_download` ```python def snapshot_download(*args: Any, **kwargs: Any) -> Any ``` Call `huggingface_hub.snapshot_download` with exponential backoff and retry ## `hf_hub_download` ```python def hf_hub_download(*args: Any, **kwargs: Any) -> Any ``` Call `huggingface_hub.hf_hub_download` with exponential backoff and retry ## `sentence_transformer` ```python def sentence_transformer(*args: Any, **kwargs: Any) -> Any ``` Call `sentence_transformers.SentenceTransformer` with exponential backoff and retry. ## `transformers_pipeline` ```python def transformers_pipeline(*args: Any, **kwargs: Any) -> Any ``` Call `transformers.pipeline` with exponential backoff and retry. ## `auto_model_for_sequence_classification` ```python def auto_model_for_sequence_classification(*args: Any, **kwargs: Any) -> Any ``` Call `transformers.AutoModelForSequenceClassification.from_pretrained` with exponential backoff and retry. ## `auto_tokenizer` ```python def auto_tokenizer(*args: Any, **kwargs: Any) -> Any ``` Call `transformers.AutoTokenizer.from_pretrained` with exponential backoff and retry. --- # `inspect_evals_utils.ids` Stable sample ids, duplicate and known-broken sample filters, optional-dependency checks. ## `require_optional_dependency` ```python def require_optional_dependency(module: str, uv_group: str, pip_target: str, display_name: str | None = None) -> None ``` Ensure an optional dependency is available, otherwise raise with an actionable message. Args: module: Importable module name to check (e.g., "mlebench"). uv_group: Required uv dependency-group name to suggest (e.g., "mle_bench"). pip_target: Required pip target to install (package name, VCS/URL), e.g., "git+https://github.com/openai/mle-bench.git". display_name: Optional nice name to show in the message (e.g. "MLE-bench", defaults to `module`). ## `create_stable_id` ```python def create_stable_id(*fields: Any, prefix: str = '', length: int = 8) -> str ``` Create a stable, deterministic ID from content fields. This is useful for datasets that don't have a natural ID field and use shuffling. By creating IDs from stable content, samples maintain consistent IDs across shuffles. Args: *fields: One or more fields to hash (typically question, passage, or other unique content) prefix: Optional prefix to identify the dataset (e.g., "boolq", "gsm8k") length: Length of the hash to include in the ID (default: 8) Returns: A stable ID string like "boolq_a4f3d9e2" (with prefix) or "a4f3d9e2" (without) Example: >>> create_stable_id("What is the capital of France?", prefix="boolq") 'boolq_cb0b4aaf' >>> create_stable_id("What is 2+2?", "4", prefix="gsm8k") 'gsm8k_17f25bba' >>> create_stable_id("Some question") '76013494' ## `DuplicateIdError` ```python class DuplicateIdError(ValueError) ``` Samples sharing an id are not duplicates, or there are more than acknowledged. ## `filter_duplicate_ids` ```python def filter_duplicate_ids(dataset: Dataset, *, max_duplicates: int | None = None, reason: str | None = None) -> Dataset ``` Drop samples whose id repeats an earlier sample's id, if they are true duplicates. Every dropped sample must match the kept sample on input, choices and target; otherwise the id is under-specified and this raises rather than silently discarding data (see #2506, #2524, #2525 for evals where that happened). Samples that differ only in metadata are dropped with a warning. Args: dataset: The dataset to filter. max_duplicates: Upper bound on samples this call may drop, measured on the full pinned dataset. Exceeding it raises, since more collisions than expected means the id fields no longer identify a record or the dataset changed. Fewer is fine, because callers that subset the dataset before deduplicating see fewer. Omitting it skips the count check and emits a ``DeprecationWarning``; it will become required. reason: Why the duplicates exist, with the URL of the upstream report. Recorded in error messages so the acknowledgement is explicit at the call site. Omitting it emits a ``DeprecationWarning``; it will become required. Returns: A filtered dataset keeping the first occurrence of each id. Raises: DuplicateIdError: If samples sharing an id differ in content, or more than ``max_duplicates`` samples would be dropped. ## `KnownBrokenSampleError` ```python class KnownBrokenSampleError(ValueError) ``` A sample listed as known-broken is not in the dataset. ## `drop_known_broken` ```python def drop_known_broken(dataset: Dataset, *, broken: Mapping[IdT, str]) -> Dataset ``` Drop samples whose defects have been reported upstream, by id. Every listed id must be present in the dataset. A listed id that is not there means the dataset revision moved, the ids changed or the defect was fixed, and in each case the list needs revisiting rather than silently doing nothing. Args: dataset: The dataset to filter. broken: Sample id to the URL of the upstream report describing the defect. Ids are matched as they appear in the loaded dataset; for positional ids that means they are stable only at the pinned dataset revision. Returns: The dataset without the listed samples, order preserved. Raises: KnownBrokenSampleError: If a listed id is not in the dataset. ValueError: If an entry has no report. --- # `inspect_evals_utils.messages` Helpers for rendering chat message content as text for scorers. ``ChatMessageAssistant.text`` concatenates only ``ContentText`` items, so a message whose content includes reasoning reads as if the model said nothing of that part. Scorers that judge model behaviour (refusal judges, blacklist monitors) need the reasoning too, and need it distinguishable from the visible response rather than concatenated into it. Reasoning renders as sibling ```` and ```` blocks. inspect_ai's own ```` serialization was the alternative, but it carries ``signature`` and base64 ``internal`` attributes that exist for round-tripping and are noise in a judge prompt, so this renders only the parts a judge reads. ## `reasoning_to_text` ```python def reasoning_to_text(reasoning: ContentReasoning) -> str ``` Render reasoning content as tagged blocks. The raw chain and the provider summary are tagged separately, each emitted only when it has content, so providers that redact the raw chain and expose only a summary (OpenAI's o1/o3 among them) still contribute text. A redacted chain keeps an empty ```` marker so a judge can distinguish a withheld chain from a model that did not reason. ## `message_content_text` ```python def message_content_text(message: ChatMessage) -> str ``` Flatten a message to text, tagging reasoning rather than inlining it. Content items are rendered in order and joined with newlines. Reasoning becomes tagged blocks, text is passed through unchanged, and any other content type (images, audio, documents) is skipped as having no textual rendering. --- # `inspect_evals_utils.metadata` Read an eval's eval.yaml file. ## `load_eval_version` ```python def load_eval_version(module_file: str | PathLike[str]) -> str ``` Return the `version` field of the eval.yaml beside a module. Call it from the module that defines the eval's tasks: EVAL_VERSION = load_eval_version(__file__) The argument is a file path and not a package name because Inspect also loads a task module by file path (`inspect eval src/my_eval/my_eval.py`), and `__package__` does not name the package there. Args: module_file: Path of a file in the directory that holds eval.yaml. Returns: The version string, for example "1-A". Raises: TypeError: eval.yaml has no `version`, or YAML read it as a number. --- # `inspect_evals_utils.prompts` A dataclass for declaring a prompt together with its provenance and contracts. An eval's prompts.py declares module-level Prompt instances. Collect them with an isinstance filter, e.g.: entries = [p for p in vars(prompts).values() if isinstance(p, Prompt)] judges = [p for p in entries if p.role == "judge"] ## `Prompt` ```python class Prompt ``` One prompt, plus the facts needed to swap it in safely. ### `title` ```python title: str ``` ### `prompt` ```python prompt: str ``` ### `role` ```python role: str ``` ### `origin` ```python origin: str ``` ### `origin_note` ```python origin_note: str = '' ``` ### `inspect_parameter` ```python inspect_parameter: str | None = None ``` ### `output_format` ```python output_format: object = None ``` --- # `inspect_evals_utils.readmes.cli` The inspect-evals-readmes command. ## `main` ```python def main(argv: list[str] | None = None) -> int ``` Run the command. Returns the exit status. --- # `inspect_evals_utils.readmes.generate` Generate and maintain auto-generated sections in per-eval README files. Scans eval directories under src/, extracts metadata from eval.yaml and task parameters from @task functions, and writes Usage, Options, Parameters, and Contributors sections into README files between HTML comment tags. Usage: inspect-evals-readmes generate inspect-evals-readmes generate --eval my_eval inspect-evals-readmes generate --create-missing inspect-evals-readmes generate --check Adapted from: https://github.com/UKGovernmentBEIS/inspect_evals/blob/main/tools/generate_readmes.py ## `log_level` ```python log_level = os.getenv('LOG_LEVEL', 'INFO') ``` ## `CONTRIBUTORS_KEY` ```python CONTRIBUTORS_KEY = 'Contributors: Automatically Generated' ``` ## `OPTIONS_KEY` ```python OPTIONS_KEY = 'Options: Automatically Generated' ``` ## `USAGE_KEY` ```python USAGE_KEY = 'Usage: Automatically Generated' ``` ## `PARAMETERS_KEY` ```python PARAMETERS_KEY = 'Parameters: Automatically Generated' ``` ## `TaskInfo` ```python class TaskInfo ``` ### `name` ```python name: str ``` ### `dataset_samples` ```python dataset_samples: int ``` ## `EvalInfo` ```python class EvalInfo ``` ### `title` ```python title: str ``` ### `description` ```python description: str ``` ### `path` ```python path: str ``` ### `group` ```python group: str ``` ### `contributors` ```python contributors: list[str] ``` ### `tasks` ```python tasks: list[TaskInfo] ``` ### `version` ```python version: str ``` ### `arxiv` ```python arxiv: str | None = None ``` ### `dependency` ```python dependency: str | None = None ``` ### `tags` ```python tags: list[str] = field(default_factory=list) ``` ### `package` ```python package: str = '' ``` ### `package_name` ```python package_name: str ``` The Python package name (e.g. 'my_eval' or 'examples.gpqa'). ## `discover_evals` ```python def discover_evals(src_dir: Path, include_examples: bool = False) -> list[EvalInfo] ``` Discover all evaluations by scanning src/*/eval.yaml. ## `Contents` ```python class Contents ``` ### `contains_key` ```python contains_key = contains_key ``` ### `prefix` ```python prefix = prefix ``` ### `suffix` ```python suffix = suffix ``` ## `readme_contents` ```python def readme_contents(file: Path, key: str) -> Contents ``` ## `rewrite_readme` ```python def rewrite_readme(file: Path, key: str, contents: list[str], *, check: bool = False) -> bool ``` Replace the section between the key's tags. Returns whether the file changes. With `check`, nothing is written. ## `rewrite_task_readme` ```python def rewrite_task_readme(eval_info: EvalInfo, key: str, contents: list[str], *, check: bool = False) -> bool ``` ## `link_md` ```python def link_md(text: str, href: str) -> str ``` ## `contributor_links` ```python def contributor_links(contributors: list[str]) -> list[str] ``` ## `build_contributors_section` ```python def build_contributors_section(eval_info: EvalInfo) -> list[str] ``` ## `build_options_section` ```python def build_options_section(eval_info: EvalInfo) -> list[str] ``` ## `build_usage_section` ```python def build_usage_section(eval_info: EvalInfo) -> list[str] ``` ## `extract_task_parameters` ```python def extract_task_parameters(task_name: str, package_name: str) -> list[dict[str, Any]] ``` Extract parameter information from a @task decorated function. Tries to import the task function from the package __init__ (which should export @task functions). Args: task_name: Name of the task function package_name: Python package name (e.g. "my_eval" or "examples.gpqa") Returns: List of parameter dictionaries with name, type_str, default, and description ## `build_parameters_section` ```python def build_parameters_section(eval_info: EvalInfo) -> list[str] ``` Build the Parameters section for a task README. ## `generate_basic_readme` ```python def generate_basic_readme(eval_info: EvalInfo) -> list[str] ``` Generate basic README content for a new eval. ## `readme_exists` ```python def readme_exists(eval_info: EvalInfo) -> bool ``` ## `TaskImportError` ```python class TaskImportError(ImportError) ``` A task named in eval.yaml could not be imported from its package. ## `missing_tasks` ```python def missing_tasks(eval_info: EvalInfo) -> list[str] ``` Return the `package.task` names in eval.yaml that cannot be imported. ## `generate_readmes` ```python def generate_readmes(src_dir: Path, *, eval_name: str | None = None, create_missing: bool = False, include_examples: bool = False, check: bool = False) -> list[Path] ``` Generate or update the README sections of every eval under `src_dir`. Args: src_dir: Directory holding `/eval.yaml` packages. eval_name: If set, only process this eval (package name, e.g. "my_eval" or "examples.gpqa"). create_missing: Create README files for evals that don't have them. include_examples: Also process example evaluations under `examples/`. check: Report what would change without writing anything. Returns: The README paths that changed, or would change under `check`. Raises: LookupError: `eval_name` matched no eval. TaskImportError: a task in some eval.yaml could not be imported; that eval's README is left untouched. --- # `inspect_evals_utils.readmes.sections` Generic script to add missing section tags to eval READMEs. This script scans all eval READMEs and adds HTML comment tags for auto-generated sections if they don't already exist. It can intelligently place the new section after a specified list of existing sections (in priority order). Usage: inspect-evals-readmes add-section --key Parameters --insert-after Options --insert-after Usage The script will: 1. Discover all eval paths from individual eval.yaml files 2. Check each README to see if the section tags already exist 3. If not, insert the tags after the first found section from --insert-after list 4. If none of those sections exist, append to the end of the file Note: ": Automatically Generated" is automatically appended to all keys. Adapted from: https://github.com/UKGovernmentBEIS/inspect_evals/blob/main/tools/add_readme_section.py ## `normalize_key` ```python def normalize_key(key: str) -> str ``` Normalize a key by ensuring it ends with ': Automatically Generated'. Args: key: The base key (e.g., "Parameters" or "Parameters: Automatically Generated") Returns: Normalized key with the suffix ## `has_section_tags` ```python def has_section_tags(readme_path: Path, key: str) -> bool ``` Check if a README already has the specified section tags. Args: readme_path: Path to the README file key: The section key (will be normalized) Returns: True if the section tags exist, False otherwise ## `find_insertion_point` ```python def find_insertion_point(lines: list[str], insert_after_keys: list[str]) -> int | None ``` Find the line index where the new section should be inserted. For each key (in priority order), tries two strategies: 1. Look for HTML comment tag (e.g., ) 2. Look for markdown header (e.g., ## Options) Args: lines: List of lines from the README insert_after_keys: List of section keys to try inserting after (in priority order) Returns: Line index to insert after, or None if no matching section found ## `add_section_tags` ```python def add_section_tags(readme_path: Path, key: str, insert_after_keys: list[str]) -> bool ``` Add section tags to a README if they don't already exist. Args: readme_path: Path to the README file key: The section key to add (will be normalized) insert_after_keys: List of section keys to try inserting after (in priority order) Returns: True if tags were added, False if they already existed or README doesn't exist ## `add_section` ```python def add_section(src_dir: Path, key: str, insert_after: list[str]) -> list[Path] ``` Add the tags for `key` to every eval README under `src_dir` that lacks them. Args: src_dir: Directory holding `/eval.yaml` packages. key: Section key, e.g. "Parameters"; ": Automatically Generated" is appended. insert_after: Section keys to insert after, in priority order. If none is found, the tags are appended to the end of the file. Returns: The README paths that gained the tags. --- # `inspect_evals_utils.scorers` Grader vocabulary and the free-text verdict parser for LLM-judged scorers. The ``ScoreReason`` constants and ``GraderFailureMode`` were moved here from ``inspect_evals.utils.scorers`` so that a standalone eval can name a grader failure the same way the registry does. ``schema_tool_graded_scorer`` stays in inspect_evals: it uses private inspect_ai registry APIs. ## `GraderFailureMode` ```python GraderFailureMode = Literal['grader_parse_failure', 'grader_refusal', 'grader_no_tool_call', 'grader_schema_mismatch', 'grader_invalid_grade'] ``` How the grader failed, one level finer than ``ScoreReason``. All of these are ``grader_failed`` upstream. We keep the distinction under our own ``metadata["grader_failure_mode"]`` key so that a run can be partitioned by failure mode without parsing prose out of ``explanation``, without claiming a vocabulary inspect_ai has not adopted. ## `INVALID_RESPONSE_FORMAT` ```python INVALID_RESPONSE_FORMAT: Final[ScoreReason] = 'invalid_response_format' ``` ## `REFUSAL` ```python REFUSAL: Final[ScoreReason] = 'refusal' ``` ## `NO_RESPONSE` ```python NO_RESPONSE: Final[ScoreReason] = 'no_response' ``` ## `GRADER_FAILED` ```python GRADER_FAILED: Final[ScoreReason] = 'grader_failed' ``` ## `SCORING_FAILED` ```python SCORING_FAILED: Final[ScoreReason] = 'scoring_failed' ``` ## `GRADER_PARSE_FAILURE` ```python GRADER_PARSE_FAILURE: Final[GraderFailureMode] = 'grader_parse_failure' ``` ## `GRADER_REFUSAL` ```python GRADER_REFUSAL: Final[GraderFailureMode] = 'grader_refusal' ``` ## `GRADER_NO_TOOL_CALL` ```python GRADER_NO_TOOL_CALL: Final[GraderFailureMode] = 'grader_no_tool_call' ``` ## `GRADER_SCHEMA_MISMATCH` ```python GRADER_SCHEMA_MISMATCH: Final[GraderFailureMode] = 'grader_schema_mismatch' ``` ## `GRADER_INVALID_GRADE` ```python GRADER_INVALID_GRADE: Final[GraderFailureMode] = 'grader_invalid_grade' ``` ## `VerdictAnchor` ```python VerdictAnchor = Literal['label', 'line'] ``` Where a verdict is read from: a labelled line, or the leading token of a line. ## `VerdictPosition` ```python VerdictPosition = Literal['first', 'last'] ``` Which candidate line holds the verdict when the reply has more than one. ## `VerdictMatch` ```python class VerdictMatch ``` A verdict read from a judge's reply. Attributes: token: The matched token, spelled as the caller passed it in ``tokens``. start: Offset of the token in the original text. end: Offset just past the token in the original text. line: The line the verdict was read from, without its line ending. ### `token` ```python token: str ``` ### `start` ```python start: int ``` ### `end` ```python end: int ``` ### `line` ```python line: str ``` ## `VerdictParseFailure` ```python class VerdictParseFailure ``` A judge's reply that holds no usable verdict. Attributes: text: The reply as received. detail: Why no verdict was read, in a few words. ### `text` ```python text: str ``` ### `detail` ```python detail: str ``` ### `unscored` ```python def unscored(**kwargs: Any) -> Score ``` Build the unscored ``Score`` for this failure. The score has ``reason`` ``grader_failed``, ``metadata["grader_failure_mode"]`` ``grader_parse_failure`` and the reply under ``metadata["grader_payload"]["grader_response"]``, the keys inspect_evals' ``schema_tool_graded_scorer`` records. Keyword arguments pass through to ``Score.unscored``; a ``metadata`` argument is merged over those defaults. ## `find_verdict` ```python def find_verdict(text: str, tokens: Iterable[str], *, anchor: VerdictAnchor, position: VerdictPosition, label: str | None = None, ignore_quoted: bool = False) -> VerdictMatch | VerdictParseFailure ``` Read a single-value verdict from a judge's free-text reply. The selected line must name exactly one token. Under ``anchor="label"`` that check scans the line from just after the separator, so a label that is itself a token (``Correct: INCORRECT``) or a numbered list marker (``1. Rating: 3``) does not count as a second verdict. Under ``anchor="line"`` it scans the whole line. Args: text: The judge's reply. tokens: The verdicts the prompt offered, such as ``("yes", "no")``. Matched case-insensitively as whole words. anchor: ``"label"`` reads the token after ``label`` and a separator on the same line; ``"line"`` reads the token that leads a line. position: ``"first"`` or ``"last"`` candidate line. There is no default, because the position follows the prompt. label: The field name the prompt asks for, required with ``anchor="label"`` and not allowed otherwise. ignore_quoted: Skip lines that start with ``>``, for prompts that quote the model under test. Returns: A ``VerdictMatch``, or a ``VerdictParseFailure`` when the reply holds no usable verdict. Raises: ValueError: The token set or the label is unusable. ## `parse_verdict` ```python def parse_verdict(text: str, tokens: Mapping[str, T], *, anchor: VerdictAnchor, position: VerdictPosition, label: str | None = None, ignore_quoted: bool = False) -> T | VerdictParseFailure ``` Read a single-value verdict from a judge's reply and map it to a value. This is for a verdict that is one value: yes or no, a letter, one number. A judge that returns several fields (a rubric, a verdict plus a confidence) should use a structured grader, such as a tool call with a schema, rather than this parser. On a ``VerdictParseFailure``, a scorer that returns one value returns ``failure.unscored()``. A scorer whose ``Score.value`` is a dict fed by several judges sets this judge's key to ``nan`` and keeps the other keys. Bounded, grader-only retries for a format failure are acceptable before unscoring, and a retry must not be served from the cache. Args: text: The judge's reply. tokens: Each verdict the prompt offered, mapped to the value to return. anchor: As for ``find_verdict``. position: As for ``find_verdict``. label: As for ``find_verdict``. ignore_quoted: As for ``find_verdict``. Returns: The value mapped from the matched token, or a ``VerdictParseFailure``. ## `VERDICT_LABEL` ```python VERDICT_LABEL: Final[str] = 'ANSWER' ``` The label ``verdict_instruction`` asks for. Pair it with ``anchor="label"``. ## `verdict_instruction` ```python def verdict_instruction(tokens: Iterable[str], *, label: str = VERDICT_LABEL) -> str ``` One sentence telling the judge how to end its reply. For ``("yes", "no")`` it returns ``End your reply with a line of the form `ANSWER: yes` or `ANSWER: no`, and nothing after it.`` Read the reply with ``parse_verdict(..., anchor="label", label=VERDICT_LABEL, position="last")``. An eval that keeps an upstream prompt for parity does not use this sentence; it states whatever anchor and position that prompt implies. Args: tokens: The verdicts the judge may give, at least two. label: The field name to ask for. Returns: The instruction sentence. Raises: ValueError: Fewer than two tokens, or an unusable token set. --- # `inspect_evals_utils.shuffle` Turn a ``shuffle`` task parameter into a dataset loader's ``shuffle`` and ``seed``. ## `shuffle_and_seed` ```python def shuffle_and_seed(shuffle: bool | int) -> tuple[bool, int | None] ``` Split a ``shuffle`` task parameter into a loader's ``shuffle`` and ``seed``. ``shuffle`` is read as inspect reads ``shuffle_choices`` and ``--sample-shuffle``: an int is the seed, ``True`` shuffles without one and ``False`` does not shuffle. Defaulting the parameter to an int keeps the order the same on every run without a separate ``seed`` parameter: @task def my_eval(shuffle: bool | int = 42) -> Task: should_shuffle, seed = shuffle_and_seed(shuffle) return Task(dataset=hf_dataset(..., shuffle=should_shuffle, seed=seed)) Args: shuffle: A seed, ``True`` for an unseeded shuffle, or ``False`` for none. Returns: The loader's ``shuffle`` and ``seed`` arguments.