E2E Testing for Chat, Voice, Phone and Video AI Agents

Run Thousands of Test Scenarios against Your Agent and Catch Hallucinations, Bias, and Toxicity Before Users Do.

Inspect AI: How to Write, Run and Gate LLM Evals in Python

Inspect AI is the UK AISI's open-source Python eval framework. Install it, write a first eval, read logs in inspect view and gate CI on accuracy.

Published

Summarise with AI

Inspect AI is an open-source Python framework for evaluating LLMs and agents. It's from the UK AI Security Institute and Meridian Labs. You define an eval as a Task (which is a dataset, a solver and a scorer); you run it via inspect eval, and then you just look at every sample in the inspect view log viewer.

This guide takes you through installing Inspect, writing your first eval off your own data, looking at the logs, sandboxing the naughty tools in Docker and then turning that into a CI gate that can fail a build. It also covers where Inspect stops (it scores a model or agent against a dataset), and it absolutely does not in any way call your deployed chatbot the way a customer would.

TL;DR

Inspect AI is the UK AI Security Institute's open-source Python framework for LLM and agent evals, built with Meridian Labs. An eval is a Task that joins a dataset, a solver and a scorer; inspect eval runs it, inspect view shows every sample, and a short Python script can fail CI on accuracy.

How Do You Get From Install to a CI Gate?

  • Install Inspect AI: Inspect AI is free (MIT license), needs Python 3.11 or later and installs with pip install inspect-ai plus your provider SDK. Its source is in the UKGovernmentBEIS/inspect_ai repository on GitHub.
  • includes() scorer: Inspect AI's includes() is a case-insensitive substring match that reports accuracy and stderr, so a short target such as "no" also matches an answer that contains "not".
  • inspect view: The Inspect log viewer reads the .eval logs in ./logs and shows each sample's messages, answer and score, so a reviewer can see why a sample failed.
  • CI gate: Inspect AI's eval() returns EvalLog objects, so a short gate.py reads the accuracy metric and exits 1 when it falls below EVAL_MIN_ACCURACY.
  • Inspect Evals: A separate library of 201 ready-made evals built on Inspect, installed with pip install inspect-evals and run with commands such as inspect eval inspect_evals/arc_easy.

Where Does Inspect AI Stop?

  • Deployed agents: Inspect AI scores a model or a Python-defined agent against a labeled dataset. TestMu AI Agent Testing calls the live chat endpoint with a simulated customer and returns a Green, Yellow or Red go-live verdict.

What Is Inspect AI?

Inspect AI is an LLM evaluation framework (in Python). The project description refers to it as an open-source framework for large language model evaluation covering coding, agentic, reasoning, knowledge, behavior and multimodal.

It was open-sourced by the UK AI Security Institute (AISI) in 2024.

Facts worth knowing before you adopt it (checked December 3, 2026):

FactValueSource
Latest release0.3.294, released December 1, 2026PyPI
Python3.11 or laterPyPI
LicenseMITPyPI, GitHub
GitHub3.4k stars, 1k forksUKGovernmentBEIS/inspect_ai repo
Model providers"over 20" plus local HuggingFace, vLLM and SGLangInspect docs
SandboxesDocker, Kubernetes, Modal, Proxmox, VagrantInspect docs
Ready-made evals201 listed in Inspect Evals (129 built in, 72 external)Inspect Evals site

Inspect sits in the 'AI tools for testing AI' half of the AI testing tools market (i.e. it's an AI tool that tests the quality of the model or agent's output) rather than the test automation tools which test the app around the model.

For a quick visual walkthrough of this concept, watch the video below from TestMu AI.

Youtube thumbnail

Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.

How Do You Install Inspect AI?

Install the package and then the SDK for the provider you're calling. Providers will pull their API keys from the standard provider environment variables.

python3 --version          # must be 3.11 or later
pip install inspect-ai
pip install anthropic      # or: openai, google-genai

# Keys and the default model come from the environment, never from code
export ANTHROPIC_API_KEY="..."          # set in your shell or CI secret store
export INSPECT_EVAL_MODEL="anthropic/claude-sonnet-5-5"

INSPECT_EVAL_MODEL is the default model, so you can simply omit the --model from all your commands. The Inspect CLI will also look for a .env file in the current working directory (or one of the parent directories), which is very handy when you're working locally. Just don't commit your .env file to Git.

The provider table in the Inspect docs lists the model string format for each provider (openai/..., anthropic/..., google/... and hf/... for the HuggingFace models).

How Do You Write Your First Inspect Eval?

An Inspect eval is a Python function decorated with @task that returns a Task. The Task joins three parts:

  • Dataset - labeled samples consisting of an input and a target.
  • Solver - what actually generates the answer, from one generate() call right through to a full agent.
  • Scorer - how the answer is marked up against the target.

Start with your own data. Here's a JSON Lines file for a store's support assistant. Each line is one sample.

{"input": "How many days do customers have to request a refund?", "target": "30 days"}
{"input": "Do you refund shipping costs on returned items?", "target": "no"}
{"input": "Which payment methods can be refunded to store credit?", "target": "gift card"}

Save it as refund_qa.jsonl and then write the task. The dataset path is a task argument, so you could point the same eval at a larger file with no code changes.

# refund_eval.py
from inspect_ai import Task, task
from inspect_ai.dataset import FieldSpec, json_dataset
from inspect_ai.scorer import includes
from inspect_ai.solver import generate, system_message

SYSTEM_PROMPT = (
    "You are the support assistant for an online store. "
    "Answer customer questions in one short sentence."
)

@task
def refund_policy(dataset: str = "refund_qa.jsonl"):
    return Task(
        dataset=json_dataset(
            dataset,
            sample_fields=FieldSpec(input="input", target="target"),
        ),
        solver=[system_message(SYSTEM_PROMPT), generate()],
        scorer=includes(),
    )

includes() matches a sample if the target text is present anywhere in the output (case insensitive). It's ideal for short facts such as "30 days".

The targets listed above are just examples. Replace them with the actual answers your own policy documents would provide.

Note

Note: Test a chatbot that your customers are already using? Inspect scores the model behind it. TestMu AI Agent Testing makes a live chat call to the chat endpoint with a simulated customer and scores every conversation on 9 metrics, one of which is hallucination detection. It has a free plan for chat and voice agents.

How Do You Run an Eval and Then Read the Results?

Run the task file with inspect eval. Use --limit as you're iterating so you don't end up paying for the entire dataset each time.

# First pass: 2 samples only
inspect eval refund_eval.py --limit 2

# Full run against a different dataset file
inspect eval refund_eval.py -T dataset=refund_qa_full.jsonl

# Repeat each sample 3 times to see how stable the answers are
inspect eval refund_eval.py --epochs 3

# Open the log viewer
inspect view
Inspect AI eval run in a terminal showing two samples scored with the includes scorer

Every run writes a log to ./logs (you can change it via --log-dir or INSPECT_LOG_DIR). Since v0.3.46 the default format is .eval (a binary format; the docs state it is "typically 1/8 the size" of the JSON alternative). The inspect view opens a browser viewer in which you can open each sample, view the full message history and see why the scorer passed or failed it.

Inspect view log viewer showing a failed sample, the model answer and the scorer decision

By default an eval will fail if any sample errors. --fail-on-error determines how many sample errors you're prepared to tolerate, which is useful when a provider is returning the odd timeout on a long run.

Which Inspect Scorer Should You Use?

Pick the scorer that corresponds to the shape of your target. The built-in scorers below are taken from the Inspect scorer docs.

ScorerWhat it checksUse it for
includes()Target appears anywhere in the output (case-insensitive by default)Short facts inside a sentence
match()Target at the end (default), begin or anywhere; ignores case and whitespace; can compare numbersFinal answers, numeric results
pattern()Extracts an answer with a regex and compares itStructured replies like "Order ID: 123"
answer()Reads the text after an ANSWER: X linePrompts that ask for a fixed answer line
exact()Normalized exact matchIDs, codes, single words
f1()Token-overlap F1Short free-text answers
choice()Multiple-choice output from multiple_choice()Benchmarks with lettered options
model_graded_fact()Another model checks the output contains the target factFacts that can be phrased many ways
model_graded_qa()Another model judges correctness from grading guidanceOpen answers that need judgment

For model-graded scorers, pass a separate grader with a model role so that the model under test doesn't grade itself:

export OPENAI_API_KEY="..."   # the grader's provider needs its own key
inspect eval refund_eval.py --model-role grader=openai/gpt-6-luna

Most scorers report accuracy and stderr; exact() and f1() report the mean and stderr.

Start with code-based scorers. At Testμ Conf 2026, Rushabh Mehta (speaker) gave an estimate that code-based graders would cover about 65-70% of what most teams actually need (TestMu AI session recap), which leaves model grading to deal with the open-ended bit.

How Do You Run Inspect Evals in a Docker Sandbox?

Inspect runs the model's tool calls within a sandbox when the eval is providing the model with tools. Set sandbox="docker" on the Task (or on a sample, or on the eval() call) and hand the model the tools via use_tools(). The standard bash(), python() and text_editor() tools all require a sandbox.

This task follows the pattern as described in the Inspect standard tools docs:

# coding_eval.py
from inspect_ai import Task, task
from inspect_ai.dataset import FieldSpec, json_dataset
from inspect_ai.scorer import includes
from inspect_ai.solver import generate, use_tools
from inspect_ai.tool import bash, python

CMD_TIMEOUT = 180  # seconds per tool call

@task
def coding_tasks(dataset: str = "coding_tasks.jsonl"):
    return Task(
        dataset=json_dataset(
            dataset,
            sample_fields=FieldSpec(input="input", target="target"),
        ),
        solver=[
            use_tools([bash(CMD_TIMEOUT), python(CMD_TIMEOUT)]),
            generate(),
        ],
        scorer=includes(),
        message_limit=30,
        sandbox="docker",
    )

Every bash() or python() call that the model makes executes inside the sample's container rather than on your machine or the CI runner. message_limit=30 will stop a sample that's looping.

To assess an agent rather than a single model turn, Inspect's built-in react() agent makes use of the same tools. The agents docs define one using react(name=..., description=..., prompt=..., tools=[...]) within an @agent function and pass that to eval() as the solver.

What the sandboxing docs state, and what they warn about:

  • Requirements - Docker Engine 24.0.6 or later and Docker Compose 2.21.0 or later (2.22.0 or later if Inspect pulls images from a registry).
  • Default image - python:3.12-bookworm if you supply neither a Dockerfile nor a compose.yaml.
  • Network - the generated config has network_mode: none. If you're supplying your own Compose file, then that default is overridden, and you'll need to explicitly add network_mode: none.
  • Isolation - each sample gets its own sandbox instance.
  • Limits - exec output over 10MB is front-truncated silently, so don't rely on an exception to catch that. Pin image digests as tags like python:3.12-bookworm can change.
  • Containment - the docs make it very clear that you should not expect a non-root user to be able to contain an adversarial model.

How Do You Gate CI on an Inspect Eval?

Inspect's Python API returns the eval log so a very small script can fail the build if the accuracy drops below some threshold you specify. eval() returns a list of EvalLog objects. Each log has a status and results.scores, and each score has a set of metrics with a value.

# gate.py: exits 1 when accuracy is below EVAL_MIN_ACCURACY
import os
import sys

from inspect_ai import eval

from refund_eval import refund_policy

model = os.environ.get("INSPECT_EVAL_MODEL")
threshold = os.environ.get("EVAL_MIN_ACCURACY")
dataset = os.environ.get("EVAL_DATASET", "refund_qa.jsonl")

if not model or not threshold:
    sys.exit("Set INSPECT_EVAL_MODEL and EVAL_MIN_ACCURACY (for example 0.9).")

log = eval(refund_policy(dataset=dataset), model=model)[0]

if log.status != "success":
    sys.exit(f"Eval did not finish: status={log.status}")
if not log.results or not log.results.scores:
    sys.exit("Eval finished without scores")

metrics = log.results.scores[0].metrics
if "accuracy" not in metrics:
    sys.exit(f"No accuracy metric in results: {sorted(metrics)}")

accuracy = metrics["accuracy"].value
print(f"accuracy={accuracy:.3f} threshold={float(threshold):.3f}")
sys.exit(0 if accuracy >= float(threshold) else 1)

Run it in any CI job that has the provider key in its secret store:

EVAL_MIN_ACCURACY=0.9 python gate.py
gate.py exiting 1 because Inspect AI accuracy fell below the threshold

The script fails in 4 ways on purpose: no settings, an eval that didn't complete, a run with no scores and accuracy below the line. Upload the ./logs folder as a build artifact so that a reviewer can open the failing samples in inspect view.

Diagram of an Inspect AI task: dataset, solver and scorer produce a log that a CI gate reads
Youtube thumbnail

Inspect AI vs TestMu AI Agent Testing: Where Does Each Fit?

Inspect and TestMu AI Agent Testing answer different questions, and a lot of teams run both. Inspect tells you whether the model or agent gets your labeled cases right. Agent Testing tells you whether the deployed agent can actually go through a full conversation with a simulated customer.

The docs show you how to set up a chat agent test via cURL.

Inspect AITestMu AI Agent Testing
What it callsA model provider or an agent you define in PythonYour live agent's API endpoint (pasted as cURL), or a phone number for voice agents
Test inputLabeled dataset (input, target)Generated scenarios: Happy Path, Negative, Edge Case, Integration, Red Team
GradingBuilt-in or custom scorers, model-graded options9 chat metrics scored 0-100% (Bias Detection, Hallucination Detection, Completeness and more)
ChannelsText, multimodal, tool-using agentsChat, voice, phone, IVR, WhatsApp, video agents
CI signalYour gate script's exit codeagent-testing-cli exit codes (0 pass, 1 a completed test failed, 2-5 input, auth, API or timeout errors)
Output.eval logs in inspect viewGo-Live Assessment (Green, Yellow, Red), PDF or HTML report
TestMu AI Agent Testing chat evaluation result with an overall score, the quality metrics and the conversation turns for one scenario

Inspect AI and TestMu AI Agent Testing are by no means mutually exclusive. TestMu AI testing in no way replaces evals at all. It actually gives you the end-to-end view of the deployed agent.

For those of you who prefer config-driven prompt tests to Python tests, you can have a look at our promptfoo guide.

The Inspect AI Eval Readiness Checklist

Use this five-part checklist (Dataset, Solver, Scorer, Sandbox, Gate) before you trust an Inspect result in a release decision:

  • Dataset - the samples are taken from real user questions or tickets (each with a target that someone on the team has signed off). Keep the file in Git alongside the task.
  • Solver - the system prompt in the task is exactly the same as the one in production, word for word. Store it in one location and have it read from that location.
  • Scorer - the scorer is the same as the target shape (see scorer table). Model-graded scorers use a different grader model via --model-role grader=.
  • Sandbox - any eval that gives the model bash() or python() (as in the coding_eval.py example above) will run with sandbox="docker", a pinned image digest and network_mode: none.
  • Gate - CI runs gate.py with a threshold, fails if below that threshold and stores ./logs as an artifact.

How Do You Run a Ready-Made Benchmark With Inspect Evals?

Inspect Evals is a separate set of evaluations built on top of Inspect. The site currently has 201 evals (129 built in, 72 external) across a range of domains including coding, math, cybersecurity, safety and agents. It's run by Generality Labs with contributions from the UK AISI, Arcadia Impact and the Vector Institute.

pip install inspect-evals
inspect eval inspect_evals/arc_easy --model "$INSPECT_EVAL_MODEL" --limit 20

The example in the README itself will run the same eval using uv run from a clone of the repo. The public benchmarks will tell you how your model compares to the others; your own dataset will tell you whether it actually answers your users correctly. Run both of those before you switch models.

Moving off of OpenAI's hosted evals following the November 2026 shutdown? Our OpenAI Evals migration guide has the options. If you go with Inspect, then json_dataset() will read in JSON Lines files and map your fields to input and target using FieldSpec as in the refund_eval.py above.

Note

Note: Test the agent your customers talk to. Your Inspect gate tells you the model still knows the refund policy. Before a release, run the deployed assistant through full conversations too. Start with TestMu AI Agent Testing: connect the chat endpoint, generate scenarios from your docs, and get a Green, Yellow or Red go-live verdict. Wire it into CI with the Agent Testing CLI, next to gate.py.

Conclusion

Start with a few real questions from your support tickets, run them with --limit, and read every failed sample in inspect view before you trust the score. Check short targets against the answers too: includes() is a substring match, so a target such as "no" also matches "not".

Once the targets and the scorer hold up, add gate.py to CI with a threshold and keep ./logs as a build artifact.

Testing an AI agent? TestMu AI's Agent Testing validates chat, voice and IVR agents before your customers talk to them.

To run your first test, start free, or
for a full walkthrough of the product.

Was this helpful?

Authors

Shantanu Wali

Shantanu Wali

Author · 33 posts

Shantanu Wali is Vice President of Product Management at TestMu AI, where he owns several product lines across the testing platform, including the Real Device Cloud and the Digital Experience Testing Cloud. He has also contributed significantly to the development and scaling of KaneAI, TestMu AI's flagship GenAI-native testing agent that uses natural language to make software testing faster and more reliable in this AI era. He brings 7+ years of experience across software development and product management, starting as a backend developer at Infosys building solutions for Fortune 500 clients. Shantanu holds an MBA from IIM Calcutta and a B.Tech in Mechanical Engineering.

Mayank Bhola

Mayank Bhola

Reviewer

Mayank Bhola is Co-Founder and Head of Products at TestMu AI, where he leads the entire product portfolio across KaneAI, Kane CLI, HyperExecute, SmartUI, the Real Device Cloud, Accessibility, and other software testing product lines. As an early Lead Architect he designed and built the company's flagship Tunnel technology from scratch, created the React-based automation platform, and architected the data-intensive pipelines and FAAS services that scale it. He brings more than 10 years of experience in software development and product engineering, with earlier roles as Head of Technology at Juggernaut Books and Senior Software Engineer at PressPlay TV and Zomato. Mayank holds a B.Tech in Computer Engineering from JIIT Noida.

Inspect AI FAQs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests