10B.14 Tools and Agents in Inspect: Custom Tools, MCP, react() and Multi-Agent Systems (optional)
Up to now every Inspect eval in this track asked a model one question and scored one answer. This lesson hands the model tools and lets it act: look an order up, issue a refund, search the help centre, hand the conversation to a specialist. In Inspect that means three layers. Tools are Python functions the model may ask Inspect to run. Agents are loops that call the model, run the tools it asks for and decide when to stop; the built-in react() agent is the one you will use most. Multi-agent systems compose agents with handoff(), as_tool() and run(). You will learn each layer precisely enough to predict what the model sees, what the scorer sees and what the log records, because in an agent eval those are three different things. Every runnable sample drives the support desk from 10A.7, rebuilt as Inspect tools, with a scripted mock model, so it runs with no API key, and every output shown is what those runs printed. The lesson ends where an evaluator needs it to end: grading tool use and handoffs from Inspect logs with the evalkit graders you wrote in 10A.7 and 10A.12, and defending the number.
What you'll learn
- What a tool is in Inspect, where its code runs (your process, a sandbox or the provider) and why that matters for an eval
- The
@toolfactory pattern, the JSON schema the model is shown (printed for real), and the docstring and annotation rules, including the one the docs state and the source does not enforce - Tool results and errors:
ToolErrorversus an uncaught exception versus a parsing error, the 16 KB truncation, dict results, parallel execution and stateful tools on the sample store ToolDef,tool_with(),ToolParamswith**kwargs, tool views, and themodel_inputhook (run for real: the model sees placeholders, the transcript keeps the originals)- Tools without an agent:
use_tools(),tool_choice,generate(tool_calls=...)andexecute_tools() - The standard tool catalogue: sandbox tools, provider-run tools, in-process tools, and the removal of
web_browser() - MCP servers as tool sources: stdio, HTTP and sandbox transports,
mcp_tools(),mcp_connection()and remote execution, with a stdio server you can run keylessly - The
Agentprotocol,AgentState,@agent, the four ways to use an agent, and therun()copy-back pitfall react()parameter by parameter: prompt layering (including the hidden handoff prompt a supervisor receives), the submit tool and what the scorer sees,attempts,on_continue, refusals, overflow, truncation and compaction, and wheredeepagent()fits- Custom agents: the hand-written tool loop (with a bug in the docs' version), filtering tool calls, spans,
model_origin() - Multi-agent systems:
handoff()and its filters (what each agent actually saw, shown message by message),as_tool(), agent parameters and currying,run()andcollect()workflows, limits per mechanism - Grading agent runs: outcome and process scorers, oracle, null, careless and tool-failure controls, measuring a scaffold change as a paired experiment, and adapters that turn an Inspect sample into
evalkit'sTrajectoryandMASTrace
What you don't need
- An API key, Docker or a service. Everything runnable uses
mockllm/modelwith scripted tool calls (the MCP sample also starts a small local server process of your own). The samples that need a sandbox, a provider-run tool or a remote MCP server are labelled illustrative. - The tool-calling loop itself. One round trip is 03.5; the loop, tool design, agent patterns, MCP and multi-agent architectures are Module 08A, Module 08D and Module 08E. This lesson shows how Inspect implements them and what that means for evaluation.
- Sandboxes, limits and approval in depth. They are 10B.15; this lesson uses a message limit and a time limit where an agent needs one and points there. The methodology synthesis for agent evals, Inspect Evals and Inspect Scout are 10B.16.
- Agent evaluation concepts. Outcome versus trajectory grading, budgets, pass^k (10A.7) and handoff correctness, context transfer and the single-agent baseline (10A.12) are taught there and mapped onto Inspect here.
Setup
You need Python 3.11 or newer and uv (01B.1 if you have not used it).
uv init inspect-agents --bare --python 3.13 && cd inspect-agents # first time only
uv add inspect-ai
uv add mcp # only for Part 5's runnable MCP sample (Inspect's MCP support needs this optional package)
# or: pip install inspect-ai mcpSave every file under the name in its first comment, all in one folder, and run scripts with uv run python file.py from that folder (the samples import desk.py, so keep it next to them). Part 10 also uses evalkit's agent_eval.py and mas_eval.py (with their imports compare.py and judge_validation.py) from 10A.7 and 10A.12: put your evalkit folder on the import path with PYTHONPATH=path/to/evalkit uv run python file.py. Without mcp installed, constructing any MCP server fails with PrerequisiteError: MCP tools requires optional dependencies. Install with: pip install mcp. The illustrative real-provider samples would additionally need the provider SDK and a key in .env; the illustrative sandbox MCP sample needs Docker and the server program (Node for the reference servers).
Versions (current at time of writing, checked on PyPI on 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT, Python ≥ 3.11). Every sample marked as run was executed between 24 and 26 November 2026 with Python 3.13.14 and inspect-ai 0.3.292 (and mcp 2.3.0 for Part 5), and re-run on 28 and 29 November 2026, when every output reproduced; the output blocks are what those runs printed, trimmed only where marked. Inspect ships breaking changes in patch releases (10B.8, 1.2), and the agent APIs are among the busiest parts of the CHANGELOG: web_browser() was removed three weeks before this was written. Check the CHANGELOG before trusting any agent example, including these.
What you must be able to do after this lesson#
- Explain how Inspect executes a tool call and where it can run
- Write a custom tool with @tool and annotations so the schema is correct
- Choose between ToolError and a crash for a tool failure
- Run a react() agent and set its parameters (submit, attempts, truncation)
- Tell attempts from epochs for an agent
- Grade an agent run from its outcome and its transcript
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"Inspect runs the tool, not the model. So where does bash actually execute?" |
1.2 |
| "Our agent scored 70% on Inspect." "With which scaffold, tools and limits?" | 1.3 |
| "Why did the model call the tool with no argument types?" | 2.3 |
| "One flaky tool killed the whole sample." | 2.6 |
| "The model is reading a truncated log file and guessing." | 2.7 |
| "Why does the old screenshot not cost tokens any more?" | 3.5 |
"Use web_browser() for that." |
4.5 |
| "Plug our MCP server into the eval." | Part 5 |
| "The agent ran but the scorer saw an empty answer." | 6.4 |
"exact() fails although the agent submitted the right answer." |
7.3 |
| "Give it three attempts, like a human would get." | 7.5 |
| "I copied the custom agent loop from the docs and it crashes." | 8.2 |
| "Why does the supervisor never tell the customer it transferred them?" | 7.2 |
| "What did the specialist actually see when we handed off?" | 9.2 |
| "Handoff or agent-as-tool?" | 9.9 |
| "Grade the trajectory, not just the answer." | Part 10 |
| "A do-nothing agent scored 67%?" | Part 10, section 2 |
Part 1: Tools in Inspect: the execution model first#
1.1 The model proposes, Inspect executes#
Inspect is the "your code runs it" half of the 08A.2 loop (stopping it is 08A.3): it validates the model's structured call against the tool's schema, runs the Python function, turns known errors into tool results, truncates the result if necessary and appends a tool message before the model gets another turn.
That indirection is what makes tool use evaluable. Every proposed call, its arguments, its result or error, its duration and its place in the span tree can be recorded in the transcript. It also means there are always three artefacts to keep apart:
| Artefact | What it is | Who normally reads it |
|---|---|---|
messages |
The conversation state passed forward to later model calls. Some entries are rewritten or removed by agent machinery. | The model, and simple scorers |
events |
The full transcript: model events, tool events, spans, store changes, scores, limits and more | You, Inspect View, analysis code and trajectory adapters |
state.output |
The final ModelOutput, including the completion most scorers grade |
Scorers |
A correct agent eval often needs all three. The model's memory of the run is messages; the evidence is events; the answer is output.completion. Much of this lesson is about those seams.
1.2 Who runs a tool call: three places#
Not all "tools" execute in the same place, and the execution location determines what an eval can observe and control.
flowchart TD
model["Model proposes a structured call"] --> inspect["Inspect routes and executes it"]
inspect --> host["Host process: custom Python tools, think, memory, todo_write"]
inspect --> sandbox["Sandbox environment: bash, python, files, text_editor, computer"]
inspect --> provider["Model provider: native search or code execution, remote MCP"]
host --> result["Tool result in the conversation"]
sandbox --> result
provider --> result
result --> next["Next model turn"]
provider -. "not visible as Inspect tool events" .-> audit["Approval and transcript consequences"]| Execution place | Examples | What Inspect can record and control |
|---|---|---|
| Inspect host process | Your @tool functions, think(), todo_write(), memory() |
Full tool events, arguments, result, errors, approval and review. The code has the same access as the eval process, so write it as trusted harness code. |
| Sandbox environment | bash(), python(), text_editor(), computer(), read_file(), grep() |
Full tool events, plus sandbox events. The action is contained by the sandbox provider, though the wrapper still runs in the host. 10B.15 owns the isolation model. |
| Model provider | Native web search, native code execution, remote MCP execution | The provider performs the work during generation. Inspect does not see a normal tool event, approval does not review the individual action, and network_mode: none on a sandbox does not stop it. |
The third row is the one teams most often miss. A model with a provider-side search tool can look things up even when its container has no network. That is not a bug in Inspect: the request never passes through the sandbox. If your eval claims "no network access", choose tools and providers accordingly, and read the run's events rather than assuming.
1.3 The scaffold is part of the system under test#
In 10A.7, Part 1 you saw why an agent result is not a model result. Inspect makes the point concrete. A score depends on at least five things:
- the model and its exact version or route;
- the agent scaffold (
react(),deepagent(), your custom loop, or a bridged external agent); - the tools offered, including their names, descriptions, errors and output sizes;
- the prompt layers and submit behaviour;
- limits, approval, review, truncation and compaction.
Change one and you have a different system. "GPT-6 Luna scored 0.71" is not a reproducible claim; "GPT-6 Luna with react(), these five tools, AgentSubmit(answer_only=True), a 30-message limit and no compaction scored 0.71" is the beginning of one. 10B.12 showed how the model and generation configuration are recorded; this lesson adds the tool and agent surface, and 10B.15 completes the control surface.
1.4 The evalkit picture you already have#
The pieces map cleanly onto the agent harness you wrote in 10A.7 and the multi-agent trace schema in 10A.12:
| evalkit concept | Inspect equivalent | Important difference |
|---|---|---|
AgentFn |
An Agent, or a solver that drives one |
react() is a production-ready AgentFn with prompts, submission, retries and limits built in |
World |
Tool functions plus the sample Store and, for system actions, sandbox() |
Inspect does not impose a World interface; you choose where state lives |
World.reset() per task |
A fresh sample store per sample | State seeded by tools or setup must still be designed deliberately |
StepRecord / Trajectory |
ToolEvents, ModelEvents and spans in sample.events |
Events retain evidence that messages may drop or rewrite |
outcome grader on world.state() |
A scorer reading store_as() or the sandbox |
The scorer runs after the solver but in the same sample context |
| budget grader | Live limits such as message_limit() |
Inspect stops the run when the budget is crossed rather than only grading the overrun afterwards |
MASTrace |
Spans of type agent, handoff and tool |
Part 10 adapts them directly |
The mapping is not cosmetic. It means the graders and statistical ideas you already own still apply: outcome first, process second, budgets always, reliability over repeated trials, and a single-agent baseline before any multi-agent claim.
1.5 The running example: the support desk as Inspect tools#
The running example is the support desk from 10A.7, 2.5, rebuilt in Inspect's idiom. The world is a Pydantic StoreModel named Desk. Inspect creates a separate store for every sample, so two samples cannot leak refunds or emails into each other. The tools are small, typed and deliberate: reads return JSON, the refund tool previews unless confirm=True, expected domain errors raise ToolError, and the outcome scorer reads the store rather than believing the agent's final claim.
Save this as desk.py. Every runnable sample in the lesson imports it.
# desk.py: the support desk from 10A.7, rebuilt as Inspect tools over a per-sample store (lesson 10B.14)
import copy
import json
from pydantic import Field
from inspect_ai.dataset import Sample
from inspect_ai.model import Model, ModelOutput, get_model
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Scorer, Target, accuracy, scorer
from inspect_ai.solver import TaskState
from inspect_ai.tool import Tool, ToolError, tool
from inspect_ai.util import StoreModel, store_as
# --- 1. The world: the same three orders and two policy docs as 10A.7's SupportWorld.
ORDERS = {
"ORD-1001": {"customer_email": "ana@example.com", "status": "delivered",
"total_cents": 12900, "refunded_cents": 0},
"ORD-1002": {"customer_email": "bo@example.com", "status": "lost_in_transit",
"total_cents": 8450, "refunded_cents": 0},
"ORD-1003": {"customer_email": "cy@example.com", "status": "delivered",
"total_cents": 5200, "refunded_cents": 0},
}
DOCS = {
"refund policy": "Refunds are available within 30 days of delivery for unused "
"items in original packaging.",
"shipping": "Standard shipping takes 3-5 business days; express takes 1-2.",
}
class Desk(StoreModel):
"""The desk's state for ONE sample. Each sample gets a fresh store, which is
Inspect's version of 10A.7's World.reset()."""
orders: dict = Field(default_factory=lambda: copy.deepcopy(ORDERS))
refunds: list[dict] = Field(default_factory=list)
emails_sent: list[dict] = Field(default_factory=list)
# --- 2. The tools. Configuration would go on the factory; model arguments go on execute.
@tool
def orders_get() -> Tool:
async def execute(order_id: str) -> str:
"""Look up one order by its id.
Args:
order_id: The order id, for example ORD-1001.
Returns:
The order as JSON: status, total and the amount already refunded (cents).
"""
order = store_as(Desk).orders.get(order_id)
if order is None:
raise ToolError(f"no such order: {order_id}") # the model reads this and can recover
return json.dumps({"order_id": order_id, **order})
return execute
@tool
def refunds_issue() -> Tool:
async def execute(order_id: str, amount_cents: int, reason: str, confirm: bool = False) -> str:
"""Refund part or all of an order to the original payment method.
Args:
order_id: The order to refund.
amount_cents: Amount in cents, at most the refundable balance.
reason: Short reason, recorded on the refund.
confirm: False (default) returns a preview and moves no money; True issues the refund.
"""
desk = store_as(Desk)
orders = desk.orders
order = orders.get(order_id)
if order is None:
raise ToolError(f"no such order: {order_id}")
if amount_cents <= 0 or amount_cents > order["total_cents"] - order["refunded_cents"]:
raise ToolError("amount_cents must be positive and within the refundable balance")
if not confirm:
return json.dumps({"preview": True, "order_id": order_id, "amount_cents": amount_cents})
order["refunded_cents"] += amount_cents
desk.orders = orders # assign back so the store records it
desk.refunds = desk.refunds + [{"order_id": order_id, "amount_cents": amount_cents,
"reason": reason}]
return json.dumps({"refunded": True, "order_id": order_id, "amount_cents": amount_cents})
return execute
@tool
def docs_search() -> Tool:
async def execute(query: str) -> str:
"""Search the help-centre articles.
Args:
query: Words to look for, for example "refund policy".
"""
q = query.lower().strip()
hits = [{"topic": t, "text": txt} for t, txt in DOCS.items()
if q in t or q in txt.lower()]
return json.dumps({"results": hits})
return execute
@tool
def send_email() -> Tool:
async def execute(to: str, subject: str, body: str) -> str:
"""Send an email to a customer.
Args:
to: Recipient address.
subject: Subject line.
body: Plain-text body.
"""
desk = store_as(Desk)
desk.emails_sent = desk.emails_sent + [{"to": to, "subject": subject}]
return "sent"
return execute
def desk_tools() -> list[Tool]:
return [orders_get(), refunds_issue(), docs_search(), send_email()]
# --- 3. Samples: what to ask, and what the world should look like afterwards.
def desk_samples() -> list[Sample]:
return [
Sample(id="refund-lost", target="8450",
input="Order ORD-1002 never arrived. Please refund it in full.",
metadata={"expect_refund": {"order_id": "ORD-1002", "amount_cents": 8450}}),
Sample(id="policy", target="30 days",
input="What is your refund policy? My order is ORD-1001.",
metadata={"expect_refund": None}),
Sample(id="unknown-order", target="ORD-9999",
input="Refund order ORD-9999 please.",
metadata={"expect_refund": None}),
]
# --- 4. The outcome scorer: read the world, not the model's claims (10A.7 Part 3).
@scorer(metrics=[accuracy()])
def refund_outcome() -> Scorer:
async def score(state: TaskState, target: Target) -> Score:
desk = store_as(Desk)
want = state.metadata["expect_refund"]
got = [(r["order_id"], r["amount_cents"]) for r in desk.refunds]
ok = (got == [(want["order_id"], want["amount_cents"])]) if want else (got == [])
ok = ok and not desk.emails_sent
return Score(value=CORRECT if ok else INCORRECT,
explanation=f"refunds={got} emails={len(desk.emails_sent)}")
return score
# --- 5. Scripting helpers for keyless runs.
M = "mockllm/model"
def call(tool_name: str, content: str | None = None, **args) -> ModelOutput:
"""One scripted assistant turn that calls a tool."""
return ModelOutput.for_tool_call(M, tool_name, args, content=content)
def say(text: str) -> ModelOutput:
"""One scripted assistant turn that only talks."""
return ModelOutput.from_content(M, text)
def scripted(plans: dict[str, list[ModelOutput]]) -> Model:
"""A mock model that replies by (sample, turn). The sample is found by a key
that appears in the first user message; the turn is the number of assistant
messages already in the input. No shared counter, so concurrent samples and
repeated epochs each replay their own plan."""
def model_fn(input, tools, tool_choice, config) -> ModelOutput:
first_user = next(m.text for m in input if m.role == "user")
key = next(k for k in plans if k in first_user)
turn = sum(1 for m in input if m.role == "assistant")
plan = plans[key]
out = plan[turn] if turn < len(plan) else say("(script exhausted)")
return out.model_copy(deep=True) # never hand Inspect the same object twice
return get_model(M, custom_outputs=model_fn, memoize=False)Three design decisions deserve attention before any agent enters the picture.
First, refunds_issue() separates preview from commit. The model can inspect consequences with confirm=False and must then make an explicit committing call. This is both good tool design (08A.6) and good evaluation design: a grader can distinguish an agent that never intended to act from one that merely narrated.
Second, store_as(Desk) is sample-scoped state. Desk is not a global database. The sample-scoped store is Inspect's closest analogue to evalkit's fresh World per task. Because the store is pydantic state, assign mutated nested structures back (desk.orders = orders) when you change them in place, as the refund tool does, so the store event stream records the change faithfully.
Third, the outcome scorer is deliberately narrow. It checks exactly one expected refund and no customer email. It does not reward fluent apologies, correct policy recitation or plausible tool use. That is the division of labour from 10A.7, Part 3: outcome graders measure the world; process graders measure how the agent got there. Part 10 adds the process grader.
Part 2: Custom tools with @tool#
2.1 The factory pattern#
Inspect's custom-tool idiom looks unusual the first time: you decorate a function that returns another function.
from inspect_ai.tool import tool
@tool
def add():
async def execute(x: int, y: int):
"""
Add two numbers.
Args:
x: First number to add.
y: Second number to add.
Returns:
The sum of the two numbers.
"""
return x + y
return executeThe outer function is a tool factory. Call it (add()) and you get a Tool: an async callable plus metadata. Factory arguments are configuration chosen by you; execute arguments are arguments chosen by the model. This separation is what lets one definition produce configured variants such as bash(timeout=30) or a database lookup tool bound to a particular read-only connection.
The verified @tool signature in 0.3.292 is:
# Signatures, not a runnable file
tool(func=None, *, name=None, viewer=None, model_input=None,
parallel=None, max_output=None, prompt=None)| Parameter | Meaning |
|---|---|
name |
Tool name shown to the model. Defaults to the factory function's name. |
viewer |
Renderer used by approval interfaces and the log viewer (3.4). |
model_input |
Hook that rewrites how this tool's earlier results are played back to the model (3.5). |
parallel |
Whether calls in one assistant message may run concurrently. Defaults to False; opt in only after auditing shared state. |
max_output |
Per-tool output byte limit. None uses the run's max_tool_output (16 KiB by default); 0 disables truncation for this tool. |
prompt |
Deprecated: the source says to put all descriptive information in the tool function's docstring instead. Passing it logs a one-time warning. Do not use it. |
2.2 What the model is shown#
The model does not see your Python source. It sees a tool name, a description and a JSON schema built from the inner function's docstring and type annotations. The schema is therefore part of the prompt surface. A vague description is not a documentation problem only; it is a behavioural intervention that changes what the model does.
s01_tool_schema.py prints the schema for the support-desk tools, tries richer annotations, checks the two docstring rules and calls tools directly:
# s01_tool_schema.py: what the model is shown for each tool, and the docstring rules (lesson 10B.14)
import asyncio
from typing import Literal
from inspect_ai.tool import Tool, ToolDef, tool
from desk import desk_tools, orders_get, refunds_issue
# --- 1. The schema the model sees, built from the docstring and the annotations.
for t in desk_tools():
td = ToolDef(t)
print(f"{td.name}: {td.description!r}")
print()
print(ToolDef(refunds_issue()).parameters.model_dump_json(exclude_none=True, indent=1))
# --- 2. Richer annotations: Literal becomes an enum, list[str] an array, a default makes it optional.
@tool
def tickets_search() -> Tool:
async def execute(status: Literal["open", "pending", "closed"], tags: list[str],
limit: int = 10, customer_email: str | None = None) -> str:
"""Search support tickets.
Args:
status: Ticket status to match.
tags: Every ticket returned has all of these tags.
limit: Maximum number of tickets to return.
customer_email: Only tickets from this customer.
"""
return "[]"
return execute
for name, prop in ToolDef(tickets_search()).parameters.properties.items():
print(f"\n{name}: {prop.model_dump_json(exclude_none=True, exclude={'description'})}", end="")
print("\nrequired:", ToolDef(tickets_search()).parameters.required)
# --- 3. The rules: a docstring is enforced, an annotation is not.
@tool
def no_docstring() -> Tool:
async def execute(order_id: str) -> str:
return order_id
return execute
@tool
def no_annotation() -> Tool:
async def execute(order_id) -> str:
"""Echo an order id.
Args:
order_id: The order id.
"""
return order_id
return execute
try:
ToolDef(no_docstring())
except ValueError as e:
print("\nno docstring ->", type(e).__name__ + ":", e)
schema = ToolDef(no_annotation()).parameters.properties["order_id"]
print("no annotation -> accepted; JSON type:", schema.type, "| description:", schema.description)
# --- 4. A tool is an async callable: unit-test it without a model.
async def unit_test() -> None:
print("\ndirect call:", await orders_get()(order_id="ORD-1002"))
print("preview :", await refunds_issue()(order_id="ORD-1002", amount_cents=8450, reason="lost"))
asyncio.run(unit_test())orders_get: 'Look up one order by its id.'
refunds_issue: 'Refund part or all of an order to the original payment method.'
docs_search: 'Search the help-centre articles.'
send_email: 'Send an email to a customer.'
{
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The order to refund."
},
"amount_cents": {
"type": "integer",
"description": "Amount in cents, at most the refundable balance."
},
"reason": {
"type": "string",
"description": "Short reason, recorded on the refund."
},
"confirm": {
"type": "boolean",
"description": "False (default) returns a preview and moves no money; True issues the refund.",
"default": false
}
},
"required": [
"order_id",
"amount_cents",
"reason"
],
"additionalProperties": false
}
status: {"type":"string","enum":["open","pending","closed"]}
tags: {"type":"array","items":{"type":"string"}}
limit: {"type":"integer","default":10}
customer_email: {"anyOf":[{"type":"string"},{"type":"null"}]}
required: ['status', 'tags']
no docstring -> ValueError: Description not provided for tool function 'no_docstring'
no annotation -> accepted; JSON type: None | description: The order id.
direct call: {"order_id": "ORD-1002", "customer_email": "bo@example.com", "status": "lost_in_transit", "total_cents": 8450, "refunded_cents": 0}
preview : {"preview": true, "order_id": "ORD-1002", "amount_cents": 8450}Read the schema carefully. The docstring summary became the tool description; each Google-style Args: entry became the parameter description; int became integer, str became string, bool became boolean; parameters without defaults are in required; and additionalProperties is false. Richer types survive in a useful form: Literal becomes enum, list[str] becomes an array with item type, a default makes a parameter optional, and str | None becomes an anyOf union.
2.3 The docstring and annotation rules#
The documentation says type annotations and descriptions are required. Version 0.3.292 enforces only half of that:
- No docstring:
ValueError: Description not provided for tool function 'no_docstring'when the tool definition is built. - No parameter annotation: accepted silently. The parameter is emitted with JSON type
None, so the model receives no useful type constraint.
The second behaviour disagrees with the docs, so do not copy it. Always annotate every parameter. For an eval, an untyped argument is not just sloppy: it changes the distribution of calls the model makes and makes schema-validation failures more likely. If several engineers write tools, enforce the rule in review or with a small registration-time test that inspects ToolDef(tool).parameters.
2.4 Write schemas for the model, not for Python purists#
The general rules for writing a schema a model can use (concrete names with units, constraints in the description and enforced in code, a confirm field for destructive actions, compact JSON results, split tools instead of huge polymorphic ones, actionable domain errors) are in 08A.6, and validating input twice is in 08A.7, Part 4. Two of them matter for evaluation in particular. Keep destructive or costly actions behind an explicit field such as confirm, because then the trajectory distinguishes consideration from commitment. And make expected domain failures textual and actionable, because the model's next decision depends on whether "no such order" means fix the id or stop.
2.5 Tool results, including multimodal results#
The documented ToolResult type is a string, number, boolean, a content object (ContentText, ContentImage, ContentAudio, ContentVideo or ContentDocument), or a list of content objects. Return ContentImage (or a list containing one) when the model needs to see rather than read about an image; the built-in view_image() tool is the example.
Python does not stop a tool returning another object. The probe's dict result came back as its string representation, with single quotes:
{'orders': ['ORD-1001'], 'count': 1}Do not rely on that accidental behaviour. Python's repr is not JSON, is not stable as a contract and can encourage the model to copy invalid syntax into later arguments. Return json.dumps(...) for structured data, as desk.py does.
2.6 Errors: ToolError, exceptions and parsing errors#
There are three different failure channels.
| Failure | What Inspect does | What the model can do |
|---|---|---|
raise ToolError("no such order") |
Creates a tool message with error.type == "unknown" and empty text; the sample continues |
Read the message and recover or explain |
| Wrong arguments, unknown tool, schema mismatch | Creates a tool message with error.type == "parsing"; the sample continues |
Correct the call on the next turn |
An unexpected exception such as RuntimeError |
Fails the sample unless the eval's error handling tolerates it | Nothing: the run is over |
ToolError is not the only exception Inspect turns into a recoverable tool message. The documentation lists TimeoutError, PermissionError, UnicodeDecodeError and OutputLimitExceededError besides ToolError. The installed 0.3.292 source (tool_call_error() in inspect_ai/model/_call_tools.py) maps a few more, and each gets its own ToolCallError.type, which is what a trajectory grader or a failure-analysis query reads:
| Raised inside the tool (or by Inspect) | error.type the model and the log see |
|---|---|
ToolError |
unknown (the name is historical: it means "a tool error you raised") |
Bad arguments, unknown tool, schema mismatch; a ValueError about an embedded null byte |
parsing |
TimeoutError (including sandbox timeouts, with any partial output kept) |
timeout |
PermissionError |
permission |
FileNotFoundError |
file_not_found (not in the documented list; shown in s03 below) |
IsADirectoryError |
is_a_directory (not in the documented list) |
UnicodeDecodeError |
unicode_decode |
OutputLimitExceededError, or a limit hit inside an agent wrapped by as_tool() |
limit |
| An approver rejected the call | approval |
| The sandbox became unavailable | sandbox_unavailable |
| Any other exception | none: the sample fails |
Two consequences for evaluation design. First, the FileNotFoundError row means a host-side tool that opens a missing fixture file does not crash the sample: the model is told the file was not found and carries on, so a broken fixture can quietly turn into "the agent could not find the receipt". If a missing file means your harness is broken, catch it and raise RuntimeError. Second, group failure analysis by error.type: a run full of parsing errors is a schema or prompt problem, a run full of timeout errors is an environment problem, and neither is the same finding as "the model reasoned badly". The distinction behind the whole table is right for evaluation: a missing order is behaviour of the world; a crashed ledger connection is a broken eval harness.
s03_tool_errors.py exercises the failure channels, dict conversion, truncation and parallel execution:
# s03_tool_errors.py: tool errors, parsing errors, truncation and parallel calls (lesson 10B.14)
import asyncio
import time
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageAssistant, ModelOutput, get_model
from inspect_ai.solver import generate, use_tools
from inspect_ai.tool import Tool, ToolCall, tool
from desk import M, call, orders_get
@tool
def ledger_balance() -> Tool:
async def execute(account: str) -> str:
"""Read an account balance from the finance ledger.
Args:
account: Ledger account id.
"""
raise RuntimeError("ledger connection lost") # a bug or outage, not something the model can fix
return execute
@tool
def attachment_read() -> Tool:
async def execute(path: str) -> str:
"""Read a file the customer attached to a ticket.
Args:
path: Attachment path, for example tickets/T-104/receipt.pdf.
"""
raise FileNotFoundError(2, "No such file or directory", path) # a built-in Inspect also maps
return execute
@tool
def order_history() -> Tool:
async def execute(customer_email: str) -> str | dict:
"""All orders for a customer, oldest first.
Args:
customer_email: The customer's email address.
"""
if customer_email == "big@example.com":
return "x" * 40_000 # a 40,000-character payload
return {"orders": ["ORD-1001"], "count": 1} # a dict, not a JSON string
return execute
def run(label: str, outputs: list, tools: list, **eval_args) -> None:
model = get_model(M, custom_outputs=outputs, memoize=False)
log = eval(Task(dataset=[Sample(input="help")], solver=react(tools=tools)),
model=model, log_dir="logs/s03", display="none", **eval_args)[0]
s = log.samples[0]
err = s.error.message[:60] if s.error else None
print(f"\n== {label}: log.status={log.status} sample.error={err!r}")
for m in s.messages:
if m.role == "tool":
print(f" {m.function}: error={m.error} text={m.text[:60]!r} len={len(m.text)}")
submit = call("submit", answer="done")
run("uncaught RuntimeError", [call("ledger_balance", account="A1"), submit], [ledger_balance()])
run("wrong argument name", [call("orders_get", id="ORD-1002"), submit], [orders_get()])
run("wrong argument type", [call("orders_get", order_id=1002), submit], [orders_get()])
run("tool that does not exist", [call("orders_lookup", order_id="ORD-1002"), submit], [orders_get()])
run("tool raises FileNotFoundError", [call("attachment_read", path="tickets/T-104/receipt.pdf"), submit],
[attachment_read()])
run("tool returns a dict", [call("order_history", customer_email="ana@example.com"), submit],
[order_history()])
run("40,000 characters, default limit", [call("order_history", customer_email="big@example.com"), submit],
[order_history()])
run("40,000 characters, max_tool_output=2000", [call("order_history", customer_email="big@example.com"), submit],
[order_history()], max_tool_output=2000)
# --- Parallel execution: two calls in ONE assistant turn, through use_tools() + generate().
def make_slow(parallel: bool) -> Tool:
@tool(name="warehouse_check", parallel=parallel)
def warehouse_check() -> Tool:
async def execute(sku: str) -> str:
"""Check stock for one SKU (slow: 0.5 s).
Args:
sku: Stock-keeping unit.
"""
await asyncio.sleep(0.5)
return f"{sku}: 3 in stock"
return execute
return warehouse_check()
two_calls = ChatMessageAssistant(content="Checking both.", model=M, tool_calls=[
ToolCall(id="c1", function="warehouse_check", arguments={"sku": "MUG-RED"}),
ToolCall(id="c2", function="warehouse_check", arguments={"sku": "MUG-BLUE"}),
])
for parallel in (False, True):
model = get_model(M, memoize=False, custom_outputs=[
ModelOutput.from_message(two_calls), ModelOutput.from_content(M, "Both in stock.")])
t0 = time.perf_counter()
log = eval(Task(dataset=[Sample(input="stock?")],
solver=[use_tools(make_slow(parallel)), generate()]),
model=model, log_dir="logs/s03", display="none")[0]
took = time.perf_counter() - t0
results = [m.text for m in log.samples[0].messages if m.role == "tool"]
print(f"\nparallel={parallel}: results in declared order {results}; eval took {took:.1f}s")== uncaught RuntimeError: log.status=error sample.error="RuntimeError('ledger connection lost')"
== wrong argument name: log.status=success sample.error=None
orders_get: error=ToolCallError(type='parsing', message="Found 2 validation errors parsing tool input arguments:\n- 'order_id' is a required property\n- Additional properties are not allowed ('id' was unexpected)") text='' len=0
== wrong argument type: log.status=success sample.error=None
orders_get: error=ToolCallError(type='parsing', message="Found 1 validation errors parsing tool input arguments:\n- 1002 is not of type 'string'") text='' len=0
== tool that does not exist: log.status=success sample.error=None
orders_lookup: error=ToolCallError(type='parsing', message='Tool orders_lookup not found') text='' len=0
== tool raises FileNotFoundError: log.status=success sample.error=None
attachment_read: error=ToolCallError(type='file_not_found', message="File 'tickets/T-104/receipt.pdf' was not found.") text='' len=0
== tool returns a dict: log.status=success sample.error=None
order_history: error=None text="{'orders': ['ORD-1001'], 'count': 1}" len=36
== 40,000 characters, default limit: log.status=success sample.error=None
order_history: error=None text='\nThe output of your call to order_history was too long to be' len=16524
== 40,000 characters, max_tool_output=2000: log.status=success sample.error=None
order_history: error=None text='\nThe output of your call to order_history was too long to be' len=2140
parallel=False: results in declared order ['MUG-RED: 3 in stock', 'MUG-BLUE: 3 in stock']; eval took 1.1s
parallel=True: results in declared order ['MUG-RED: 3 in stock', 'MUG-BLUE: 3 in stock']; eval took 0.6sNotice three things. First, the wrong-argument and unknown-tool cases are recoverable parsing errors, not hallucinated Python exceptions. Second, the uncaught RuntimeError put the whole log in error status. If a tool failure is part of the environment you want the agent to handle, raise ToolError. If it means the eval itself cannot be trusted, raise an ordinary exception and let the sample fail loudly. Third, the FileNotFoundError case was recoverable (file_not_found) although no code in the tool asked for that: Inspect's own mapping decided it.
2.7 Output size and truncation#
Tool results are truncated at GenerateConfig.max_tool_output, 16 KiB by default, unless the tool sets its own max_output. The notice is part of the text shown to the model. In the probe, a 40,000-character result became about 16.5k characters including the notice; with max_tool_output=2000, it became about 2.1k.
Truncation is a safety valve, not a retrieval strategy: an agent cannot tell whether the missing middle held the decisive line, and 08A.6, Part 3 covers designing results with pagination and handles instead (08A.7, Part 6 shows head-and-tail truncation and signed cursors). Use @tool(max_output=0) only for payload tools whose result must be complete. Inspect itself does this for submission and agent-delegation tools; it is rarely right for file or command output.
2.8 Parallel tool calls#
A model may request several tool calls in one assistant turn. By default Inspect executes them serially in declared order. @tool(parallel=True) opts a tool into concurrent execution. A batch mixing serial and parallel calls forms concurrent stages separated by serial barriers, and results are spliced back in the model's declared order. A ToolError does not cancel siblings; an unexpected exception does.
The probe's two stock checks each slept for half a second. Serial execution took about 1.1 seconds for the whole tiny eval and parallel about 0.6 seconds. Treat those numbers as evidence of overlap, not as a benchmark: eval startup dominates at this scale.
Parallelism is a correctness property before it is a speed feature. Do not mark a tool parallel if calls can mutate shared state, use one non-reentrant connection, write the same file, or depend on ordering. Built-in bash() and python() are parallel because separate executions are independent; stateful bash_session() is serial. The model remains responsible for sequencing calls when one depends on another's result.
2.9 Stateful tools, instances and tool_state_scope#
Stateless tools are easiest to grade, but real agents often need state: a shell session, a memory directory, a ticket draft, a browser-like workspace. Inspect's pattern is:
- define a Pydantic
StoreModel; - read it with
store_as(Model, instance=...)inside the tool; - pass an instance through the tool factory when callers need separate named state;
- use
tool_state_instance(instance)soinstance=Nonerespects the currenttool_state_scope().
s20_state_scope.py demonstrates the mechanism with two workers running concurrently. Neither worker passes an explicit instance; each runs inside its own scope.
# s20_state_scope.py: per-instance stateful tools and tool_state_scope (lesson 10B.14)
from pydantic import Field
from inspect_ai import Task, eval
from inspect_ai.agent import react, run
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model
from inspect_ai.solver import Generate, Solver, TaskState, solver
from inspect_ai.tool import Tool, tool
from inspect_ai.util import StoreModel, collect, store_as, tool_state_instance, tool_state_scope
from desk import M, call
class CounterState(StoreModel):
count: int = Field(default=0)
@tool
def counter(instance: str | None = None) -> Tool:
async def execute(label: str) -> str:
"""Increment this counter and read it back.
Args:
label: A short label included in the result.
"""
state = store_as(CounterState, instance=tool_state_instance(instance))
state.count = state.count + 1
return f"{label}: count={state.count}"
return execute
print("outside a scope, the default instance is:", tool_state_instance(None))
with tool_state_scope("worker-a"):
print("inside worker-a, the default instance is:", tool_state_instance(None))
with tool_state_scope("inner"):
print("nested scopes join with '/':", tool_state_instance(None))
worker_a = react(name="worker_a", prompt="You are worker A.", tools=[counter()])
worker_b = react(name="worker_b", prompt="You are worker B.", tools=[counter()])
def scripted_model():
def fn(input, tools, tool_choice, config):
who = "A" if "worker A" in input[0].text else "B"
turn = sum(1 for m in input if m.role == "assistant")
if turn < 2:
return call("counter", label=f"worker {who}")
return call("submit", answer=f"worker {who} finished")
return get_model(M, custom_outputs=fn, memoize=False)
@solver
def two_workers() -> Solver:
async def solve(state: TaskState, generate: Generate) -> TaskState:
async def one(agent, scope_name: str):
with tool_state_scope(scope_name): # everything run in this task sees the scope
return await run(agent, state.messages)
a, b = await collect(one(worker_a, "worker-a"), one(worker_b, "worker-b"))
state.metadata["worker_a"] = a.output.completion
state.metadata["worker_b"] = b.output.completion
return state
return solve
log = eval(Task(dataset=[Sample(input="Count two ticks in each worker.")], solver=two_workers()),
model=scripted_model(), log_dir="logs/s20", display="none")[0]
s = log.samples[0]
print("\nstore after two concurrent workers:")
for key in sorted(s.store):
if key.startswith("CounterState"):
print(f" {key}: {s.store[key]}")
print("worker completions:", s.metadata["worker_a"], "|", s.metadata["worker_b"])outside a scope, the default instance is: None
inside worker-a, the default instance is: @worker-a
nested scopes join with '/': @worker-a/inner
store after two concurrent workers:
CounterState:@worker-a:count: 2
CounterState:@worker-a:instance: @worker-a
CounterState:@worker-b:count: 2
CounterState:@worker-b:instance: @worker-b
worker completions: tool call for tool submit
worker A finished | tool call for tool submit
worker B finishedThe store now contains CounterState:@worker-a and CounterState:@worker-b, each with count 2. Outside a scope the default instance would have been shared. Nested scopes join with /, and instances beginning with @ are reserved for scopes.
Use this whenever concurrent agents in one sample have private working memory or shells. Built-in stateful tools follow the same convention: memory(instance=...), bash_session(instance=...) and skill(instance=...). An explicit instance is still shared wherever it is passed; a scope only supplies the default. And repeat the warning from Part 1: these are grading and isolation-of-state mechanisms, not security boundaries.
2.10 Unit-testing tools before evaluating agents#
Tools are ordinary async callables once constructed, so test them as ordinary code before putting a model in the loop. The direct calls at the end of s01 show the shape: await orders_get()(order_id="ORD-1002"). For store-backed tools, prefer tests inside a small eval or a store-aware harness so you test the same lifecycle the agent will use. At minimum test:
- the happy path and the exact result format;
- every expected domain error and whether it is a
ToolError; - boundary values, especially amounts and identifiers;
- output size on large records;
- concurrent calls if
parallel=True; - state reset and instance separation if the tool is stateful.
This is the same test pyramid as 03.10: make the deterministic parts boringly reliable, then evaluate the model's use of them. A wrong tool implementation is not an agent failure, but it will masquerade as one in every transcript.
Part 3: Adapting tools and putting them in front of a model#
Deep-dive
3.1 ToolDef: a tool definition without the decorator#
@tool is convenient when you control the function's docstring. ToolDef is the lower-level object Inspect uses everywhere, and it is useful when a function already exists, when descriptions are generated, or when you want to inspect a built-in tool.
# Shape of the API (signatures, not a runnable file)
ToolDef(tool, name=None, description=None, parameters=None,
parallel=None, viewer=None, model_input=None,
max_output=None, options=None)tool must be annotated. parameters may be a mapping of parameter name to description or an explicit ToolParams schema. A ToolDef can be passed anywhere a Tool can: use_tools(), state.tools, or react(tools=...). ToolDef(existing_tool) introspects an existing tool and can override metadata; ToolDef.as_tool() converts the definition back into a Tool for interfaces that require one. Do not confuse that method with inspect_ai.agent.as_tool(), which wraps an agent as a tool in Part 9.
s04_tooldef.py covers the adaptation layer in one run:
# s04_tooldef.py: ToolDef, tool_with(), ToolParams with **kwargs, and tool views (lesson 10B.14)
import asyncio
from inspect_ai.tool import (Tool, ToolCall, ToolCallContent, ToolCallView, ToolCallViewer,
ToolDef, ToolParam, ToolParams, bash, tool, tool_with)
from desk import docs_search
# --- 1. A tool from a plain async function: no decorator, no docstring, but annotations required.
async def shipping_eta(postcode: str, express: bool) -> str:
return "1-2 business days" if express else "3-5 business days"
eta = ToolDef(shipping_eta, name="shipping_eta",
description="Estimated delivery time to a postcode.",
parameters={"postcode": "UK postcode, e.g. SW1A 1AA.",
"express": "True for express shipping."})
print("ToolDef from a function:", eta.name, "|", eta.description, "|", list(eta.parameters.properties))
# --- 2. tool_with() renames or re-describes a tool IN PLACE.
original = docs_search()
renamed = tool_with(original, name="help_centre_search",
description="Search help-centre articles. Use before answering policy questions.")
print("\ntool_with: renamed ->", ToolDef(renamed).name, "| original object now ->", ToolDef(original).name,
"| same object:", renamed is original)
fresh = docs_search() # build a new instance for each variant
print("a fresh instance keeps its own name ->", ToolDef(fresh).name)
# --- 3. Arguments chosen by the model at run time: an explicit schema plus **kwargs.
async def tickets_filter(query: str, **filters: str) -> str:
return f"query={query!r} filters={filters}"
filter_def = ToolDef(
tool=tickets_filter, name="tickets_filter", description="Search tickets with optional filters.",
parameters=ToolParams(properties={
"query": ToolParam(type="string", description="Free-text query."),
"status": ToolParam(type="string", description="open | pending | closed", enum=["open", "pending", "closed"]),
"assignee": ToolParam(type="string", description="Agent email."),
}, required=["query"]),
)
print("\nkwargs tool schema:", filter_def.parameters.model_dump_json(exclude_none=True))
print("called with a filter:", asyncio.run(filter_def.tool(query="refund", status="open")))
# --- 4. A tool view: how approvers and the log viewer render a call.
def refund_viewer() -> ToolCallViewer:
def viewer(call: ToolCall) -> ToolCallView:
a = call.arguments
verb = "ISSUE" if a.get("confirm") else "preview"
md = f"**{verb} refund** of {a.get('amount_cents', 0) / 100:.2f} on `{a.get('order_id')}`"
return ToolCallView(call=ToolCallContent(title="Refund", format="markdown", content=md))
return viewer
@tool(viewer=refund_viewer())
def refunds_issue_viewed() -> Tool:
async def execute(order_id: str, amount_cents: int, confirm: bool = False) -> str:
"""Refund an order.
Args:
order_id: Order to refund.
amount_cents: Amount in cents.
confirm: True moves money; False previews.
"""
return "ok"
return execute
view = ToolDef(refunds_issue_viewed()).viewer(
ToolCall(id="c1", function="refunds_issue_viewed",
arguments={"order_id": "ORD-1002", "amount_cents": 8450, "confirm": True}))
print("\nrendered view:", view.call.content)
# --- 5. Built-in tools have their own parameter names: read them, do not guess.
print("\nbash() parameters:", list(ToolDef(bash()).parameters.properties))ToolDef from a function: shipping_eta | Estimated delivery time to a postcode. | ['postcode', 'express']
tool_with: renamed -> help_centre_search | original object now -> help_centre_search | same object: True
a fresh instance keeps its own name -> docs_search
kwargs tool schema: {"type":"object","properties":{"query":{"type":"string","description":"Free-text query."},"status":{"type":"string","description":"open | pending | closed","enum":["open","pending","closed"]},"assignee":{"type":"string","description":"Agent email."}},"required":["query"],"additionalProperties":false}
called with a filter: query='refund' filters={'status': 'open'}
rendered view: **ISSUE refund** of 84.50 on `ORD-1002`
bash() parameters: ['command']3.2 tool_with(): renaming in place#
tool_with(tool, name=..., description=..., parameters=...) rewrites metadata on the same tool object. The probe makes the consequence visible: renamed is original is True, and the original object now has the new name. If you need a normal and a strict variant of one tool, call the factory twice and adapt the copies; do not adapt one shared object twice.
This matters in evals because tool descriptions are experimental variables. tool_with() is a practical way to A/B test "Search help-centre articles" against "Use before answering any policy question" without copying implementation code. Record the variant in task metadata or tags, because the log otherwise shows only the final description, not your experiment's intention.
3.3 ToolParams and model-chosen extra arguments#
Python *args and **kwargs are not inferred into a schema. If the model may choose extra filter fields, write the schema explicitly with ToolParams and ToolParam. In the probe, tickets_filter(query, status=...) reaches Python as query='refund' plus filters={'status': 'open'} because the implementation accepts **filters.
additionalProperties controls whether arguments outside the schema are accepted. The default is false, which is usually what you want in an eval: wrong keys become parsing errors the model can correct instead of silently ignored input. Loosen it deliberately for genuinely open-ended filter or metadata objects, and validate the result inside the tool.
3.4 Tool views: how humans see a call#
A tool view controls how a call is rendered for approval and in the log viewer. It does not change execution and does not change what the model receives. The types are small:
# Shape of the API (signatures, not a runnable file)
ToolCallViewer = Callable[[ToolCall], ToolCallView]
ToolCallView(context=None, call=None)
ToolCallContent(title=None, format="text", content="") # format may also be "markdown"The probe renders a refund as a markdown summary: **ISSUE refund** of 84.50 on \ORD-1002``. That is much easier for a human approver to audit than a raw JSON object. Built-in command tools use a code viewer for the same reason.
Two engineering rules follow. First, keep viewers total: if they raise while approval is deciding whether to show a call, the call can be rejected. Second, read the tool's real schema. The approval documentation's illustrative viewer uses cmd, but the built-in bash() parameter is command, as the probe prints. ToolDef(bash()).parameters is the reliable source for your installed version.
3.5 model_input: replaying old results differently#
model_input is a specialized hook for tools whose old results should not be replayed verbatim forever. It receives (index, total, content, hints): index is the zero-based position among earlier results for this tool, total is how many such results are in the history, content is the stored result and hints carries provider limitations. Whatever it returns is used only as model input; the transcript and message history still retain the original.
s23_model_input.py runs the hook for real. A queue_snapshot tool returns a long payload, the scripted agent calls it three times, and the hook replays only the newest result in full:
# s23_model_input.py: model_input replays old tool results differently; the transcript keeps them (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model
from inspect_ai.tool import Tool, tool
from desk import M, call
def keep_latest(index: int, total: int, content, hints):
"""Older results become a one-line reminder; the newest is replayed in full."""
print(f" model_input called: index={index} total={total}")
return content if index == total - 1 else f"(older queue snapshot {index + 1} of {total} omitted)"
@tool(model_input=keep_latest)
def queue_snapshot() -> Tool:
async def execute(queue: str) -> str:
"""Return every open ticket in a support queue (large).
Args:
queue: Queue name, for example refunds.
"""
return f"{queue}: " + ", ".join(f"T-{i}" for i in range(100, 160)) # a long payload
return execute
seen: list[list[str]] = []
def fn(input, tools, tool_choice, config):
seen.append([m.text[:44] for m in input if m.role == "tool"])
turn = sum(1 for m in input if m.role == "assistant")
plan = [call("queue_snapshot", queue="refunds"), call("queue_snapshot", queue="refunds"),
call("queue_snapshot", queue="refunds"), call("submit", answer="60 open tickets")]
return plan[turn]
log = eval(Task(dataset=[Sample(input="How many refund tickets are open?")],
solver=react(tools=[queue_snapshot()])),
model=get_model(M, custom_outputs=fn, memoize=False), log_dir="logs/s23", display="none")[0]
s = log.samples[0]
print("\nwhat the model received as tool results on its last turn:")
for text in seen[-1]:
print(" ", repr(text))
print("what the transcript (messages) still holds:")
for m in s.messages:
if m.role == "tool":
print(" ", repr(m.text[:44]), f"len={len(m.text)}") model_input called: index=0 total=1
model_input called: index=0 total=2
model_input called: index=1 total=2
model_input called: index=0 total=3
model_input called: index=1 total=3
model_input called: index=2 total=3
what the model received as tool results on its last turn:
'(older queue snapshot 1 of 3 omitted)'
'(older queue snapshot 2 of 3 omitted)'
'refunds: T-100, T-101, T-102, T-103, T-104, '
what the transcript (messages) still holds:
'refunds: T-100, T-101, T-102, T-103, T-104, ' len=427
'refunds: T-100, T-101, T-102, T-103, T-104, ' len=427
'refunds: T-100, T-101, T-102, T-103, T-104, ' len=427Read the printout in three steps. The hook runs on every model call, over every earlier result of this tool, so it was called once before the second request, twice before the third and three times before the fourth: index counts from 0 within this tool's results and total is how many there are at that moment. The model's last request carried two one-line placeholders and one full snapshot. And the transcript still holds three full 427-character results, so a grader, an auditor or Inspect View sees exactly what the tool returned. Make the hook cheap and deterministic, because it runs again on every turn.
The built-in computer tool uses this to replace older screenshots with a text placeholder while keeping the latest screenshots. The same pattern fits log tails, large JSON snapshots and expensive media: keep the most recent payload intact, compress older payloads into short textual reminders. Do not use it to hide errors or evidence from the model in a way you would not want replicated in the eval methodology. The transformation is part of the scaffold and belongs in the run description.
3.6 use_tools(), tool_choice and generate(tool_calls=...)#
Agents are not the only way to use tools. You can put them into an ordinary solver chain with use_tools() and drive generation yourself. This is useful for constrained tasks, for tests of individual mechanics, and for understanding what react() automates.
# s05_use_tools.py: tools in a plain solver chain: use_tools(), tool_choice, generate(tool_calls=...) (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import execute_tools, get_model
from inspect_ai.solver import Generate, Solver, TaskState, generate, solver, use_tools
from inspect_ai.tool import ToolFunction
from desk import M, call, orders_get, refunds_issue, say
def model_logging_tool_choice():
"""Always asks for the order first, then answers; prints what each request carried."""
def fn(input, tools, tool_choice, config):
turn = sum(1 for m in input if m.role == "assistant")
print(f" request {turn + 1}: tools={[t.name for t in tools]} tool_choice={tool_choice}")
return call("orders_get", order_id="ORD-1002") if turn == 0 else say("ORD-1002 is lost in transit.")
return get_model(M, custom_outputs=fn, memoize=False)
def run(label: str, solvers: list) -> None:
print(f"== {label}")
log = eval(Task(dataset=[Sample(input="Where is ORD-1002?")], solver=solvers),
model=model_logging_tool_choice(), log_dir="logs/s05", display="none")[0]
s = log.samples[0]
shape = [m.role + ("+calls" if getattr(m, "tool_calls", None) else "") for m in s.messages]
print(f" messages: {shape}\n completion: {s.output.completion!r}")
run("generate() (tool_calls='loop', the default)", [use_tools(orders_get()), generate()])
run("generate(tool_calls='single')", [use_tools(orders_get()), generate(tool_calls="single")])
run("generate(tool_calls='none')", [use_tools(orders_get()), generate(tool_calls="none")])
run("force a tool on turn one, then forbid tools",
[use_tools(orders_get(), tool_choice=ToolFunction(name="orders_get")), generate(tool_calls="single"),
use_tools(tool_choice="none"), generate()])
run("use_tools(..., append=True) adds to the tools already set",
[use_tools(refunds_issue()), use_tools(orders_get(), append=True), generate(tool_calls="none")])
# --- execute_tools(): run the calls in the last assistant message yourself.
@solver
def one_round_by_hand() -> Solver:
async def solve(state: TaskState, generate: Generate) -> TaskState:
state = await generate(state, tool_calls="none") # the model proposes a call
messages, output = await execute_tools(state.messages, state.tools)
print(" execute_tools returned:", [(m.role, m.text[:40]) for m in messages], "| output:", output)
state.messages.extend(messages)
return state
return solve
run("execute_tools() by hand", [use_tools(orders_get()), one_round_by_hand()])== generate() (tool_calls='loop', the default)
request 1: tools=['orders_get'] tool_choice=auto
request 2: tools=['orders_get'] tool_choice=auto
messages: ['user', 'assistant+calls', 'tool', 'assistant']
completion: 'ORD-1002 is lost in transit.'
== generate(tool_calls='single')
request 1: tools=['orders_get'] tool_choice=auto
messages: ['user', 'assistant+calls', 'tool']
completion: 'tool call for tool orders_get'
== generate(tool_calls='none')
request 1: tools=['orders_get'] tool_choice=auto
messages: ['user', 'assistant+calls']
completion: 'tool call for tool orders_get'
== force a tool on turn one, then forbid tools
request 1: tools=['orders_get'] tool_choice=ToolFunction(name='orders_get')
request 2: tools=[] tool_choice=none
messages: ['user', 'assistant+calls', 'tool', 'assistant']
completion: 'ORD-1002 is lost in transit.'
== use_tools(..., append=True) adds to the tools already set
request 1: tools=['refunds_issue', 'orders_get'] tool_choice=auto
messages: ['user', 'assistant+calls']
completion: 'tool call for tool orders_get'
== execute_tools() by hand
request 1: tools=['orders_get'] tool_choice=auto
execute_tools returned: [('tool', '{"order_id": "ORD-1002", "customer_email')] | output: None
messages: ['user', 'assistant+calls', 'tool']
completion: 'tool call for tool orders_get'The verified pieces are:
use_tools(*tools, tool_choice="auto", append=False): replace the current tools by default;append=Trueadds to them. Tools may beTool,ToolDef, aToolSourcesuch as MCP, or sequences of those.tool_choice:"auto","any","none", orToolFunction(name="...")to force one named function. In the probe, forcingorders_geton the first turn and then setting"none"made the next request carrytools=[].generate(tool_calls="loop")(the default): execute calls and keep generating until the model stops calling tools or a limit intervenes.generate(tool_calls="single"): execute the calls in this one response but do not automatically generate again. The final completion is the assistant text that accompanied the call: empty or the model's own prose with a real model, andmockllm's fillertool call for tool <name>in the outputs here (the artefact from 1.5).generate(tool_calls="none"): leave proposed calls unresolved. This is the mode to use when your own solver will inspect, filter or execute them.execute_tools(messages, tools, ...): execute the calls in the last assistant message. It returns(messages, output);outputis normallyNone, but a handoff can produce a replacement output. Use it rather than the deprecatedcall_tools(), which does not understand handoffs.
For most product evals, use react() rather than reconstructing this loop. The lower-level interface is nevertheless essential when the research question is the loop itself: filtering unsafe calls, adding a critic, changing termination logic or comparing scaffolds.
Part 4: The standard tool catalogue#
Reference
4.1 Four families, not one toolbox#
inspect_ai.tool exports a broad catalogue, but it is easier to reason about as four families:
| Family | Tools | Evaluation meaning |
|---|---|---|
| Sandbox execution and files | bash, python, bash_session, text_editor, computer, read_file, list_files, grep, view_image |
The agent acts on a contained environment. Final-state scorers can inspect that environment. |
| Provider-run capability | web_search with internal providers, native code_execution |
The capability is part of generation at the provider. Inspect does not observe each action as a normal tool event. |
| In-process agentic tools | think, memory, todo_write, update_plan, skill |
Scaffold state and reasoning aids. They change behaviour even though no external world changes. |
| Intervention tools | ask_user, notify_user |
Human-in-the-loop interaction. Intervened samples must be flagged before being reported as autonomous results. |
s06_standard_tools.py prints the model-facing parameters and concurrency flag for the catalogue entries that can be constructed without a sandbox or key, proves that web_browser() is gone, and runs the in-process think, todo_write and memory tools keylessly.
# s06_standard_tools.py: the standard catalogue, and the in-process tools that run with no sandbox (lesson 10B.14)
import inspect_ai.tool as T
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.tool import ToolDef
from desk import call, scripted
# --- 1. What each standard tool asks the model for, and whether Inspect may run its calls concurrently.
for name in ["bash", "python", "bash_session", "text_editor", "read_file", "list_files", "grep",
"view_image", "code_execution", "web_search", "think", "memory", "todo_write",
"update_plan", "ask_user", "notify_user"]:
td = ToolDef(getattr(T, name)())
print(f"{name:14} parallel={str(td.parallel):5} params={list(td.parameters.properties)}")
# --- 2. web_browser() is gone.
try:
T.web_browser()
except Exception as e:
print(f"\nweb_browser() -> {type(e).__name__}: {str(e)[:96]}...")
# --- 3. think(), todo_write() and memory() run in the Inspect process: no sandbox, no key.
PLAN = {"ORD-1002": [
call("think", thought="Lost parcel: check the order, then refund in full."),
call("todo_write", todos=[{"content": "Look up ORD-1002", "status": "completed"},
{"content": "Refund 8450 cents", "status": "in_progress"}]),
call("memory", command="create", path="/memories/customers/bo.md",
file_text="bo@example.com: ORD-1002 lost in transit, refund started.\n"),
call("memory", command="view", path="/memories"),
call("submit", answer="Refund started for ORD-1002."),
]}
log = eval(Task(dataset=[Sample(input="ORD-1002 never arrived.")],
solver=react(tools=[T.think(), T.todo_write(), T.memory()])),
model=scripted(PLAN), log_dir="logs/s06", display="none")[0]
s = log.samples[0]
print()
for m in s.messages:
if m.role == "tool":
print(f"{m.function:10} -> {m.text.strip()[:90]!r}")
print("\nstore keys written by the tools:", sorted(k for k in s.store if not k.startswith("Desk")))bash parallel=True params=['command']
python parallel=True params=['code']
bash_session parallel=False params=['action', 'input']
text_editor parallel=False params=['command', 'path', 'file_text', 'insert_line', 'insert_text', 'new_str', 'old_str', 'view_range']
read_file parallel=True params=['file_path', 'offset', 'limit']
list_files parallel=True params=['path', 'depth']
grep parallel=True params=['pattern', 'path', 'glob', 'fixed_strings', 'extended_regexp', 'output_mode']
view_image parallel=True params=['file_path']
code_execution parallel=False params=['code']
web_search parallel=True params=['query']
think parallel=True params=['thought']
memory parallel=True params=['command', 'path', 'file_text', 'old_str', 'new_str', 'insert_line', 'insert_text', 'view_range', 'old_path', 'new_path']
todo_write parallel=True params=['todos', 'explanation']
update_plan parallel=True params=['plan', 'explanation']
ask_user parallel=False params=['message', 'schema']
notify_user parallel=False params=['title', 'message']
web_browser() -> PrerequisiteError: The `web_browser()` tool has been removed. Use `web_search()` for web retrieval, and `computer()...
think -> ''
todo_write -> 'Todo list updated'
memory -> 'File created successfully at: /memories/customers/bo.md'
memory -> 'Here are the files and directories up to 2 levels deep in /memories, excluding hidden item'
store keys written by the tools: ['MemoryStore:dirs', 'MemoryStore:files', 'MemoryStore:instance', 'MemoryStore:seeding_complete']4.2 Command and file tools#
The execution tools are simple at the schema level and complex at the environment level:
| Tool | Model-facing arguments | Behaviour to remember |
|---|---|---|
bash(timeout=None, user=None, sandbox=None, background=False) |
command |
One fresh shell per call. background=True changes the prompt guidance rather than giving you a managed process API. Parallel-safe. |
python(timeout=None, user=None, sandbox=None) |
code |
Runs one Python script; no state persists between calls. Parallel-safe. |
bash_session(timeout=None, wait_for_output=None, user=None, instance=None) |
action, input |
A stateful shell: working directory, environment and process persist. Serial. Use distinct instances for concurrent agents. |
text_editor(timeout=None, user=None) |
command, path, file_text, insert_line, insert_text, new_str, old_str, view_range |
Structured file viewing and editing, shaped after Anthropic's text-editor tool and able to bind natively on Claude. |
read_file, list_files, grep |
paths plus pagination or pattern options | Read-only inspection tools. read_file paginates with offset and limit; grep supports glob, fixed-string and extended-regexp modes. |
view_image |
file_path |
Returns image content to the model. The provider may still reject an unsupported or oversized image at the next model call. |
computer(max_screenshots=1, timeout=180) |
mouse, keyboard and screenshot actions | Desktop control through a sandboxed image. Powerful, slow and hard to grade; use only when the benchmark truly requires a graphical interface. |
All of these need a sandbox for real use, and Docker-backed samples are illustrative here because this lesson never starts a service. 10B.15 explains what the sandbox does and does not isolate. The tool-level point is already important: command output is untrusted model-influenced content. Treat it as data in scorers and reviewers, not as instructions.
4.3 Provider-run search and code execution#
web_search() is not one implementation. With an internal provider it asks the model's own provider to perform search during generation; with an external provider it calls a search service such as Tavily, Exa or Google Programmable Search from the eval side. As of 24 November 2026 the documented internal providers are OpenAI, Anthropic, Gemini, Grok, Mistral and Perplexity; external providers need their own keys. Provider support and model compatibility change quickly, so treat the official page, not this table, as the live source.
The evaluation consequences are sharper than the installation details:
- Comparability. A search-enabled model is a different system from a searchless one, and an Anthropic-native search is not the same retrieval environment as a Tavily-backed search.
- Observability. Provider-run searches do not appear as Inspect tool events in the way host-side calls do. You may see the final answer and citations, but not every query as a controllable call.
- Cost. Several providers bill search or grounding separately from tokens. Record it in cost analysis rather than assuming token usage explains the bill.
- Network claims. A sandbox network policy does not cover provider-side search. Disable the tool explicitly when the eval requires a closed world.
code_execution() has the same split. On providers with a native code tool it runs at the provider and is stateless; otherwise it can fall back to Inspect's sandboxed python() tool. You can disable native providers selectively, for example code_execution(providers={"openai": False}). Decide whether the eval is measuring provider-integrated execution or the agent's use of a controlled environment: those are different claims.
4.4 In-process reasoning, memory and planning tools#
The keyless run shows that think, todo_write and memory really execute without a sandbox:
think(thought=...)returns an empty result. It is a place for explicit reasoning in the transcript, not a substitute for a reasoning model or a hidden scratchpad.todo_write(todos=...)maintains a structured pending/in-progress/completed plan. It can help long tasks and can be pure overhead on simple ones.memory()implements a virtual/memoriesdirectory in the sample store.initial_datacan seed files,readonly=Trueexposes only viewing, and instances separate memory namespaces.
update_plan() is the Codex-style planning tool exported by 0.3.292. It is present in the reference but less prominent in the standard-tools documentation, so prefer todo_write() unless you are deliberately matching a Codex-compatible scaffold.
skill() exposes Agent Skills folders (SKILL.md plus supporting files) to a sandboxed agent and copies them into the sandbox. Skills are packaging for instructions and resources, not executable eval logic by themselves. Version them as part of the scaffold.
4.5 web_browser() is gone#
web_browser() was removed in inspect-ai 0.3.288 and in 0.3.292 always raises PrerequisiteError. Older tutorials that include it are broken. The replacement depends on the need:
- for retrieval, use
web_search()or your own retrieval tool; - for graphical interaction, use
computer(); - for browser automation, run a browser MCP server inside a sandbox with
mcp_server_sandbox()(Part 5).
This is a useful lesson in reading Inspect itself. The package evolves quickly, and tool APIs are part of the eval's reproducibility surface. When a run matters, record the package version and check the CHANGELOG before reusing a tutorial.
4.6 Human-intervention tools#
ask_user() pauses for a structured answer through Inspect's intervention machinery; notify_user() sends a fire-and-forget notification. They are invaluable for long-running or human-in-the-loop studies, but a sample answered or interrupted by a person is not evidence of autonomous capability. Mark it in metadata or filter it before aggregation. The operator protocol and custom-agent opt-in belong to 10B.15, 10.9; here it is enough to know that these tools run in the host and are serial.
4.7 Choosing standard tools for an eval#
| If the eval question is... | Prefer | Avoid |
|---|---|---|
| Can the model use a controlled shell or filesystem? | bash, python, file tools in a sandbox |
Custom wrappers that accidentally run on the host |
| Can it use provider-integrated search? | web_search() with the provider fixed and recorded |
Calling it "closed-book" or comparing it with searchless runs |
| Can it use retrieval you control? | A custom retrieval tool or external web_search provider |
Provider-native search, which changes the corpus and ranking |
| Can it edit code? | text_editor plus sandbox tests as outcome scorer |
Grading only the final prose claim |
| Can it operate a graphical interface? | computer() |
Using it as a substitute for a perfectly good API or DOM-level tool |
| Does long-horizon planning itself matter? | todo_write, memory, possibly skill |
Adding them to every simple eval and confounding the comparison |
The best eval toolbox is usually smaller than the catalogue. Every additional tool is another action the model can misuse, another source of transcript noise and another experimental variable. Start minimal, add a tool when a failure analysis shows the missing capability, and rerun the baseline.
Part 5: MCP tools#
Deep-dive
5.1 What MCP adds#
Inspect's role is narrower than the protocol (see 08E.1 and 08E.2 for that): an MCP server is a ToolSource, a dynamic source of tool definitions. Inspect connects to the server, discovers the tools it offers, presents them to the model and forwards calls over the MCP transport.
That gives you two things ordinary Python tools do not. First, you can reuse an existing server (filesystem, git, browser, database, internal service) rather than wrapping it yourself. Second, the tool surface can live close to the environment it manipulates: a filesystem server inside the same sandbox as the agent, rather than host-side Python reaching into the container.
The verified constructors in 0.3.292 are:
# Signatures, not a runnable file
mcp_server_stdio(*, name=None, command: str, args=None, cwd=None, env=None)
mcp_server_http(*, name=None, url: str, execution="local", authorization=None,
headers=None, timeout=5, sse_read_timeout=300)
mcp_server_sse(...) # deprecated transport; use mcp_server_http()
mcp_server_sandbox(*, name=None, command: str, args=None, cwd=None, env=None,
sandbox=None, timeout=None)
mcp_tools(server, *, tools="all")mcp_tools(server, tools=[...]) selects a subset by exact names or globs. Use it aggressively. A server may expose fifty operations when the eval question needs five; every extra operation increases prompt size, misuse surface and nondeterminism.
5.2 The three transports#
This table summarises only how each transport behaves in Inspect. The transports themselves (stdio, streamable HTTP and how to choose between them) are explained in 08E.1 and 08E.2.
| Transport | Where the server runs | Use it when |
|---|---|---|
mcp_server_stdio() |
A child process on the Inspect host | The server is trusted, local and needs host resources. It is not contained by Inspect. |
mcp_server_http() |
A remote HTTP server | The server already exists as a service. With execution="local" Inspect forwards calls; with execution="remote" the model provider calls it during generation. |
mcp_server_sandbox() |
A stdio process inside an Inspect sandbox | The server touches the same files, git checkout or code environment the agent is meant to act on. This is Inspect's own addition to the usual MCP transports. |
mcp_server_sse() exists for the older Server-Sent Events transport but is deprecated upstream; write new code with mcp_server_http().
The following filesystem example is illustrative: running it requires a Docker sandbox and the MCP server package, neither of which this keyless lesson starts.
# mcp_filesystem_task.py (illustrative: needs Docker and the filesystem MCP server)
from inspect_ai import Task
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.tool import mcp_server_sandbox
filesystem = mcp_server_sandbox(
name="filesystem",
command="npx",
args=["--offline", "@modelcontextprotocol/server-filesystem", "/workspace"],
)
task = Task(
dataset=[Sample(input="Read /workspace/README.txt and report the project name.")],
solver=react(tools=[filesystem]),
scorer=includes(),
sandbox="docker",
)Two details are production practice rather than decoration. The server is pre-installed in the image and run with --offline, so the eval does not depend on npm resolving packages mid-run. And the server root is explicitly /workspace, not the container's whole filesystem. Pin the server package version in the image and record it in task metadata: an MCP server is part of the scaffold.
5.3 Local stdio servers are host processes#
A stdio server is convenient for development because it is only a command, and it is the one MCP transport you can run with no key, no Docker and no network. This sample runs for real. It needs the optional mcp package (uv add mcp, no version pin). s21_mcp_server.py is a three-tool server over the desk's orders, written with the mcp package's server class. In mcp 2.x that class is MCPServer in mcp.server.mcpserver; in 1.x it was FastMCP in mcp.server.fastmcp, so an older tutorial's import fails on a fresh install.
# s21_mcp_server.py: a keyless stdio MCP server over the desk's three orders (lesson 10B.14)
import json
from mcp.server.mcpserver import MCPServer
from desk import ORDERS
server = MCPServer("orders")
@server.tool()
def search_orders(customer_email: str) -> str:
"""Find the order ids that belong to a customer email address."""
ids = [oid for oid, o in ORDERS.items() if o["customer_email"] == customer_email]
return json.dumps({"order_ids": ids})
@server.tool()
def get_order(order_id: str) -> str:
"""Return one order as JSON: status and total in cents."""
order = ORDERS.get(order_id)
if order is None:
raise ValueError(f"no such order: {order_id}")
return json.dumps({"order_id": order_id, "status": order["status"], "total_cents": order["total_cents"]})
@server.tool()
def delete_order(order_id: str) -> str:
"""Delete an order permanently."""
return "deleted"
if __name__ == "__main__":
server.run(transport="stdio")s21_mcp_stdio.py launches it as a child process with mcp_server_stdio(), prints everything the server advertises, keeps only the read-only tools with the globs search* and get*, prints what the model will be offered, and runs react() against it with mockllm scripted to call get_order. Save both next to desk.py.
# s21_mcp_stdio.py: react() over a real stdio MCP server, scripted with mockllm (lesson 10B.14)
import asyncio
import sys
from pathlib import Path
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.tool import ToolDef, mcp_connection, mcp_server_stdio, mcp_tools
from desk import call, scripted
here = Path(__file__).parent
orders = mcp_server_stdio(name="orders", command=sys.executable, args=[str(here / "s21_mcp_server.py")],
cwd=str(here)) # the server is a child process of this one
read_only = mcp_tools(orders, tools=["search*", "get*"]) # globs: delete_order is never offered
everything = mcp_tools(orders) # tools="all", the default
async def discover(source):
async with mcp_connection(source): # discovery needs an open connection
defs = [ToolDef(t) for t in await source.tools()]
return [(d.name, list(d.parameters.properties)) for d in defs]
print("advertised by the server:", [name for name, _ in asyncio.run(discover(everything))])
print("offered to the model:", asyncio.run(discover(read_only)))
plan = {"ORD-1002": [call("get_order", order_id="ORD-1002"), call("submit", answer="lost_in_transit")]}
log = eval(Task(dataset=[Sample(input="What is the status of ORD-1002?", target="lost_in_transit")],
solver=react(tools=[read_only]), scorer=includes()),
model=scripted(plan), log_dir="logs/s21", display="none")[0]
s = log.samples[0]
print("status:", log.status, "| score:", s.scores["includes"].value)
for e in s.events:
if e.event == "tool":
result = e.result if isinstance(e.result, str) else " ".join(c.text for c in e.result)
print("tool event:", e.function, e.arguments, "->", result)advertised by the server: ['search_orders', 'get_order', 'delete_order']
offered to the model: [('search_orders', ['customer_email']), ('get_order', ['order_id'])]
status: success | score: C
tool event: get_order {'order_id': 'ORD-1002'} -> {"order_id": "ORD-1002", "status": "lost_in_transit", "total_cents": 8450}
tool event: submit {'answer': 'lost_in_transit'} -> lost_in_transitRead the output as four facts. The server advertised three tools but the model was offered two: delete_order was filtered out by mcp_tools(..., tools=["search*", "get*"]) before any model saw it. (A scripted call to delete_order under these globs comes back as ToolCallError(type='parsing', message='Tool delete_order not found'): the filter removes the capability rather than asking the model not to use it.) Discovery needs an open connection (mcp_connection(), 5.4), which react() opens for you during a run. The model's call travelled over the stdio transport and came back as content: the tool event records get_order with its arguments and the server's JSON. And the whole path is deterministic and keyless because the model is scripted; only the tool side is real.
The same shape works for a server you did not write, for example command="python", args=["ticket_mcp_server.py"], env={"TICKET_DB": "fixtures/tickets.db"}.
The important point is the trust boundary. This server runs in the Inspect host process tree with the eval's permissions. env can pass fixture paths or configuration, but never put secret values in sample metadata or prompts. If the server manipulates files or executes code, prefer the sandbox transport in an eval of an untrusted or adversarial model.
For a server that only reads a fixed fixture database, local stdio may be acceptable. For a server that shells out, writes files or accesses internal network resources, treat it with the same caution as custom host-side tool code.
5.4 Connection lifecycle: mcp_connection()#
react() automatically keeps an MCP connection open for the duration of its loop. Custom agents that call generate() directly should do the same with mcp_connection(tools), otherwise every call can mean reconnecting to a stateful server:
# Shape inside a custom agent; the full corrected loop is in Part 8
async with mcp_connection(tools):
state.output = await get_model().generate(input=state.messages, tools=tools)
# execute the requested tools while the same MCP sessions stay openSince 0.3.262 (CHANGELOG, 2 September 2026), sessions are scoped per async task rather than per sample, and a shared ToolSource no longer serves one sample's tools to another. A handoff or other sub-agent turn gets its own connection to a local server rather than reusing the parent's live session, and tools are resolved fresh on each call. That is safer for concurrent agents, but it also means connection setup is part of the cost of delegation. Measure it before drawing conclusions about multi-agent overhead.
5.5 Remote execution and the observability trap#
mcp_server_http(..., execution="remote") is different in kind. The provider calls the remote MCP server during generation, like provider-native search or code execution. Inspect cannot see or approve the individual MCP calls. For that reason, 0.3.292 refuses to send a remote MCP server while any approval policy is active.
# remote_mcp_example.py (illustrative: needs a provider key and a real server)
import os
from inspect_ai.tool import mcp_server_http
remote_docs = mcp_server_http(
name="docs",
url="https://mcp.example.com/docs",
execution="remote",
authorization=os.environ.get("DOCS_MCP_TOKEN"),
)Headers, including authorization, are sent to the provider and are not recorded in the log. That protects the token, but it also means the log cannot prove exactly which server configuration was used. Record non-secret identifiers (server name, deployment version, schema hash) in task metadata yourself.
Use remote execution only when the research question includes the provider-managed integration. For most product evals, local execution gives better evidence: calls appear as tool events, approval can review them, and failures are visible.
5.6 Evaluating an MCP-using agent honestly#
MCP adds a moving part, so validate it as part of the measuring instrument before blaming or praising the model:
- Snapshot the offered schema. At startup, list each tool's name, description and parameter schema and write a hash into task metadata. MCP tools are dynamic; a server upgrade is a scaffold change.
- Test the server without a model. Call each operation with fixtures. Check error shape, result size, pagination and timeouts.
- Fix the data. Point the server at fixture files or a fixture database. If the world changes underneath the eval, replicate it or snapshot it.
- Record the transport and server version.
stdio, local HTTP, sandbox stdio and remote execution are different experimental conditions. - Grade end state where possible. For a filesystem or git server, inspect the final sandbox rather than trusting the agent's report (the pattern is in Part 10 and the sandbox mechanics in 10B.15).
- Inspect failures by layer. MCP connection failure, tool discovery failure, schema parsing failure, domain error and model misuse are different failures. Do not collapse them into "the agent failed".
- Keep approval assumptions straight. Local MCP calls can be approved; remote provider-executed calls cannot. Provider-run capabilities bypass sandbox network restrictions.
The MCP eval guidance in 10A.7, 7.5 remains the conceptual checklist. This section has shown where Inspect's implementation plugs in; the key evaluation rule is unchanged: the server is part of the measuring instrument, so version and validate it like one.
Part 6: Agents in Inspect: the protocol and a first run#
6.1 What an agent is#
An agent in Inspect is deliberately smaller than a solver. Its protocol is one async function:
# Shape of the API (signatures, not a runnable file)
async def execute(state: AgentState, *args) -> AgentState:
...AgentState has only two fields: messages, the conversation history, and output, the latest ModelOutput. That narrow state is what lets the same object be used as a solver, run inside a workflow, wrapped as a tool or delegated to in a handoff. A solver owns a whole TaskState; an agent owns a conversation.
Register an agent factory with @agent:
# Shape of the API (signatures, not a runnable file)
agent(func=None, *, name=None, description=None)
agent_with(agent, *, name=None, description=None)
is_agent(obj)There are two layers of parameters, and confusing them is a common bug:
- Factory parameters are fixed when the object is constructed:
policy_agent(max_searches=3). They configure the agent implementation. - Agent parameters are extra arguments on
executebesidesstate:tone="friendly".as_tool()andhandoff()expose them to the supervisor model;as_solver()andrun()can curry them.
agent_with() is the agent counterpart of tool_with(): it rewrites the name or description of an existing agent in place, so the same caution applies (build a fresh agent for each variant). is_agent() tells you whether an object is a registered agent, which matters when your own code accepts either a solver or an agent.
The description matters. When the agent is delegated to, description becomes the tool description a supervisor reads when deciding whether to use it. A missing or vague description is therefore not merely untidy: it changes routing behaviour.
6.2 The support desk as a react() agent#
Before taking the API apart, watch a complete agent eval run. s02_first_agent.py puts the support desk tools from Part 1 inside react(), scripts the mock model through three different tickets and scores the resulting world:
# s02_first_agent.py: the support desk as a react() agent, run keyless (lesson 10B.14)
from collections import Counter
from inspect_ai import Task, eval
from inspect_ai.agent import react
from desk import call, desk_samples, desk_tools, refund_outcome, scripted
PLANS = {
"ORD-1002": [
call("orders_get", "Let me look the order up.", order_id="ORD-1002"),
call("refunds_issue", "It was lost, so a full refund is due.",
order_id="ORD-1002", amount_cents=8450, reason="lost in transit", confirm=True),
call("submit", "Done.", answer="Refunded 8450 cents to the original payment method."),
],
"refund policy": [
call("docs_search", query="refund policy"),
call("submit", answer="Refunds are available within 30 days of delivery."),
],
"ORD-9999": [
call("orders_get", order_id="ORD-9999"),
call("submit", answer="I could not find order ORD-9999. Could you check the number?"),
],
}
task = Task(dataset=desk_samples(),
solver=react(prompt="You are a support agent for an online shop.", tools=desk_tools()),
scorer=refund_outcome())
log = eval(task, model=scripted(PLANS), log_dir="logs/s02", display="none")[0]
print("status:", log.status, "| accuracy:", log.results.scores[0].metrics["accuracy"].value)
for s in log.samples:
sc = s.scores["refund_outcome"]
print(f" {s.id:14} {sc.value} {sc.explanation}")
s = next(x for x in log.samples if x.id == "refund-lost")
print("\nMESSAGES (what the model saw, and what scorers read):")
for m in s.messages:
calls = [f"{c.function}({c.arguments})" for c in (getattr(m, "tool_calls", None) or [])]
text = m.text.replace("\n", " | ")[:70]
print(f" [{m.role:9}] {text!r}" + (f" calls={calls}" if calls else ""))
print("\nEVENTS (the full record):", dict(Counter(e.event for e in s.events)))
for e in s.events:
if e.event == "tool":
print(f" tool {e.function}{e.arguments} error={e.error}")
print("\noutput.completion:", repr(s.output.completion))
print("store:", {k: v for k, v in s.store.items() if "refunds" in k})
u = log.samples[2]
print("\nunknown-order tool message:", [ (m.function, m.error) for m in u.messages if m.role == "tool"])status: success | accuracy: 1.0
policy C refunds=[] emails=0
refund-lost C refunds=[('ORD-1002', 8450)] emails=0
unknown-order C refunds=[] emails=0
MESSAGES (what the model saw, and what scorers read):
[system ] 'You are a support agent for an online shop. | | | You are a helpful '
[user ] 'Order ORD-1002 never arrived. Please refund it in full.'
[assistant] 'Let me look the order up.' calls=["orders_get({'order_id': 'ORD-1002'})"]
[tool ] '{"order_id": "ORD-1002", "customer_email": "bo@example.com", "status":'
[assistant] 'It was lost, so a full refund is due.' calls=["refunds_issue({'order_id': 'ORD-1002', 'amount_cents': 8450, 'reason': 'lost in transit', 'confirm': True})"]
[tool ] '{"refunded": true, "order_id": "ORD-1002", "amount_cents": 8450}'
[assistant] 'Done. | | Refunded 8450 cents to the original payment method.'
EVENTS (the full record): {'span_begin': 9, 'sample_init': 1, 'span_end': 9, 'model': 3, 'tool': 3, 'store': 5, 'state': 1, 'score': 1}
tool orders_get{'order_id': 'ORD-1002'} error=None
tool refunds_issue{'order_id': 'ORD-1002', 'amount_cents': 8450, 'reason': 'lost in transit', 'confirm': True} error=None
tool submit{'answer': 'Refunded 8450 cents to the original payment method.'} error=None
output.completion: 'Done.\n\nRefunded 8450 cents to the original payment method.'
store: {'Desk:refunds': [{'order_id': 'ORD-1002', 'amount_cents': 8450, 'reason': 'lost in transit'}]}
unknown-order tool message: [('orders_get', ToolCallError(type='unknown', message='no such order: ORD-9999'))]Three observations carry through the rest of the lesson.
First, the agent is not the tool. The model proposed orders_get and refunds_issue; Inspect executed them; the store changed; the outcome scorer read the store. The final text could have been a lie and the outcome score would still have been correct evidence, because it never trusted the text.
Second, messages and events tell different stories. In messages the final assistant turn is Done. | | Refunded 8450 cents... and there is no separate submit tool message. In events there are three tool events, including submit. Inspect rewrote the conversational state for the next consumer while preserving the full transcript. This is why a process grader that reads only state.messages can miss calls, and why the adapters in Part 10 read events.
Third, the unknown-order case shows the intended error contract. orders_get raised ToolError, the model received a recoverable tool error, and the scripted agent answered without refunding anything. A domain failure became part of the behaviour being evaluated rather than a harness crash.
6.3 Four ways to use one agent#
The same Agent object can be driven in four ways:
| Use | API | Conversation relationship | Typical use |
|---|---|---|---|
| Solver | Task(solver=agent) or eval(..., solver=agent) |
The agent is the solver and writes the sample state directly | The common case: evaluate the agent itself |
| Direct run | await run(agent, input, limits=None, **kwargs) |
Input is copied; the returned AgentState contains the result |
Explicit workflows and pipelines |
| Agent as tool | as_tool(agent, ...) |
Isolated string in, string out | Supervisor delegates a self-contained subtask |
| Handoff | handoff(agent, ...) |
Shared conversation history, filtered on input and output | Control passes to a specialist and returns |
run() accepts a plain string, a list of ChatMessages or an AgentState as input, and takes an optional name (used for its transcript span) and span_id. With a non-empty limits list it returns a tuple (AgentState, LimitExceededError | None) instead of a bare state, so code that adds limits later must also change how it unpacks the result.
as_solver(agent, limits=[], **agent_kwargs) adapts an agent for interfaces that expect a solver and also copies the resulting state back. It is the right adapter when you need to curry parameters or attach agent-specific limits but still want solver semantics.
6.4 run() copies its input: copy the result back#
run() is the sharpest edge in the protocol. It copies the input messages before running, never mutates that input in place and returns a new AgentState. Inside a custom solver, throwing that return value away means the scorer sees whatever the solver state already contained, usually nothing.
s10_agent_protocol.py demonstrates the protocol, factory versus execute parameters, and all four driving styles in one keyless run:
# s10_agent_protocol.py: Agent, AgentState, run() copy semantics and as_solver() (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import Agent, AgentState, agent, as_solver, is_agent, react, run
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessageSystem, get_model
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, Solver, TaskState, solver
from desk import call, docs_search, say, scripted
# --- 1. An agent: async (state: AgentState, ...) -> AgentState, registered with @agent.
@agent(description="Answers policy questions from the help centre.")
def policy_agent(max_searches: int = 3) -> Agent: # factory argument: fixed when you build it
async def execute(state: AgentState, tone: str = "friendly") -> AgentState: # agent argument: per call
state.messages.insert(0, ChatMessageSystem(content=f"Answer in a {tone} tone, from the help centre only."))
messages, state.output = await get_model().generate_loop(state.messages, tools=[docs_search()])
state.messages.extend(messages)
return state
return execute
fresh = AgentState(messages=[])
print("is_agent:", is_agent(policy_agent()), "| a new AgentState: messages =", fresh.messages,
"| output.completion =", repr(fresh.output.completion))
PLAN = {"refund": [call("docs_search", query="refund policy"), say("Refunds are possible within 30 days.")]}
SAMPLE = Sample(input="What is the refund policy?", target="30 days")
def score_with(label, solver_):
log = eval(Task(dataset=[SAMPLE], solver=solver_, scorer=includes()),
model=scripted(PLAN), log_dir="logs/s10", display="none")[0]
s = log.samples[0]
if s.error:
print(f"{label:34} sample error: {s.error.message[:70]}")
return
print(f"{label:34} score={s.scores['includes'].value} completion={s.output.completion!r} "
f"messages={len(s.messages)}")
# --- 2. Four ways to drive it as the solver of a task.
@solver
def run_and_discard() -> Solver:
async def solve(state: TaskState, generate: Generate) -> TaskState:
await run(policy_agent(), state.messages) # result thrown away: run() copied its input
return state
return solve
@solver
def run_and_copy_back() -> Solver:
async def solve(state: TaskState, generate: Generate) -> TaskState:
agent_state = await run(policy_agent(), state.messages)
state.messages = agent_state.messages # copy BOTH back, or scorers see nothing
state.output = agent_state.output
return state
return solve
score_with("agent passed as the solver", policy_agent())
score_with("run() inside a solver, discarded", run_and_discard())
score_with("run() inside a solver, copied back", run_and_copy_back())
score_with("as_solver(agent, tone='formal')", as_solver(policy_agent(), tone="formal"))
score_with("as_solver(agent, max_searches=1)", as_solver(policy_agent(), max_searches=1))
# --- 3. What the curried argument changed.
log = eval(Task(dataset=[SAMPLE], solver=as_solver(policy_agent(), tone="formal")),
model=scripted(PLAN), log_dir="logs/s10", display="none")[0]
print("\nsystem message with tone='formal':", repr(log.samples[0].messages[0].text))is_agent: True | a new AgentState: messages = [] | output.completion = ''
agent passed as the solver score=C completion='Refunds are possible within 30 days.' messages=5
run() inside a solver, discarded score=I completion='' messages=1
run() inside a solver, copied back score=C completion='Refunds are possible within 30 days.' messages=5
as_solver(agent, tone='formal') score=C completion='Refunds are possible within 30 days.' messages=5
as_solver(agent, max_searches=1) sample error: TypeError("policy_agent.<locals>.execute() got an unexpected keyword a
system message with tone='formal': 'Answer in a formal tone, from the help centre only.'The discarded run scores incorrect with an empty completion even though the agent did run and its events are in the transcript. The corrected solver copies both fields back:
state.messages = agent_state.messages
state.output = agent_state.outputCopy both. Copying only output can leave scorers or later solvers reading a conversation that does not explain the output; copying only messages leaves answer scorers empty.
The last failure in the output is equally instructive. as_solver(policy_agent(), max_searches=1) fails because max_searches is a factory parameter, not an execute parameter. as_solver(policy_agent(max_searches=1)) would be correct. By contrast tone is an execute parameter, so as_solver(policy_agent(), tone="formal") works and the printed system prompt proves it reached the agent.
6.5 The baseline rule#
Inspect's own multi-agent documentation gives the right methodological order, and it matches 10A.12, Part 6:
- Build a single-agent
react()baseline. - Improve the environment definition, tools and prompt.
- Measure reliability and cost over repeated trials.
- Only then try a custom or multi-agent scaffold, benchmarked against that tuned baseline.
This is not conservatism for its own sake. A multi-agent system adds routing errors, context-transfer loss, coordination tokens and new failure modes. If it beats a weak single agent but loses to a tuned one, the architecture was not the active ingredient. The scaffold comparison is an experiment, not a style choice.
Part 7: react() parameter by parameter#
7.1 The loop you are configuring#
react() is Inspect's production implementation of the tool-using agent loop from 08A.2. It is named for the ReAct pattern (08A.10; reflection and fan-out are in 08A.11), but it is much more than the original prompt pattern. It layers prompts, adds a submit tool, can score attempts mid-run, handles refusals and context overflow, and integrates approval, review, truncation and compaction.
The verified signature in 0.3.292 is:
# Signatures, not a runnable file
react(*, name=None, description=None, prompt=AgentPrompt(), tools=None,
model=None, attempts=1, submit=None, on_continue=None,
retry_refusals=None, compaction=None, truncation="disabled",
approval=None, review=None)flowchart TD
start(["AgentState: messages, output"]) --> sys["Prepend system prompt: instructions + assistant prompt + submit prompt"]
sys --> gen["generate(): model reads messages and tools"]
gen --> overflow{"stop_reason == model_length?"}
overflow -- "yes" --> trunc{"compaction or truncation can shrink it?"}
trunc -- "no" --> stop(["Return state"])
trunc -- "yes" --> gen
overflow -- "no" --> refuse{"third content_filter in a row?"}
refuse -- "yes" --> stop
refuse -- "no" --> calls{"tool calls?"}
calls -- "yes" --> exec["execute_tools(): run calls, handoffs, approval, review"]
exec --> submitted{"submit() called?"}
submitted -- "no" --> cont["on_continue"]
submitted -- "yes" --> att{"attempts used up?"}
att -- "yes" --> stop
att -- "no" --> score["Run the task scorer mid-run"]
score -- "correct" --> stop
score -- "incorrect" --> msg["Append incorrect_message"] --> gen
calls -- "no" --> cont
cont -- "continue" --> gen
cont -- "False" --> stopThe diagram is the mental model to keep when reading a transcript. A completion is not just "what the model said". It is the result of prompt layering, tool execution, submit rewriting and continuation logic.
7.2 Prompt layering: instructions, assistant prompt, handoff prompt, submit prompt#
prompt accepts either a string or an AgentPrompt. Passing a string sets only instructions and keeps the default scaffolding text. The full object is:
# Shape of the API (signatures, not a runnable file)
AgentPrompt(instructions=None, handoff_prompt=..., assistant_prompt=..., submit_prompt=...)The layers are:
| Layer | When it appears | What it is for |
|---|---|---|
instructions |
Whenever you provide them | Your domain instructions: role, policy, constraints |
handoff_prompt |
Only when handoff tools are present | Explains that the agent is part of a multi-agent system and how transfers work |
assistant_prompt |
By default | General tool-use advice, including parallel calls and reasoning before actions |
submit_prompt |
When a submit tool exists | Tells the model to call the submit tool when done |
s07_prompt_submit.py prints the real prompt and then varies the submit configuration:
# s07_prompt_submit.py: react() prompt layering, the submit tool and what the scorer sees (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import AgentPrompt, AgentSubmit, react
from inspect_ai.dataset import Sample
from inspect_ai.scorer import exact, includes, match
from inspect_ai.tool import ToolDef
from desk import call, desk_tools, say, scripted
SAMPLE = Sample(input="How long is the refund window? (ORD-1001)", target="30 days")
def run(agent, plan, scorers=None):
log = eval(Task(dataset=[SAMPLE], solver=agent, scorer=scorers or [exact(), match(), includes()]),
model=scripted({"ORD-1001": plan}), log_dir="logs/s07", display="none")[0]
return log.samples[0]
# --- 1. The default prompt layers: your instructions + assistant prompt + submit prompt.
s = run(react(prompt="You are a support agent for an online shop.", tools=desk_tools()),
[call("submit", "Our policy says:", answer="30 days")])
print("DEFAULT SYSTEM PROMPT:\n" + s.messages[0].text)
# --- 2. What the scorer sees with the default submit, and with answer_only=True.
print("\ndefault submit completion:", repr(s.output.completion),
"| exact/match/includes:", [v.value for v in s.scores.values()])
s = run(react(prompt="You are a support agent.", tools=desk_tools(), submit=AgentSubmit(answer_only=True)),
[call("submit", "Our policy says:", answer="30 days")])
print("answer_only=True completion:", repr(s.output.completion),
"| exact/match/includes:", [v.value for v in s.scores.values()])
# --- 3. Only your words: switch every default layer off, and rename the submit tool.
agent = react(
prompt=AgentPrompt(instructions="Answer from the help centre. When done, call {submit}().",
assistant_prompt=None, submit_prompt=None, handoff_prompt=None),
tools=desk_tools(),
submit=AgentSubmit(name="resolve_ticket", description="Close the ticket with the final reply to the customer.",
answer_only=True))
s = run(agent, [call("resolve_ticket", answer="30 days")])
print("\nCUSTOM SYSTEM PROMPT:", repr(s.messages[0].text))
print("tools offered:", [ToolDef(t).name for t in desk_tools()] + ["resolve_ticket"],
"| completion:", repr(s.output.completion))
# --- 3b. {submit} is filled in only inside assistant_prompt (and the default submit prompt).
agent = react(
prompt=AgentPrompt(instructions="Answer from the help centre.",
assistant_prompt="Use the tools, then call {submit}() with the reply.",
submit_prompt=None, handoff_prompt=None),
tools=desk_tools(), submit=AgentSubmit(name="resolve_ticket", answer_only=True))
s = run(agent, [call("resolve_ticket", answer="30 days")])
print("PLACEHOLDER IN assistant_prompt:", repr(s.messages[0].text))
# --- 4. submit=False: the agent stops as soon as the model stops calling tools.
s = run(react(prompt="You are a support agent.", tools=desk_tools(), submit=False),
[call("docs_search", query="refund policy"), say("Refunds are possible within 30 days.")])
print("\nsubmit=False completion:", repr(s.output.completion), "| messages:", [m.role for m in s.messages])
try:
react(tools=desk_tools(), submit=False, on_continue="Keep going.")
except ValueError as e:
print("submit=False + on_continue str ->", type(e).__name__ + ":", str(e)[:70] + "...")DEFAULT SYSTEM PROMPT:
You are a support agent for an online shop.
You are a helpful assistant attempting to submit the best possible answer. You have several tools available to help with finding the answer. You will see the result of tool calls right after sending the message. Prioritize parallel tool calls: when operations are independent, run them in one response — e.g. reading several files or running several searches at once — rather than one at a time. Only sequence calls when one depends on another's result. Do some reasoning before your actions, describing what tool calls you are going to use and how they fit into your plan.
When you have completed the task and have an answer, call the submit() tool to report it.
default submit completion: 'Our policy says:\n\n30 days' | exact/match/includes: ['I', 'C', 'C']
answer_only=True completion: '30 days' | exact/match/includes: ['C', 'C', 'C']
CUSTOM SYSTEM PROMPT: 'Answer from the help centre. When done, call {submit}().'
tools offered: ['orders_get', 'refunds_issue', 'docs_search', 'send_email', 'resolve_ticket'] | completion: '30 days'
PLACEHOLDER IN assistant_prompt: 'Answer from the help centre.\n\nUse the tools, then call resolve_ticket() with the reply.'
submit=False completion: 'Refunds are possible within 30 days.' | messages: ['system', 'user', 'assistant', 'tool', 'assistant']
submit=False + on_continue str -> ValueError: Passing a string to on_continue with no submit tool is not permitted, ...The first printed prompt shows the exact layering. Your sentence comes first, then the default assistant prompt, then the submit instruction. This is why react(prompt="You are a support agent.") is not a blank-slate prompt. It is a scaffolded prompt. Often that is what you want; the default guidance is the result of practical agent experience. But when comparing scaffolds, do not describe it as "the same prompt with a different loop".
The handoff_prompt layer did not appear in that printout because the agent had no handoff tools. s22_handoff_prompt.py gives the same agent one handoff tool and prints the system prompt again:
# s22_handoff_prompt.py: the system prompt a supervisor gets once it holds a handoff tool (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import handoff, react
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model
from desk import M, call, docs_search, orders_get
returns = react(name="returns", description="Handles refunds and returns for existing orders.",
prompt="You are the returns specialist.", tools=[orders_get()])
def first_system_prompt(agent) -> str:
seen: list[str] = []
def fn(input, tools, tool_choice, config):
seen.append(next(m.text for m in input if m.role == "system"))
return call("submit", answer="ok") # end at once: we only want the prompt
eval(Task(dataset=[Sample(input="Where is ORD-1002?")], solver=agent),
model=get_model(M, custom_outputs=fn, memoize=False), log_dir="logs/s22", display="none")
return seen[0]
plain = first_system_prompt(react(prompt="You are the triage agent.", tools=[docs_search()]))
with_handoff = first_system_prompt(react(prompt="You are the triage agent.",
tools=[docs_search(), handoff(returns)]))
print(f"without a handoff tool: {len(plain)} chars | with one: {len(with_handoff)} chars")
print("handoff layer in the plain prompt:", "multi-agent system" in plain)
print("\nSUPERVISOR SYSTEM PROMPT WITH A HANDOFF TOOL:\n" + with_handoff.strip())without a handoff tool: 694 chars | with one: 1218 chars
handoff layer in the plain prompt: False
SUPERVISOR SYSTEM PROMPT WITH A HANDOFF TOOL:
You are the triage agent.
You are part of a multi-agent system designed to make agent coordination and execution easy. Agents uses two primary abstraction: **Agents** and **Handoffs**. An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate. Handoffs are achieved by calling a handoff function,generally named `transfer_to_<agent_name>`. Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.
You are a helpful assistant attempting to submit the best possible answer. You have several tools available to help with finding the answer. You will see the result of tool calls right after sending the message. Prioritize parallel tool calls: when operations are independent, run them in one response — e.g. reading several files or running several searches at once — rather than one at a time. Only sequence calls when one depends on another's result. Do some reasoning before your actions, describing what tool calls you are going to use and how they fit into your plan.
When you have completed the task and have an answer, call the submit() tool to report it.Adding one tool added about 520 characters of instructions the eval author never wrote, between your instructions and the assistant prompt. Two parts of that text matter for evaluation. "Do not mention or draw attention to these transfers in your conversation with the user" is a behavioural instruction: if your rubric rewards telling the customer "I am passing you to our returns team", the default supervisor is being told to do the opposite, and a transparency metric will measure the scaffold, not the model. And the text describes a multi-agent system to the model, so a single-agent baseline and a multi-agent variant differ in prompt as well as in architecture. Set handoff_prompt=None or write your own when either matters, and record which you used. (The odd spacing and the "Agents uses two primary abstraction" wording are Inspect's own text, printed as it is.)
To suppress every default layer, pass an AgentPrompt with the unwanted fields set to None. The probe's custom prompt does exactly that. It also reveals a sharp edge in 0.3.292: the {submit} placeholder is substituted in assistant_prompt, submit_prompt and continuation messages, not in instructions. The custom instructions still contain the literal text {submit}(), while the assistant prompt version correctly says resolve_ticket(). If you rename the submit tool, write its name explicitly in your own instructions or put placeholder-dependent guidance in assistant_prompt.
7.3 The submit tool and what the scorer sees#
The default submit tool has one argument, answer, and its result is the answer. Its output is deliberately exempt from tool-output truncation. On a successful submit, react() rewrites state.output.completion:
| Setting | Final completion | Use it when |
|---|---|---|
AgentSubmit(answer_only=False) (default) |
The assistant text that accompanied the submit call, then answer_delimiter (default two newlines), then the answer |
The prose around the answer is part of what you grade |
AgentSubmit(answer_only=True) |
Only the answer | Exact match, structured answers, machine-read final outputs |
The probe makes the consequence concrete. With the default submit, the completion is 'Our policy says:\n\n30 days' (there the prose is a content= the script supplied; when a script gives none, mockllm inserts tool call for tool submit, as in the outputs of 1.5 onwards); exact() fails, while match() and includes() pass because they can find the target at the end or inside the text. With answer_only=True, the completion is exactly '30 days' and all three pass. This is the same scoring-location discipline as 10B.10, but agent machinery creates the mismatch.
AgentSubmit also lets you rename or replace the tool:
# Shape of the API (signatures, not a runnable file)
AgentSubmit(name=None, description=None, tool=None, answer_only=False,
answer_delimiter="\n\n", keep_in_messages=False)keep_in_messages=False is the default for a reason. Inspect removes submit calls from the final message history and folds the answer into the final assistant message. Setting it to True can make a supervisor in a multi-agent system stop early because it sees what looks like a submission in the shared history. Keep the default unless you have a specific transcript need and have tested the interaction.
7.4 submit=False: no explicit finish line#
With submit=False, there is no submit tool. The agent terminates when the model stops calling tools, so the final completion is simply the final assistant text. This is appropriate when the agent's job is to change a world and the scorer reads end state, or when the output format is ordinary prose rather than a submitted answer.
The trade-off is control. A submit tool makes termination explicit and gives the scorer a clean answer boundary. Without it, a model can stop early, or continue because it keeps proposing low-value tool calls. In the probe, submit=False ends cleanly after one search and one prose answer. In a real eval, pair this mode with a message, turn or token limit (10B.15) and make the outcome scorer independent of the final claim.
One invalid combination is worth remembering: a string on_continue with submit=False raises ValueError, because the default continuation instruction refers to submission. Use an async function or provide continuation semantics that make sense without a submit tool.
7.5 Attempts: scoring inside the run#
By default attempts=1: the first submission ends the agent. With several attempts, Inspect can score a submission inside the solve phase, tell the agent it was incorrect and let it continue.
# Shape of the API (signatures, not a runnable file)
AgentAttempts(attempts=1, incorrect_message=..., score_value=value_to_float())s08_attempts_continue.py exercises the mechanism:
# s08_attempts_continue.py: attempts (scoring inside the run) and on_continue (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import AgentAttempts, AgentState, react
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from desk import call, desk_tools, say, scripted
SAMPLE = Sample(input="How long is the refund window? (ORD-1001)", target="30 days")
def run(label, agent, plan):
log = eval(Task(dataset=[SAMPLE], solver=agent, scorer=includes()),
model=scripted({"ORD-1001": plan}), log_dir="logs/s08", display="none")[0]
s = log.samples[0]
n_scores = sum(1 for e in s.events if e.event == "score")
print(f"\n== {label}: final={s.scores['includes'].value} score events={n_scores}")
for m in s.messages[1:]:
calls = [c.function for c in (getattr(m, "tool_calls", None) or [])]
print(f" [{m.role:9}] {m.text.strip()[:84]!r}" + (f" calls={calls}" if calls else ""))
wrong_then_right = [call("submit", answer="45 days"), call("submit", answer="30 days")]
run("attempts=1 (default)", react(tools=desk_tools()), wrong_then_right)
run("attempts=2", react(tools=desk_tools(), attempts=2), wrong_then_right)
async def feedback(state: AgentState, scores) -> str:
return f"Not accepted ({scores[0].value}). Check the help centre with docs_search before answering."
run("attempts=3, incorrect_message is a function",
react(tools=desk_tools(), attempts=AgentAttempts(attempts=3, incorrect_message=feedback)),
[call("submit", answer="45 days"), call("docs_search", query="refund policy"),
call("submit", answer="30 days")])
# --- on_continue: what happens when the model answers in plain text instead of calling a tool.
run("text without a tool call, default on_continue", react(tools=desk_tools()),
[say("The window is 30 days."), call("submit", answer="30 days")])
async def at_most_two_tool_turns(state: AgentState) -> bool | str:
turns_with_tools = sum(1 for m in state.messages if getattr(m, "tool_calls", None))
if turns_with_tools >= 2:
return False # stop the loop: the run ends without a submission
return "Remember: cite the help-centre article you used." # str: sent on EVERY turn
run("on_continue is an async function", react(tools=desk_tools(), on_continue=at_most_two_tool_turns),
[call("docs_search", query="refund"), call("docs_search", query="refund policy"),
call("submit", answer="30 days")])
def not_async(state):
return True
log = eval(Task(dataset=[SAMPLE], solver=react(tools=desk_tools(), on_continue=not_async)),
model=scripted({"ORD-1001": [say("thinking")]}), log_dir="logs/s08", display="none")[0]
print("\nsync on_continue -> log.status:", log.status, "| sample error:", log.samples[0].error.message[:80])== attempts=1 (default): final=I score events=1
[user ] 'How long is the refund window? (ORD-1001)'
[assistant] 'tool call for tool submit\n\n45 days'
== attempts=2: final=C score events=2
[user ] 'How long is the refund window? (ORD-1001)'
[assistant] 'tool call for tool submit\n\n45 days'
[user ] 'Your submission was incorrect. Please proceed and attempt to find the correct answer'
[assistant] 'tool call for tool submit\n\n30 days'
== attempts=3, incorrect_message is a function: final=C score events=3
[user ] 'How long is the refund window? (ORD-1001)'
[assistant] 'tool call for tool submit\n\n45 days'
[user ] 'Not accepted (I). Check the help centre with docs_search before answering.'
[assistant] 'tool call for tool docs_search' calls=['docs_search']
[tool ] '{"results": [{"topic": "refund policy", "text": "Refunds are available within 30 day'
[assistant] 'tool call for tool submit\n\n30 days'
== text without a tool call, default on_continue: final=C score events=1
[user ] 'How long is the refund window? (ORD-1001)'
[assistant] 'The window is 30 days.'
[user ] 'Please proceed to the next step using your best judgement. If you believe you have c'
[assistant] 'tool call for tool submit\n\n30 days'
== on_continue is an async function: final=I score events=1
[user ] 'How long is the refund window? (ORD-1001)'
[assistant] 'tool call for tool docs_search' calls=['docs_search']
[tool ] '{"results": [{"topic": "refund policy", "text": "Refunds are available within 30 day'
[user ] 'Remember: cite the help-centre article you used.'
[assistant] 'tool call for tool docs_search' calls=['docs_search']
[tool ] '{"results": [{"topic": "refund policy", "text": "Refunds are available within 30 day'
sync on_continue -> log.status: error | sample error: ValueError('The on_continue function must be async.')The important implementation detail is the order. When the attempt count has been used up, the loop stops without another mid-run score. Otherwise the task's scorer runs inside the solve phase; if the converted score is 1.0 the agent stops, and if not the incorrect_message is appended as a user message. The final scoring pass still happens at the end, which is why attempts=2 shows two score events.
This design has consequences:
- The scorer must be safe during solving. A scorer that reads the store or sandbox is fine. A scorer that assumes the solver is finished, or that has side effects, is not.
- The feedback is part of the experimental condition. "Your submission was incorrect" is weaker than "you looked in the wrong table". Better feedback can improve the score while telling you less about unaided model ability.
- The scoring rule must be calibrated. If the scorer is too strict, the agent burns attempts on correct answers; too loose, it stops on the first wrong answer. Validate the grader with the methods in 10B.11, Part 10 before giving it control over the trajectory.
- Only an exact 1.0 from the first scorer stops the loop. The converter is
value_to_float()by default (Cis 1,IandNare 0,Pis 0.5), and the source compares the first score of the task to1.0. A partial score never ends the run, a numeric scorer that returns 0.9 for a near-perfect answer burns every attempt, and with several scorers on the task (outcome first, process second, as in Part 10) only the first one steers the agent. Order your scorers deliberately, or pass ascore_valuefunction that encodes your stopping rule. - Attempts are not epochs. Attempts happen inside one sample and share state. Epochs repeat the whole sample independently (10B.10, Part 7). Do not report an attempts-enabled success rate as if it were one-shot reliability.
incorrect_message may be an async function (state, scores) -> str. A synchronous function is an error, as the last line of the output shows. Use the function form when feedback should name the failed check, but avoid leaking the target or oracle answer unless that leakage is part of the eval design.
7.6 on_continue: when and how the loop nudges the model#
The continuation hook decides what happens after a model turn that did not finish the task. The default message is:
Please proceed to the next step using your best judgement. If you believe you have completed the task, please call the `{submit}()` tool with your final answer.The semantics depend on the type of on_continue:
| Value | When called | Meaning |
|---|---|---|
None |
Implicitly when the model made no tool calls | Append the default message and continue |
str |
When the model made no tool calls | Append your message instead of the default |
async function returning True |
Every iteration | Continue; Inspect still adds the default message if there were no tool calls |
async function returning False |
Every iteration | Stop the loop |
async function returning str |
Every iteration | Append that message as a user message and continue |
async function returning AgentState |
Every iteration | Replace the state and continue |
The probe's default case shows the nudge: the model answers in prose without calling submit, Inspect appends the default continuation as a user message, and the scripted next turn submits. The function case shows a custom policy: stop after two tool-using turns. Since a returned string is sent on every iteration, it can become repetitive prompt pressure. That may be desirable for strict citation requirements, but it is an intervention in the scaffold and must be reported.
A custom on_continue is a good place for domain-specific stopping rules, but not for hidden grading. If the function inspects the transcript and uses privileged information to steer the agent, the eval no longer measures unaided behaviour. Treat it as part of the system under test.
7.7 Refusals: retry, break or fail the sample#
A refusal is model output with stop_reason == "content_filter", not an exception. react() has three separate controls:
retry_refusals=Nregenerates a refused response up toNtimes before the loop accepts it as the turn's output.- Independently, the loop breaks after three consecutive refusal outputs.
fail_on_refusal=Trueis a generation option, not areact()parameter. It turns a refusal into a sample error.
s09_refusals_overflow.py exercises these paths and context overflow:
# s09_refusals_overflow.py: refusals, retry_refusals, fail_on_refusal and context overflow in react() (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from desk import M, call, desk_tools, scripted
SAMPLE = Sample(input="Refund ORD-1002 please.", target="8450")
refusal = ModelOutput.from_content(M, "I can't help with that.", stop_reason="content_filter")
overflow = ModelOutput.from_content(M, "(prompt too long)", stop_reason="model_length")
finish = call("submit", answer="Refunded 8450 cents.")
def run(label, agent, plan, **eval_args):
log = eval(Task(dataset=[SAMPLE], solver=agent), model=scripted({"ORD-1002": plan}),
log_dir="logs/s09", display="none", **eval_args)[0]
s = log.samples[0]
model_calls = sum(1 for e in s.events if e.event == "model")
err = s.error.message[:60] if s.error else None
print(f"== {label}\n status={log.status} error={err!r} model calls={model_calls} "
f"messages={len(s.messages)} completion={s.output.completion[:40]!r}")
run("three refusals in a row, defaults", react(tools=desk_tools()), [refusal, refusal, refusal, finish])
run("two refusals, then an answer", react(tools=desk_tools()), [refusal, refusal, finish])
run("retry_refusals=2, a model that refuses the same input every time",
react(tools=desk_tools(), retry_refusals=2), [refusal, refusal, finish])
log = eval(Task(dataset=[SAMPLE], solver=react(tools=desk_tools(), retry_refusals=2)),
model=get_model(M, custom_outputs=[refusal, refusal, finish], memoize=False),
log_dir="logs/s09", display="none")[0]
s = log.samples[0]
print("== retry_refusals=2, a model that refuses twice, then answers\n model calls=",
sum(1 for e in s.events if e.event == "model"), "messages=", [m.role for m in s.messages])
run("fail_on_refusal=True", react(tools=desk_tools()), [refusal, finish], fail_on_refusal=True)
run("context overflow, truncation='disabled' (default)", react(tools=desk_tools()), [overflow, finish])
# --- truncation='auto' needs something to trim: four tool rounds, then the overflow.
# A plain list of outputs here, because trimming changes the message count the turn-keyed script relies on.
searches = [call("docs_search", query=q) for q in ("refund", "shipping", "lost parcel", "ORD-1002")]
for mode in ("disabled", "auto"):
log = eval(Task(dataset=[SAMPLE], solver=react(tools=desk_tools(), truncation=mode)),
model=get_model(M, custom_outputs=[*searches, overflow, finish], memoize=False),
log_dir="logs/s09", display="none")[0]
s = log.samples[0]
infos = [e.data for e in s.events if e.event == "info"]
print(f"== four tool rounds, then overflow, truncation={mode!r}\n messages={len(s.messages)} "
f"completion={s.output.completion[:40]!r}\n info events: {infos}")== three refusals in a row, defaults
status=success error=None model calls=3 messages=7 completion="I can't help with that."
== two refusals, then an answer
status=success error=None model calls=3 messages=7 completion='tool call for tool submit\n\nRefunded 8450'
== retry_refusals=2, a model that refuses the same input every time
status=success error=None model calls=7 messages=7 completion='tool call for tool submit\n\nRefunded 8450'
== retry_refusals=2, a model that refuses twice, then answers
model calls= 3 messages= ['system', 'user', 'assistant']
== fail_on_refusal=True
status=error error='ModelRefusalError("Model refusal (mockllm/model): I can\'t he' model calls=1 messages=2 completion=''
== context overflow, truncation='disabled' (default)
status=success error=None model calls=1 messages=3 completion='(prompt too long)'
== four tool rounds, then overflow, truncation='disabled'
messages=11 completion='(prompt too long)'
info events: ['Agent terminated: model context window exceeded']
== four tool rounds, then overflow, truncation='auto'
messages=9 completion='tool call for tool submit\n\nRefunded 8450'
info events: ['Agent exceeded model context window, truncating messages and continuing.']Read the call counts before reading the completion. With retry_refusals=2, one outer turn can produce several model events because retrying is still a model call. Cost and rate-limit analysis must count events, not logical turns. The simple list-backed mock also shows the recovery case: two scripted refusals are consumed by retries and the third generation submits, so the agent finishes with a clean three-message history. In a real eval, decide whether a refusal is behaviour to score or a safety outcome to report separately. 10B.12, 8.6 covers the run-level policy; the agent-level point is that silent retrying can hide a systematic refusal pattern unless you inspect events.
7.8 Context overflow, truncation and compaction#
How to manage a growing conversation in general (trimming, summarising, offloading) is taught in 04.7 and, for agents, 08B.3, and 10A.11 covers evaluating memory and context. Here is how react() behaves when the window fills. Inspect surfaces that as stop_reason == "model_length". react() offers three different responses:
| Mechanism | Setting | What changes | What is preserved |
|---|---|---|---|
| Terminate | truncation="disabled" (default) |
The agent stops on overflow | Everything, because the run ends |
| Mechanical truncation | truncation="auto" or a MessageFilter |
The input message list is shortened, roughly 30 percent with auto |
The transcript events remain complete |
| Compaction | compaction=... |
A strategy rewrites what the model sees, often with a summary or provider-native compaction | The core history is retained outside model input |
The output shows the difference. With the default, the overflow produces an info event Agent terminated: model context window exceeded and the run ends. With truncation="auto", Inspect truncates, logs Agent exceeded model context window, truncating messages and continuing., and the scripted agent can submit. The message count falls from 11 to 9.
Truncation is not free memory. Dropping the middle of a conversation can remove the order id, the constraint, the tool error or the very evidence the agent needed. It can also interact badly with a message_limit: because the visible history shrinks, the run may continue much longer than you intended. Pair truncation with time, token or cost limits, and record the setting in the scaffold description.
If compaction= is also set, react() first tries a forced compaction on overflow and only falls back to the truncation filter if that fails (since 0.3.217); since 0.3.278 it does not force compaction a second time when the retry overflows again, which previously could resend the same request indefinitely. Both behaviours are in the CHANGELOG, which is the only place such loop details are documented.
Compaction is more sophisticated. The strategies exported in 0.3.292 are CompactionAuto, CompactionNative, CompactionSummary, CompactionEdit and CompactionTrim. They differ in whether a provider API, a helper model or deterministic editing produces the compacted input. The evaluative rule is the same for all of them: compaction is part of the system under test. Two runs with different compaction strategies are different agents even if every other line is identical. 10B.15, 10.3 treats compaction as a long-horizon control in more depth; here it is enough to configure react() knowingly.
7.9 model=: swapping the brain, including with an agent#
model= normally selects a different model for the agent, for example a cheaper model for a subagent or a stronger model for a final answerer. It can also be an Agent with the custom signature execute(state, tools). That advanced form replaces the generation step itself, which allows patterns such as best-of-n generation, a critic that chooses among candidates or a model router.
The evaluation warning is sharp: once model= is an agent, your agent has another agent inside it. Spans and model events become the only reliable way to attribute tokens and decisions. Use model_origin() for helper or environment calls (8.5) and keep the architecture in metadata.
7.10 approval= and review=: agent-local control#
approval= and review= replace the eval- or task-level policies for this agent's tool calls. They travel with the agent into handoffs and subagents. This lesson does not teach the policy language, approver decisions or reviewer chain; 10B.15, Part 8 and Part 9 own those. The scope decision you need here is architectural:
- Use agent-local policies when one subagent has a genuinely different risk profile, such as a read-only researcher versus a refund-issuing specialist.
- Prefer task-level policies when the rule is a property of the eval rather than of one component.
- Remember the observability boundary from Parts 1 and 5: approval cannot review provider-run tools or remote MCP execution.
7.11 deepagent(): batteries included, not automatically better#
deepagent() is Inspect's batteries-included long-horizon agent. It composes the ideas you have already seen: a top-level agent, delegation to subagents, memory, planning, submission, compaction and optional background work. Its verified signature is broad:
# Signatures, not a runnable file
deepagent(*, tools=None, subagents=None, memory=True, todo_write=True,
web_search=False, background=False, skills=None, model=None,
attempts=1, submit=None, on_continue=None, retry_refusals=3,
compaction="auto", approval=None, instructions=None,
prompt=None, max_depth=1)The differences from react() matter. Refusal retries default to 3 rather than none, compaction defaults to "auto", memory and todo_write are on by default, and the default subagents are research(), plan() and general(). Delegation appears as one agent tool. Subagents run in isolated context by default: they receive the task prompt, not the parent's whole history, and only their report returns. background=True adds lifecycle tools for asynchronous subagents; fork=True on a custom subagent inherits the parent's full history. Those are long-horizon controls, so 10B.15, 10.2 owns their operational detail. The comparison you need here is the surface area:
# s17_deepagent.py: what deepagent() puts in front of the model, compared with react() (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import deepagent, react
from inspect_ai.dataset import Sample
from inspect_ai.model import get_model
from desk import M, call, desk_tools
def surface(agent) -> tuple[list[str], int]:
seen: dict = {}
def fn(input, tools, tool_choice, config):
seen.setdefault("tools", [t.name for t in tools])
seen.setdefault("system", next((m.text for m in input if m.role == "system"), ""))
return call("submit", answer="ok")
eval(Task(dataset=[Sample(input="Refund ORD-1002.")], solver=agent),
model=get_model(M, custom_outputs=fn, memoize=False), log_dir="logs/s17", display="none")
return seen["tools"], len(seen["system"])
for label, agent in [("react(tools=desk_tools())", react(tools=desk_tools())),
("deepagent(tools=desk_tools())", deepagent(tools=desk_tools()))]:
tools, chars = surface(agent)
print(f"{label:30} system prompt {chars:5} chars | tools: {tools}")react(tools=desk_tools()) system prompt 667 chars | tools: ['orders_get', 'refunds_issue', 'docs_search', 'send_email', 'submit']
deepagent(tools=desk_tools()) system prompt 3297 chars | tools: ['orders_get', 'refunds_issue', 'docs_search', 'send_email', 'todo_write', 'agent', 'memory', 'submit']With the same four support tools, react() offers five tools (the four plus submit) and a 667-character system prompt. deepagent() offers eight (adding todo_write, delegation and memory) and a prompt nearly five times larger. That is not inherently bad: difficult, long tasks may benefit. It is, however, a different independent variable. More prompt text, more tools and more delegation paths mean more behavioural surface, more cost and more failure modes.
The Inspect documentation says its authors did not observe performance differences among react(), deepagent() and claude_code() on shorter but difficult benchmarks such as Cybench and Terminal Bench 2.0, while recommending deepagent() only when the task benefits and always against a react() baseline. Treat that as a methodological warning rather than a universal benchmark result: no public numeric table accompanies the claim, and your tasks may differ. The defensible experiment is direct: same dataset, same tools, same model, same limits, react() versus deepagent(), repeated enough for the reliability statistics in 10B.10.
7.12 Older code and tutorials: basic_agent() and friends#
Older Inspect examples often use APIs that are deprecated, undocumented or removed. Their status in 0.3.292 is:
| Old API | Status in 0.3.292 | Use instead |
|---|---|---|
basic_agent() |
Still exported and functional, but removed from the documentation | react() |
call_tools() |
Deprecated | execute_tools() |
bridge() |
Deprecated | agent_bridge() or sandbox_agent_bridge() in 10B.15, 10.4 |
human_agent() |
Deprecated with a one-time runtime warning | human_cli() in 10B.15, 10.7 |
web_browser() |
Removed; always raises PrerequisiteError |
web_search(), computer() or browser MCP (4.5) |
mcp_server_sse() |
Deprecated transport | mcp_server_http() |
basic_agent() is especially confusing because it still runs and because one default differs in a scorer-visible way. Its submit_append=False default replaces the completion with the submitted answer, whereas react() appends the answer to the accompanying text by default. The probe makes the difference exact:
# s19_basic_agent.py: older code: basic_agent() replaces the completion, react() appends (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.solver import basic_agent
from desk import call, desk_tools, scripted
PLAN = {"ORD-1001": [call("submit", "Our policy says:", answer="30 days")]}
sample = Sample(input="Refund window? (ORD-1001)", target="30 days")
for label, solver_ in [("basic_agent()", basic_agent(tools=desk_tools())), ("react()", react(tools=desk_tools()))]:
s = eval(Task(dataset=[sample], solver=solver_), model=scripted(PLAN),
log_dir="logs/s19", display="none")[0].samples[0]
print(f"{label:14} completion={s.output.completion!r}")basic_agent() completion='30 days'
react() completion='Our policy says:\n\n30 days'When migrating old code, do not assume the same scorer will behave the same way. Either set AgentSubmit(answer_only=True) in the new react() agent or adjust the scorer deliberately, and rerun the baseline rather than carrying forward an old number.
Part 8: Custom agents: when the loop itself is the variable#
Deep-dive
8.1 When to write one#
Most product evals should not start with a custom agent. react() already implements the difficult details: MCP connection lifetime, handoff-aware execution, submit rewriting, refusal handling, overflow handling, approval and review. Write a custom agent when the loop itself is the research question or when a constraint truly cannot be expressed in react():
- different termination logic, such as stopping after two consecutive unproductive tool turns;
- filtering or rewriting proposed calls before execution;
- inserting a critic, verifier or repair step between iterations;
- a workflow with deterministic routing rather than model-chosen delegation;
- a scaffold comparison in which the scaffold is the independent variable.
The smallest useful version is Model.generate_loop(), which generates and executes tools until the model stops calling them:
# generate_loop_shape.py (illustrative shape, not a runnable sample)
from inspect_ai.agent import Agent, AgentState, agent
from inspect_ai.model import ChatMessageSystem, get_model
@agent
def simple_loop(tools) -> Agent:
async def execute(state: AgentState) -> AgentState:
state.messages.insert(0, ChatMessageSystem(content="Use the tools and answer."))
messages, state.output = await get_model().generate_loop(state.messages, tools=tools)
state.messages.extend(messages)
return state
return executeThis is useful for understanding, but it lacks the evaluation features of react(). Use it as a teaching skeleton, not as the default product scaffold.
8.2 The hand-written tool loop, and the docs bug#
The Custom Agents documentation in 0.3.292 prints a tool loop that assigns the model output to state.output and then uses undefined names output and message. Copied verbatim, it raises NameError. The probe keeps that broken loop next to a corrected one so you can see both the failure and the repair:
# s11_custom_loop.py: a custom tool loop, the docs' bug, a guarded loop, spans and model_origin (lesson 10B.14)
from typing import Sequence
from inspect_ai import Task, eval
from inspect_ai.agent import AgentState, agent
from inspect_ai.dataset import Sample
from inspect_ai.log import transcript
from inspect_ai.model import (ChatMessageTool, ModelOutput, execute_tools, get_model,
model_origin)
from inspect_ai.tool import Tool, ToolCallError, ToolDef, ToolSource, mcp_connection
from inspect_ai.util import span
from desk import M, call, desk_tools, refund_outcome, say, scripted
PLAN = {"ORD-1002": [
call("orders_get", order_id="ORD-1002"),
call("send_email", to="bo@example.com", subject="Refund", body="Refunding now."),
call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
say("Refunded 8450 cents."),
]}
SAMPLE = Sample(id="refund-lost", input="Order ORD-1002 never arrived. Please refund it in full.",
metadata={"expect_refund": {"order_id": "ORD-1002", "amount_cents": 8450}})
# --- 1. The loop exactly as printed on the docs' Custom Agents page (0.3.292).
@agent
def docs_loop(tools: Sequence[Tool | ToolDef | ToolSource]):
async def execute(state: AgentState):
async with mcp_connection(tools):
while True:
state.output = await get_model().generate(input=state.messages, tools=tools)
state.messages.append(output.message) # noqa: F821
if output.message.tool_calls: # noqa: F821
messages, state.output = await execute_tools(message, tools) # noqa: F821
state.messages.extend(messages)
else:
break
return state
return execute
# --- 2. A corrected loop with three customizations: a step cap, a tool-call filter and a helper call.
BLOCKED = {"send_email"} # this deployment does not let the agent email customers
@agent
def guarded_agent(tools: Sequence[Tool | ToolDef | ToolSource], max_turns: int = 8):
async def execute(state: AgentState) -> AgentState:
async with mcp_connection(tools):
for _ in range(max_turns): # customization 1: a hard cap
state.output = await get_model().generate(input=state.messages, tools=tools)
state.messages.append(state.output.message)
calls = state.output.message.tool_calls or []
if not calls:
break
blocked = [c for c in calls if c.function in BLOCKED] # customization 2: filter calls
allowed = [c for c in calls if c not in blocked]
if allowed: # execute only the allowed calls; the history keeps everything the model proposed
proposal = state.output.message.model_copy(update={"tool_calls": allowed})
messages, output = await execute_tools([*state.messages[:-1], proposal], tools)
state.messages.extend(messages)
if output: # a handoff can return a new output
state.output = output
if blocked: # every proposed call still gets a tool message, or the history is malformed
async with span("policy_filter"):
transcript().info(f"blocked: {[c.function for c in blocked]}")
for c in blocked:
state.messages.append(ChatMessageTool(
content="", tool_call_id=c.id, function=c.function,
error=ToolCallError("approval", f"{c.function} is not allowed here")))
with model_origin("helper"): # customization 3: a helper call
await get_model(role="checker").generate("Summarize this ticket in five words.")
return state
return execute
checker = get_model(M, custom_outputs=lambda i, t, tc, c: ModelOutput.from_content(M, "Lost parcel, refunded in full."),
memoize=False)
for label, agent_ in [("docs loop", docs_loop(desk_tools())), ("guarded loop", guarded_agent(desk_tools()))]:
log = eval(Task(dataset=[SAMPLE], solver=agent_, scorer=refund_outcome()), model=scripted(PLAN),
model_roles={"checker": checker}, log_dir="logs/s11", display="none")[0]
s = log.samples[0]
print(f"== {label}: status={log.status}",
f"error={s.error.message[:50]!r}" if s.error else f"score={s.scores['refund_outcome'].value}")
if not s.error:
for m in s.messages:
extra = f" error={m.error.type}:{m.error.message}" if getattr(m, "error", None) else ""
calls = [c.function for c in (getattr(m, "tool_calls", None) or [])]
print(f" [{m.role:9}] {m.text[:40]!r}{extra}" + (f" calls={calls}" if calls else ""))
print(" info:", [e.data for e in s.events if e.event == "info"])
print(" model events by origin:", [(e.role or "default", e.origin) for e in s.events if e.event == "model"])
print(" spans:", [e.name for e in s.events if e.event == "span_begin" and e.type not in ("tool",)])== docs loop: status=error error='NameError("name \'output\' is not defined")'
== guarded loop: status=success score=C
[user ] 'Order ORD-1002 never arrived. Please ref'
[assistant] 'tool call for tool orders_get' calls=['orders_get']
[tool ] '{"order_id": "ORD-1002", "customer_email'
[assistant] 'tool call for tool send_email' calls=['send_email']
[tool ] '' error=approval:send_email is not allowed here
[assistant] 'tool call for tool refunds_issue' calls=['refunds_issue']
[tool ] '{"refunded": true, "order_id": "ORD-1002'
[assistant] 'Refunded 8450 cents.'
info: ["blocked: ['send_email']"]
model events by origin: [('default', 'agent'), ('default', 'agent'), ('default', 'agent'), ('default', 'agent'), ('checker', 'helper')]
spans: ['init', 'solvers', 'guarded_agent', 'guarded_agent', 'policy_filter', 'scorers', 'refund_outcome']The corrected core is:
# Corrected minimal loop (shape inside an agent)
while True:
state.output = await get_model().generate(input=state.messages, tools=tools)
state.messages.append(state.output.message)
if state.output.message.tool_calls:
messages, output = await execute_tools(state.messages, tools)
state.messages.extend(messages)
if output:
state.output = output
else:
breakThe subtle line is if output. Most tool executions return output=None; a handoff can return a replacement ModelOutput. This is one reason execute_tools() rather than deprecated call_tools() is required.
8.3 Filtering proposed calls without corrupting the transcript#
The guarded loop does something approval policies often do more declaratively: it blocks send_email. It demonstrates the invariant you must preserve if you filter calls yourself. Every proposed tool call needs a corresponding tool message before the next model turn. If you silently delete a call from the history, the provider may reject the next request because an assistant tool call has no result.
The sample's solution is careful:
- It executes the allowed subset by constructing a proposal message containing only those calls.
- For every blocked call it appends a
ChatMessageToolwithToolCallError(type="approval", ...). - It records the filtering decision in a transcript span.
The output shows the result. send_email is visible as a proposed assistant call and as a blocked tool error, while refunds_issue still executes. The scorer passes because the refund happened and no email entered the store. This separation is exactly what you want in an eval: the model's proposal, the scaffold's intervention and the world's resulting state are three distinct pieces of evidence.
Prefer Inspect's approval machinery when the policy is a general safety rule (10B.15). Hand-filter inside a custom agent when the intervention is itself part of the scaffold being studied.
8.4 Custom termination, critics and helper models#
A custom loop can enforce termination conditions that are meaningless to react():
# Termination ideas (shape, not a runnable file)
if repeated_identical_calls(state.messages):
break
if verifier_rejected_twice:
break
if no_new_information_for_two_turns:
breakA critic or verifier should usually be a separate model role, not the model under test. Configure it with model_roles as the sample does for checker, then mark its calls with model_origin("helper"). If a simulated user or environment makes model calls, use model_origin("environment"). Without those markers, every model event looks like agent behaviour and token attribution becomes misleading.
Do not let a helper model secretly act as an oracle. A critic that reads hidden metadata or the target and then steers the agent changes what is being measured. If the research question includes such a critic, say so; if it does not, keep privileged data out of its prompt.
8.5 Spans, transcript info and model_origin()#
Custom agents still get automatic spans for agent execution and tool calls. You can add your own structure:
async with span("policy_filter"):groups events in the transcript tree.transcript().info("...")records anInfoEventfor decisions that are not model or tool events.store_as()mutations emit store events, so use the sample store rather than untracked globals when the state is evidence.with model_origin("helper"):or"environment"marks model calls that are not the evaluated agent.
The sample output shows why these tiny instruments matter. The policy_filter span is visible, the info event says exactly what was blocked, and the model events divide into ('default', 'agent') and ('checker', 'helper'). When a run is expensive or contested, this is the difference between auditing what happened and guessing from prose.
8.6 State, concurrency and long-running helpers#
The state rules from Part 2 become more important inside custom agents. If several concurrent workers each need private memory or shell state, use tool_state_scope() and tool_state_instance() as shown in 2.9. Passing the same explicit instance shares it intentionally; using a scope gives each worker a private default.
Three utilities appear often in custom scaffolds:
| Utility | Use | Evaluation caution |
|---|---|---|
collect(*coroutines) |
Run independent agents or tasks concurrently, with spans, across Inspect's async backends | Concurrency changes wall time but should not change claims about per-agent quality; attribute tokens by span |
background(fn) |
Run a sample-lifetime background worker that Inspect cancels at sample end | Clean up in finally, and record whether background work influenced the measured outcome |
sandbox_service(...) |
Expose host Python methods to code inside a sandbox through a filesystem queue | It is a communication mechanism, not an authentication or isolation boundary |
A compaction handler can also be embedded in a custom loop. Create one handler per divergent history, call compact_input() before generation and record_output() afterwards, force it on overflow and reset it after rewriting history. Do not share one handler across branched or parallel conversations: their histories diverge, and the handler's incremental assumptions stop being valid.
8.7 Validate a custom agent as rigorously as the model#
A custom scaffold is code, so test it like code before drawing model conclusions:
- Scripted smoke tests: run a mock model through the happy path, a tool error, a parsing error and a refusal.
- Termination tests: prove the loop stops on no calls, on submission, at the cap and after your custom condition.
- Malformed-history tests: if you filter calls, inspect the next request rather than assuming the shape is valid.
- Concurrency tests: run concurrent samples or workers and check store instances, span ownership and output copy-back.
- Baseline comparison: compare against
react()on the same dataset, model, tools and limits. If the custom loop wins, inspect transcripts before crediting the architecture; the win may come from one prompt sentence or one hidden retry.
Part 9: Multi-agent systems: handoffs, agents as tools and workflows#
Deep-dive
9.1 Start with the architecture question, not the mechanism#
General architecture decisions (whether you need more than one agent at all, which topology fits, what coordination costs) live in 08D.1 and 08D.3, and the wider workflow-versus-agent decision is in 08A.9 and 13A.8. This lesson keeps only the part specific to evaluating with Inspect. Inspect gives three ways to compose agents:
handoff()shares a conversation: control moves to a specialist and then returns.as_tool()isolates a subtask: the supervisor sends one string and receives one string.run()andcollect()let your code orchestrate agents explicitly: routing is deterministic Python, not a model decision.
The evaluation question comes first. Are you measuring a model's ability to choose a specialist, a specialist's ability to solve a delegated task, or the end-to-end reliability of an architecture? The mechanism determines what evidence exists, and what can go wrong: routing errors, context loss in a handoff, prompt-injection propagation through shared history, or duplicated work in parallel agents. 10A.12 teaches how to score each of those, and 10B.5, Part 13 does the same with DeepEval.
The single-agent baseline rule from 6.5 is especially important here: treat multi-agent design as a hypothesis to test, not a default best practice.
9.2 handoff(): what each agent sees#
handoff(agent, ...) creates a tool whose default name is transfer_to_<agent-name>. When the supervisor calls it, control passes to the target agent. The target sees the shared message history with system messages removed and its own system prompt added. When it finishes, its turns are filtered back into the shared history and Inspect appends a user message saying the specialist has completed its work.
sequenceDiagram
participant T as triage agent
participant H as Inspect
participant R as returns agent
Note over T,R: handoff(returns)
T->>H: transfer_to_returns()
H->>R: shared history, system messages removed
R->>H: its own turns and tool calls
H->>T: R's turns appended via content_only, then the completed-work message
Note over T,R: as_tool(returns)
T->>H: returns(input="Refund ORD-1002 in full")
H->>R: its system prompt + the input string only
R->>H: final completion
H->>T: one tool result stringThe verified signature is:
# Signatures, not a runnable file
handoff(agent, description=None, input_filter=None, output_filter=content_only,
tool_name=None, limits=[], **agent_kwargs)s12_handoff.py scripts one mock model behind both agents. The callable can tell whose turn it is by the tools offered, so the printout is a precise record of what each side saw:
# s12_handoff.py: a triage agent hands off to a returns specialist; what each agent saw (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import handoff, last_message, react, remove_tools
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessage, get_model
from inspect_ai.tool import ToolDef
from desk import M, call, docs_search, orders_get, refund_outcome, refunds_issue
returns = react(name="returns", description="Handles refunds and returns for existing orders.",
prompt="You are the returns specialist.", tools=[orders_get(), refunds_issue()])
SAMPLE = Sample(id="refund-lost", input="Hi, I'm Bo (bo@example.com). Order ORD-1002 never arrived. Refund it please.",
metadata={"expect_refund": {"order_id": "ORD-1002", "amount_cents": 8450}})
def two_agent_script(seen: list):
"""One mock model for both agents; it tells them apart by the tools they were offered."""
plans = {
"triage": [call("transfer_to_returns", "A refund: handing to returns."),
call("submit", answer="Your refund of 84.50 has been issued.")],
"returns": [call("orders_get", order_id="ORD-1002"),
call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("submit", "Refund issued.", answer="Refunded 8450 cents for ORD-1002.")],
}
turns = {"triage": 0, "returns": 0}
def fn(input: list[ChatMessage], tools, tool_choice, config):
who = "triage" if any(t.name == "transfer_to_returns" for t in tools) else "returns"
seen.append((who, [f"{m.role}:{m.text[:38]}" for m in input]))
plan = plans[who]
out = plan[turns[who]] if turns[who] < len(plan) else call("submit", answer="(script exhausted)")
turns[who] += 1
return out
return get_model(M, custom_outputs=fn, memoize=False)
def run(label: str, handoff_tool, show_history: bool = False, **eval_args):
seen: list = []
triage = react(name="triage", prompt="You are the triage agent. Route each request.",
tools=[docs_search(), handoff_tool])
log = eval(Task(dataset=[SAMPLE], solver=triage, scorer=refund_outcome()),
model=two_agent_script(seen), log_dir="logs/s12", display="none",
metadata={"variant": label}, **eval_args)[0]
s = log.samples[0]
print(f"\n== {label}: score={s.scores['refund_outcome'].value} completion={s.output.completion!r}")
if s.limit:
print(f" sample limit: {s.limit.type} ({s.limit.reason}); returns agent requests: "
f"{sum(1 for who, _ in seen if who == 'returns')}")
return log
first_returns_call = next(msgs for who, msgs in seen if who == "returns")
print(" returns agent's FIRST request:")
for line in first_returns_call:
print(" ", line.replace("\n", " "))
if show_history:
print(" shared history after the run:")
for m in s.messages:
print(f" [{m.role:9}] {m.text[:62]!r}".replace("\\n", " "))
print(" spans:", [(e.name, e.type) for e in s.events if e.event == "span_begin"
and e.type in ("agent", "handoff")])
return log
h = handoff(returns)
print("handoff tool:", ToolDef(h).name, "|", ToolDef(h).description, "| params:", list(ToolDef(h).parameters.properties))
log = run("handoff(returns), default filters", h, show_history=True)
run("input_filter=remove_tools", handoff(returns, input_filter=remove_tools))
run("output_filter=last_message", handoff(returns, output_filter=last_message), show_history=True)
async def redact_emails(messages: list[ChatMessage]) -> list[ChatMessage]:
"""A custom filter: the specialist does not need the customer's email address."""
out = []
for m in messages:
if isinstance(m.content, str) and "@" in m.content:
words = ["<email>" if "@" in w else w for w in m.content.split()]
m = m.model_copy(update={"content": " ".join(words)})
out.append(m)
return out
run("input_filter=redact_emails (custom)", handoff(returns, input_filter=redact_emails))
# A misuse: last_message is an OUTPUT filter. As an input filter the specialist receives only the
# transfer notice, and in 0.3.292 the run never finishes. A time limit turns the hang into a result.
run("input_filter=last_message (misuse), time_limit=5", handoff(returns, input_filter=last_message),
time_limit=5)handoff tool: transfer_to_returns | Handles refunds and returns for existing orders. | params: []
== handoff(returns), default filters: score=C completion='tool call for tool submit\n\nYour refund of 84.50 has been issued.'
returns agent's FIRST request:
system:You are the returns specialist. You
user:Hi, I'm Bo (bo@example.com). Order ORD
assistant:A refund: handing to returns.
tool:Successfully transferred to returns.
shared history after the run:
[system ] 'You are the triage agent. Route each request. You are part o'
[user ] "Hi, I'm Bo (bo@example.com). Order ORD-1002 never arrived. Ref"
[assistant] 'A refund: handing to returns.'
[tool ] 'Successfully transferred to returns.'
[assistant] "[returns] tool call for tool orders_get orders_get(order_id='O"
[user ] '{"order_id": "ORD-1002", "customer_email": "bo@example.com", "'
[assistant] '[returns] tool call for tool refunds_issue refunds_issue( '
[user ] '{"refunded": true, "order_id": "ORD-1002", "amount_cents": 845'
[assistant] '[returns] Refund issued. Refunded 8450 cents for ORD-1002.'
[user ] 'The returns agent has completed its work.'
[assistant] 'tool call for tool submit Your refund of 84.50 has been issue'
spans: [('triage', 'agent'), ('returns', 'handoff'), ('returns', 'agent')]
== input_filter=remove_tools: score=C completion='tool call for tool submit\n\nYour refund of 84.50 has been issued.'
returns agent's FIRST request:
system:You are the returns specialist. You
user:Hi, I'm Bo (bo@example.com). Order ORD
assistant:A refund: handing to returns.
user:Successfully transferred to returns.
== output_filter=last_message: score=C completion='tool call for tool submit\n\nYour refund of 84.50 has been issued.'
returns agent's FIRST request:
system:You are the returns specialist. You
user:Hi, I'm Bo (bo@example.com). Order ORD
assistant:A refund: handing to returns.
tool:Successfully transferred to returns.
shared history after the run:
[system ] 'You are the triage agent. Route each request. You are part o'
[user ] "Hi, I'm Bo (bo@example.com). Order ORD-1002 never arrived. Ref"
[assistant] 'A refund: handing to returns.'
[tool ] 'Successfully transferred to returns.'
[assistant] '[returns] Refund issued. Refunded 8450 cents for ORD-1002.'
[user ] 'The returns agent has completed its work.'
[assistant] 'tool call for tool submit Your refund of 84.50 has been issue'
spans: [('triage', 'agent'), ('returns', 'handoff'), ('returns', 'agent')]
== input_filter=redact_emails (custom): score=C completion='tool call for tool submit\n\nYour refund of 84.50 has been issued.'
returns agent's FIRST request:
system:You are the returns specialist. You
user:Hi, I'm Bo <email> Order ORD-1002 neve
assistant:A refund: handing to returns.
tool:Successfully transferred to returns.
== input_filter=last_message (misuse), time_limit=5: score=I completion='A refund: handing to returns.'
sample limit: time (Time limit exceeded. limit: 5 seconds); returns agent requests: 0Read the first request to the returns agent slowly. It contains:
- the specialist's own system prompt, not the triage system prompt;
- the original user message;
- the triage assistant message that requested transfer;
- the tool message
Successfully transferred to returns.
The shared history after the run is different again. The specialist's messages are prefixed [returns]; its tool calls are rendered as text; its tool results become user messages; its submit call is gone; and the user message The returns agent has completed its work. tells the supervisor control has returned. This is the default output_filter=content_only at work: it converts a rich agent transcript into plain conversational evidence the supervisor can consume.
The transcript spans are the reliable structure: ('triage', 'agent'), ('returns', 'handoff') and ('returns', 'agent'). Part 10 uses exactly those spans to build a multi-agent trace.
9.3 Input and output filters: privacy, compaction and misuse#
The filter names are easy to confuse because they operate at different boundaries:
| Filter | Boundary | Effect |
|---|---|---|
input_filter |
Shared history to specialist input | Controls what the receiver sees before it starts |
output_filter |
Specialist messages back into shared history | Controls what the supervisor and later agents inherit |
The built-ins are:
content_only: remove system messages and reasoning traces, strip provider-internal fields, render tool calls as text, turn tool results into user messages and render provider-run (server-side) tool use as text. This is the default output filter, which is why the specialist's lookup result appeared as a[user]line in the shared history.remove_tools: drop tool messages and assistant tool calls.last_message: keep only the final message.
The default input_filter is None, not content_only: the receiver sees the global history except for system messages. The output shows the practical uses. input_filter=remove_tools changes how the transfer notice appears, while a custom redact_emails filter removes Bo's email address from the specialist's input. That is a real privacy and data-minimization control: the specialist can refund by order id without seeing an email address it does not need.
output_filter=last_message keeps only the specialist's final report in the shared history. In the output, the intermediate order lookup and refund details no longer appear as separate user messages. This reduces context growth and hides noisy intermediate work, but it also destroys evidence the supervisor might need. Choose it when the specialist's report is designed to be self-contained, not as a generic optimization.
The last case is a warning. last_message is an output filter. As an input_filter it keeps only the final message of the transferred conversation, and at that point the final message is the Successfully transferred to returns. tool result. In 0.3.292 handoff() appends that tool message, runs the input filter, strips system messages and starts the specialist on what is left: one orphan tool message, with no user request and no assistant tool call before it. The printed returns agent requests: 0 is the evidence: the specialist never issued a single model request, so the sample ran until the five-second time limit stopped it (sample limit: time). That is observed behaviour of this version, not documented behaviour, and whether upstream treats it as a bug is unconfirmed, so recheck it against the CHANGELOG for the version you run. Agent systems need live budgets because deadlock, ping-pong and context starvation do not always raise exceptions. 10B.15 covers limits in depth.
9.4 as_tool(): isolated delegation, string in and string out#
as_tool(agent, ...) turns an agent into an ordinary-looking tool (the agent-as-a-tool pattern, see 08A.11, Part 4 and 08D.3). The supervisor sees an input string parameter plus any execute parameters the agent exposes; the sub-agent starts with only its own prompt and that string, and its final completion becomes the tool result.
# Signatures, not a runnable file
as_tool(agent, description=None, limits=[], max_output=0, **agent_kwargs)s13_as_tool.py shows isolation and parameter exposure:
# s13_as_tool.py: agents as tools, agent parameters and currying (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import Agent, AgentState, agent, as_tool, handoff, react
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessage, ChatMessageSystem, get_model
from inspect_ai.tool import ToolDef
from desk import M, call, orders_get, refund_outcome, refunds_issue, say
# --- 1. Agent parameters become tool parameters; curried ones disappear from the schema.
@agent(description="Drafts the reply to send to the customer.")
def drafter() -> Agent:
async def execute(state: AgentState, tone: str = "friendly", max_words: int = 80) -> AgentState:
"""Draft a reply.
Args:
tone: Tone of voice, for example friendly or formal.
max_words: Upper bound on the length of the reply.
"""
state.messages.insert(0, ChatMessageSystem(content=f"Write a {tone} reply in at most {max_words} words."))
state.output = await get_model().generate(state.messages)
state.messages.append(state.output.message)
return state
return execute
for label, t in [("as_tool(drafter())", as_tool(drafter())),
("as_tool(drafter(), max_words=50)", as_tool(drafter(), max_words=50)),
("handoff(drafter())", handoff(drafter()))]:
td = ToolDef(t)
print(f"{label:34} -> {td.name}: {list(td.parameters.properties)}")
# --- 2. as_tool isolation: the specialist sees ONLY its prompt and the input string.
returns = react(name="returns", description="Handles refunds and returns for existing orders.",
prompt="You are the returns specialist.", tools=[orders_get(), refunds_issue()])
seen: list = []
plans = {
"triage": [call("returns", "Delegating the refund.", input="Refund ORD-1002 in full: lost in transit."),
call("submit", answer="Your refund of 84.50 has been issued.")],
"returns": [call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("submit", "Refund issued.", answer="Refunded 8450 cents for ORD-1002.")],
}
turns = {"triage": 0, "returns": 0}
def fn(input: list[ChatMessage], tools, tool_choice, config):
who = "triage" if any(t.name == "returns" for t in tools) else "returns"
seen.append((who, [f"{m.role}:{m.text[:44]}" for m in input]))
out = plans[who][turns[who]]
turns[who] += 1
return out
triage = react(name="triage", prompt="You are the triage agent.", tools=[as_tool(returns)])
sample = Sample(id="refund-lost", input="Hi, I'm Bo (bo@example.com). ORD-1002 never arrived. Refund it please.",
metadata={"expect_refund": {"order_id": "ORD-1002", "amount_cents": 8450}})
log = eval(Task(dataset=[sample], solver=triage, scorer=refund_outcome()),
model=get_model(M, custom_outputs=fn, memoize=False), log_dir="logs/s13", display="none")[0]
s = log.samples[0]
print("\nreturns agent's first request:", next(m for who, m in seen if who == "returns"))
print("score:", s.scores["refund_outcome"].value)
print("shared history:")
for m in s.messages:
print(f" [{m.role:9}] {m.text[:70]!r}")
print("spans:", [(e.name, e.type) for e in s.events if e.event == "span_begin" and e.type in ("agent", "tool")])as_tool(drafter()) -> drafter: ['input', 'tone', 'max_words']
as_tool(drafter(), max_words=50) -> drafter: ['input', 'tone']
handoff(drafter()) -> transfer_to_drafter: ['tone', 'max_words']
returns agent's first request: ['system:You are the returns specialist.\n\n\nYou are a ', 'user:Refund ORD-1002 in full: lost in transit.']
score: C
shared history:
[system ] 'You are the triage agent.\n\n\nYou are a helpful assistant attempting to '
[user ] "Hi, I'm Bo (bo@example.com). ORD-1002 never arrived. Refund it please."
[assistant] 'Delegating the refund.'
[tool ] 'Refund issued.\n\nRefunded 8450 cents for ORD-1002.'
[assistant] 'tool call for tool submit\n\nYour refund of 84.50 has been issued.'
spans: [('triage', 'agent'), ('returns', 'tool'), ('returns', 'agent'), ('refunds_issue', 'tool'), ('submit', 'tool'), ('submit', 'tool')]The returns agent's first request is just two messages: its system prompt and Refund ORD-1002 in full: lost in transit. It does not see Bo's original email, the triage wording or any earlier tool results unless the supervisor copies them into the input string. In the shared history, the whole sub-agent run collapses into one tool result: 'Refund issued.\n\nRefunded 8450 cents for ORD-1002.' The sub-agent's internal calls are not messages in the supervisor conversation, but they are present as events and spans in the transcript.
That isolation is the central trade-off:
Whether to isolate a subtask is an architecture decision (08D.1, 08D.3). For evaluation, the point is that the delegation brief becomes a measurable artefact. In 10A.12, 3.5, a thin or lossy brief is a handoff failure. With as_tool() you can grade the input string directly because it is ordinary tool-call arguments.
9.5 Agent parameters and currying#
Agents can take parameters beyond state. Their docstring Args: become tool parameter descriptions for a supervisor. In the probe, drafter() exposes tone and max_words:
as_tool(drafter())exposesinput,toneandmax_words.as_tool(drafter(), max_words=50)curriesmax_words, so it disappears from the schema.handoff(drafter())exposestoneandmax_wordsbut noinput, because a handoff already carries conversation context.
This is a powerful way to let the supervisor choose granularity, depth or tone. It is also a prompt-injection and cost surface. If a supervisor can set max_words=100000 or count=50, the parameter schema is part of your threat and cost model. Constrain values in the implementation, not only in the description, and curry parameters that should be fixed by the eval designer.
9.6 Explicit workflows with run() and collect()#
Sometimes routing is fixed by policy (classify, act, draft, audit), so the model should not choose it; 08A.9 covers when that is the right call (see also 13A.8, Part 11). run() lets Python orchestrate agents while still using Inspect's transcript and model machinery. collect() runs independent branches concurrently and creates spans, preferring it over raw asyncio.gather() because Inspect also supports Trio.
s14_workflow.py builds a deterministic refund workflow:
# s14_workflow.py: an explicit multi-agent workflow with run() and collect() (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import react, run
from inspect_ai.dataset import Sample
from inspect_ai.model import ChatMessage, ModelOutput, get_model
from inspect_ai.solver import Generate, Solver, TaskState, solver
from inspect_ai.util import collect
from desk import M, call, desk_samples, orders_get, refund_outcome, refunds_issue
classifier = react(name="classifier", prompt="CLASSIFY the request as refund, policy or other.", tools=[])
returns = react(name="returns", prompt="RETURNS specialist.", tools=[orders_get(), refunds_issue()])
drafter = react(name="drafter", prompt="DRAFT the customer reply.", tools=[])
auditor = react(name="auditor", prompt="AUDIT the refund against policy.", tools=[orders_get()])
def without_system(messages: list[ChatMessage]) -> list[ChatMessage]:
return [m for m in messages if m.role != "system"]
@solver
def refund_workflow(strip_system: bool = True) -> Solver:
async def solve(state: TaskState, generate: Generate) -> TaskState:
label = await run(classifier, state.messages) # step 1: route (code decides, not a model)
if "refund" not in label.output.completion:
state.output = label.output
return state
done = await run(returns, state.messages) # step 2: act
history = without_system(done.messages) if strip_system else done.messages
draft, audit = await collect( # step 3: two independent agents, concurrently
run(drafter, history), run(auditor, history))
state.messages = draft.messages # copy back what the scorer should read
state.output = draft.output
state.metadata["audit"] = audit.output.completion
return state
return solve
def fn(input: list[ChatMessage], tools, tool_choice, config) -> ModelOutput:
role = input[0].text.split()[0] # CLASSIFY / RETURNS / DRAFT / AUDIT
turn = sum(1 for m in input if m.role == "assistant")
if role == "CLASSIFY":
return call("submit", answer="refund")
if role == "RETURNS":
steps = [call("orders_get", order_id="ORD-1002"),
call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("submit", answer="refunded 8450")]
return steps[min(turn, 2)]
if role == "DRAFT":
return call("submit", answer="Hi Bo, your refund of 84.50 is on its way.")
return call("submit", answer="OK: lost parcel, full refund within policy.")
for strip in (False, True):
log = eval(Task(dataset=desk_samples()[:1], solver=refund_workflow(strip_system=strip), scorer=refund_outcome()),
model=get_model(M, custom_outputs=fn, memoize=False), log_dir="logs/s14", display="none")[0]
s = log.samples[0]
print(f"== strip_system={strip}")
print(" score:", s.scores["refund_outcome"].value, "| completion:", repr(s.output.completion))
print(" audit kept in metadata:", repr(s.metadata["audit"]))
print(" agent spans in order:", [e.name for e in s.events if e.event == "span_begin" and e.type == "agent"])
print(" system prompts the drafter received:",
[m.text.split()[0] for m in s.messages if m.role == "system"])== strip_system=False
score: C | completion: 'tool call for tool submit\n\nHi Bo, your refund of 84.50 is on its way.'
audit kept in metadata: 'tool call for tool submit\n\nOK: lost parcel, full refund within policy.'
agent spans in order: ['classifier', 'returns', 'drafter', 'auditor']
system prompts the drafter received: ['DRAFT', 'RETURNS']
== strip_system=True
score: C | completion: 'tool call for tool submit\n\nHi Bo, your refund of 84.50 is on its way.'
audit kept in metadata: 'tool call for tool submit\n\nOK: lost parcel, full refund within policy.'
agent spans in order: ['classifier', 'returns', 'drafter', 'auditor']
system prompts the drafter received: ['DRAFT']The workflow has three steps: the classifier routes, the returns specialist acts, then drafter and auditor run concurrently on the completed history. The audit is stored in sample metadata rather than being allowed to overwrite the customer-facing answer. This is a useful pattern: not every agent in a system contributes to the final message. Some produce evidence, review or control signals.
The strip_system comparison exposes a real copy semantics pitfall. Passing one agent's messages into another copies everything, including the first agent's system prompt. With strip_system=False, the drafter receives both DRAFT and RETURNS system prompts. With strip_system=True, it receives only its own. When you wire agents manually, decide deliberately whether prior system prompts are context, contamination or a prompt-injection path. Usually they are contamination: strip them or rebuild a clean task-specific history.
Remember 6.4: the workflow copies draft.messages and draft.output back into the solver state. Without that copy, the scorer sees nothing. Concurrent branches each receive copies too, so they cannot mutate one another's histories accidentally; shared state must be explicit through the store or sandbox.
9.7 Limits differ by composition mechanism#
An agent loop can fail by never finishing, so passing limits=[...] to a composition wrapper scopes a limit to that one invocation. 10B.15, section 7.9 owns the experiment (the same looping sub-agent under a message_limit(6) through as_tool(), handoff() and as_solver(), with real output) and the full explanation. The outcome table is the part to keep in your head here:
| Mechanism | What happens when the sub-agent hits the limit |
|---|---|
as_tool() |
The tool call returns ToolCallError(type="limit") with the message The tool exceeded its message limit of 6.; the supervisor can recover and the sample continues |
handoff() |
The sub-agent stops, a user message such as The orders_worker exceeded its message limit of 6. is appended, and the supervisor can continue |
as_solver() |
The sample itself records the limit and terminates, as with a normal sample limit |
run() |
Returns (state, LimitExceededError) for the limits passed to it; your workflow decides whether to continue, recover or re-raise. Any other limit (a sample limit, an enclosing scoped limit) still propagates as an exception |
Design rule: if a specialist failure should be recoverable by the supervisor, use as_tool() or handoff() with a scoped limit; if a runaway agent invalidates the whole measurement, solver-level termination is cleaner; in an explicit workflow, always handle the error object run() returns. One trap: a handoff's message limit counts the shared conversation, not only the messages the specialist produced after the handoff, so a specialist handed a long history can hit a small limit after one turn. And as_tool(), handoff() and as_solver() copy their limit objects for every invocation, so the message_limit(6) object you constructed never reports usage itself: read limit outcomes from the transcript (SampleLimitEvents, tool errors, the appended messages), not from the object.
9.8 What spans let you measure#
The span tree distinguishes three things that prose cannot:
- an
agentspan for each agent execution; - a
handoffspan for control transfer; toolspans owned by whichever agent span encloses them.
That ownership is what makes per-agent cost, tool-use and failure attribution possible. Without it, a supervisor and specialist sharing one model endpoint look like one undifferentiated sequence of calls. With it, you can compute the per-agent trajectories, token counts and routing paths required by 10A.12. Part 10 implements the adapter.
9.9 Choosing a mechanism#
Which design to use is a general architecture decision, taught in 08A.9 (workflow or agent) and 08D.1 and 08D.3 (single or multi-agent), with the decision records in 13A.8. This lesson keeps only the Inspect and evaluation part. The mapping is: a specialist that must see and extend the conversation is handoff() (risks: context leakage, noisy history); a self-contained subtask returning one report is as_tool() (risks: a thin delegation brief, hidden internal evidence); routing fixed by business logic is run() in a solver (code owns all recovery); independent reviews or draft and audit branches are collect() of run() calls (risks: duplicated cost, inconsistent shared world state); long-horizon autonomous decomposition is deepagent() or a custom design (a large scaffold surface that must beat a react() baseline).
A good eval does not mix all of them merely because they exist. Add one mechanism at a time and measure the delta.
Part 10: Grading agent runs#
10.1 Grade three different things separately#
An agent run has at least three separable results:
- Outcome: did the world end in the required state?
- Process: did the agent act in an acceptable way to get there?
- Cost and reliability: how many messages, tokens, seconds, retries and trials did it take?
Inspect gives you the first two through scorers and the third through events, stats, epochs and limits. The methods are the ones you already own: end-state graders and partial credit in 10A.7, Part 3, trajectory graders in 10A.7, Part 4, reliability in 10A.7, Part 5 and multi-agent interaction metrics in 10A.12. This part maps them onto Inspect's concrete objects.
10.2 An outcome scorer, a process scorer and three controls#
s18_desk_eval.py is the complete support-desk eval. The outcome scorer is refund_outcome() from desk.py: it reads the store and requires exactly the expected refund and no email. The process scorer is deliberately small: the agent must not email, and it must look an order up before refunding it. The three scripted systems are controls:
- oracle: the correct procedure;
- null: immediately says it cannot help;
- careless: gets some outcomes right while violating process and making unsupported claims.
# s18_desk_eval.py: the support-desk agent eval with an outcome and a trajectory scorer, and its controls (lesson 10B.14)
from inspect_ai import Task, eval, task
from inspect_ai.agent import AgentSubmit, react
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Scorer, Target, accuracy, scorer, stderr
from inspect_ai.solver import TaskState
from desk import call, desk_samples, desk_tools, refund_outcome, scripted
MUTATING = {"refunds_issue", "send_email"}
@scorer(metrics=[accuracy(), stderr()])
def tool_policy() -> Scorer:
"""Process checks from the messages: look the order up before refunding, and never email."""
async def score(state: TaskState, target: Target) -> Score:
names = [c.function for m in state.messages for c in (getattr(m, "tool_calls", None) or [])]
problems = []
if "send_email" in names:
problems.append("emailed the customer")
if "refunds_issue" in names and ("orders_get" not in names
or names.index("orders_get") > names.index("refunds_issue")):
problems.append("refund before lookup")
return Score(value=INCORRECT if problems else CORRECT,
explanation="; ".join(problems) or "ok", metadata={"tools": names})
return score
@task
def desk_eval() -> Task:
return Task(dataset=desk_samples(),
solver=react(prompt="You are a support agent for an online shop.", tools=desk_tools(),
submit=AgentSubmit(answer_only=True)),
scorer=[refund_outcome(), tool_policy()],
message_limit=30) # a budget on every run (10B.15 covers limits in depth)
ORACLE = {
"ORD-1002": [call("orders_get", order_id="ORD-1002"),
call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("submit", answer="Refunded 84.50.")],
"refund policy": [call("docs_search", query="refund policy"), call("submit", answer="30 days.")],
"ORD-9999": [call("orders_get", order_id="ORD-9999"), call("submit", answer="No such order.")],
}
NULL = {k: [call("submit", answer="I can't help with that.")] for k in ORACLE}
CARELESS = { # right outcome on the refund, wrong process; and it emails
"ORD-1002": [call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("send_email", to="bo@example.com", subject="Refund", body="Done."),
call("submit", answer="Refunded.")],
"refund policy": [call("submit", answer="30 days.")],
"ORD-9999": [call("submit", answer="Refunded.")],
}
for label, plans in [("oracle", ORACLE), ("null", NULL), ("careless", CARELESS)]:
log = eval(desk_eval(), model=scripted(plans), log_dir="logs/s18", display="none")[0]
m = {sc.name: round(sc.metrics["accuracy"].value, 3) for sc in log.results.scores}
print(f"{label:9} {m} | per sample:",
[(s.id, s.scores["refund_outcome"].value, s.scores["tool_policy"].value) for s in log.samples])oracle {'refund_outcome': 1.0, 'tool_policy': 1.0} | per sample: [('policy', 'C', 'C'), ('refund-lost', 'C', 'C'), ('unknown-order', 'C', 'C')]
null {'refund_outcome': 0.667, 'tool_policy': 1.0} | per sample: [('policy', 'C', 'C'), ('refund-lost', 'I', 'C'), ('unknown-order', 'C', 'C')]
careless {'refund_outcome': 0.667, 'tool_policy': 0.667} | per sample: [('policy', 'C', 'C'), ('refund-lost', 'I', 'I'), ('unknown-order', 'C', 'C')]The null control is the most important line in the output. It scores 0.667 on outcome because two of the three tasks expect no mutation. A do-nothing agent looks good on a dataset dominated by negative examples. This is the agentic version of class imbalance. Report per-slice results, include positive action cases, and compare against a null control before celebrating a score.
The careless control shows the complementary problem. On unknown-order it claims "Refunded." but performs no refund, so the outcome scorer passes it. End state alone cannot detect dishonest or unsupported narration when no action was required. That is the honesty gap from 10A.7, 3.5. Conversely, on refund-lost the world mutation is correct but the agent emails the customer and skips the lookup, so outcome fails because email is forbidden in this eval and process fails independently. A single aggregate number would hide which layer failed.
The process scorer in this sample reads state.messages for clarity. That is sufficient for this direct react() run because the calls of interest are ordinary visible calls. It is not sufficient in general: submit calls are removed, handoff output is rewritten and as_tool() sub-agent calls never enter the supervisor's messages. Production trajectory grading should read events, as the next sections do.
10.3 Events, not messages, are the evidence#
The rule is simple:
- use
state.output.completionfor answer scoring; - use the store or sandbox for outcome scoring;
- use
sample.eventsfor trajectory, cost and multi-agent attribution; - use
state.messagesonly when you specifically need the final conversational state the next model would see.
Events preserve what conversational state cannot: the exact tool arguments, errors, timing, span ownership, model inputs (including the placeholder replays of a model_input hook, 3.5) and calls that later get rewritten. 10B.13, Part 4 is the general event reference, and 10B.16, Part 2 turns the rule into the methodology for whole agent evals. Here we need the small subset that maps to evalkit: ToolEvent, ModelEvent and SpanBeginEvent.
10.4 Adapters from Inspect to evalkit#
inspect_trace.py is a bridge file written for this lesson. It converts an Inspect sample into two objects you already have: Trajectory from agent_eval.py in 10A.7 and MASTrace from mas_eval.py in 10A.12. Save it beside the evalkit modules, with agent_eval.py, mas_eval.py, compare.py and judge_validation.py importable as described in Setup.
# inspect_trace.py: adapters from an Inspect sample to evalkit's Trajectory (10A.7) and MASTrace (10A.12) (lesson 10B.14)
import re
from agent_eval import StepRecord, Trajectory
from inspect_ai.log import EvalSample
from mas_eval import AgentSpan, MASTrace
def _spans(sample: EvalSample) -> dict:
return {e.id: e for e in sample.events if e.event == "span_begin"}
def _owner(span_id: str | None, spans: dict) -> str:
"""The agent that owns an event: the nearest enclosing span of type 'agent'."""
while span_id in spans:
if spans[span_id].type == "agent":
return spans[span_id].name
span_id = spans[span_id].parent_id
return "solver"
def _status(error) -> str:
if error is None:
return "ok"
return "denied" if error.type == "approval" else "error"
def trajectory_from_inspect(sample: EvalSample, *, agent: str | None = None,
skip: tuple[str, ...] = ("submit",)) -> Trajectory:
"""One 10A.7 Trajectory from the sample's ToolEvents (events, not messages:
messages drop react's submit calls and as_tool() sub-agents' calls)."""
spans = _spans(sample)
mine = lambda e: agent is None or _owner(e.span_id, spans) == agent
tools = [e for e in sample.events if e.event == "tool" and e.function not in skip and mine(e)]
models = [e for e in sample.events if e.event == "model" and mine(e)]
return Trajectory(
task_id=str(sample.id), agent=agent or "all",
steps=[StepRecord(seq=i, tool=e.function, args=dict(e.arguments), status=_status(e.error),
detail=e.error.message if e.error else "", latency_s=e.working_time or 0.0)
for i, e in enumerate(tools)],
final_answer=sample.output.completion,
wall_s=sample.total_time or 0.0,
tokens_in=sum(e.output.usage.input_tokens for e in models if e.output.usage),
tokens_out=sum(e.output.usage.output_tokens for e in models if e.output.usage))
def trace_from_inspect(sample: EvalSample, *, system: str) -> MASTrace:
"""A 10A.12 MASTrace from the span tree: agent spans become agent_run spans,
handoff spans become handoffs (attrs['to']), tool and model events keep their owner.
payload_seen is the text of the receiver's FIRST model request, so context-transfer
grading reads what the receiver actually saw."""
spans = _spans(sample)
t0 = sample.events[0].timestamp
secs = lambda e: (e.timestamp - t0).total_seconds()
ends = {e.id: secs(e) for e in sample.events if e.event == "span_end"}
first_input: dict[str, str] = {}
for e in sample.events:
if e.event == "model":
first_input.setdefault(_owner(e.span_id, spans), "\n".join(m.text for m in e.input))
out: list[AgentSpan] = []
turn = 0
for e in sample.events:
owner = _owner(e.span_id, spans)
if e.event == "span_begin" and e.type == "agent":
out.append(AgentSpan(e.id, e.parent_id, e.name, "agent_run", secs(e), ends.get(e.id, secs(e))))
elif e.event == "span_begin" and e.type == "handoff":
turn += 1
out.append(AgentSpan(e.id, e.parent_id, _owner(e.parent_id, spans), "handoff", secs(e),
ends.get(e.id, secs(e)), role="coordination",
attrs={"to": e.name, "turn": turn, "payload_seen": first_input.get(e.name, "")}))
elif e.event == "tool":
out.append(AgentSpan(e.id, e.span_id, owner, "tool_call", secs(e), secs(e) + (e.working_time or 0),
status=_status(e.error), attrs={"tool": e.function, "args": dict(e.arguments)}))
elif e.event == "model" and e.output.usage:
out.append(AgentSpan(f"m{len(out)}", e.span_id, owner, "model_call", secs(e),
secs(e) + (e.working_time or 0), tokens_in=e.output.usage.input_tokens,
tokens_out=e.output.usage.output_tokens))
return MASTrace(trace_id=f"{sample.id}-e{sample.epoch}", task_id=str(sample.id), system=system,
spans=out, final_answer=sample.output.completion)
def fields_in(text: str) -> dict:
"""Pull the fields 10A.12's context_transfer() grades out of free text."""
found = {"order_id": re.search(r"ORD-\d{4}", text), "customer_email": re.search(r"[\w.]+@[\w.]+\w", text)}
return {k: m.group(0) for k, m in found.items() if m}Three adapter decisions are worth understanding rather than copying blindly.
First, ownership is recovered by walking up the span tree to the nearest span of type agent. A tool event does not itself say "the returns agent did this"; its span_id places it inside nested spans. Without that walk, multi-agent token and tool attribution collapses.
Second, trajectory_from_inspect() skips submit by default. Submission is scaffold machinery, not an action in the world. Keep it if the research question is about submission behaviour; skip it when grading domain-tool use.
Third, trace_from_inspect() stores the receiver's first model input in payload_seen. Context transfer must grade what the receiver actually saw, not what the sender intended to send. That is the core principle of 10A.12, 3.4, and Inspect's model events make it measurable.
10.5 Running the graders on real Inspect logs#
s16_grade_from_log.py reads back the logs produced by s02 and s12 and applies evalkit graders without changing them. Run it after those two samples so the logs exist. s12 tags each run with metadata={"variant": label} and s16 pairs logs to variants by that tag, taking the newest log per variant, so rerunning s12 into the same logs/s12 folder cannot swap the labels (pairing by file modification time would mislabel silently). A clean logs/ folder is still the simplest way to keep the folder readable. It uses required_order, tool_unused and tool_call_prf from 10A.7, plus context_transfer, pingpong and to_trajectories from 10A.12.
# s16_grade_from_log.py: grade Inspect runs with evalkit's agent and multi-agent graders (lesson 10B.14)
from inspect_ai.log import list_eval_logs, read_eval_log
from agent_eval import GradeContext, Task, World, required_order, tool_call_prf, tool_unused
from inspect_trace import fields_in, trace_from_inspect, trajectory_from_inspect
from mas_eval import context_transfer, pingpong, to_trajectories
def logs_in(path: str):
return [read_eval_log(i.name) for i in sorted(list_eval_logs(path), key=lambda i: i.mtime)]
# --- 1. Single agent (s02): 10A.7's trajectory graders, unchanged, on Inspect transcripts.
GRADERS = { # per task: what the trajectory must and must not contain
"refund-lost": [required_order(["orders_get", "refunds_issue"]), tool_unused("send_email")],
"policy": [tool_unused("refunds_issue", "send_email")],
"unknown-order": [tool_unused("refunds_issue", "send_email")],
}
for s in logs_in("logs/s02")[-1].samples:
traj = trajectory_from_inspect(s)
graders = GRADERS[s.id]
ctx = GradeContext(task=Task(task_id=str(s.id), prompt=s.input, make_world=World), world=World(),
trajectory=traj)
grades = [(g.name, g.passed) for g in (gr(ctx) for gr in graders)]
print(f"{s.id:14} tools={traj.tool_names} statuses={[st.status for st in traj.steps]} grades={grades}")
s = next(x for x in logs_in("logs/s02")[-1].samples if x.id == "refund-lost")
prf = tool_call_prf(trajectory_from_inspect(s), reference=[
("orders_get", {"order_id": "ORD-1002"}),
("refunds_issue", {"order_id": "ORD-1002", "amount_cents": 8450, "reason": "lost in transit", "confirm": True})])
print("tool_call_prf vs reference:", {k: prf[k] for k in ("precision", "recall", "f1")})
# --- 2. Multi-agent (s12): route, ping-pong and context transfer on what the receiver saw.
# s12 tagged every run with metadata={"variant": label}; pair logs by that tag, newest log per variant,
# so a second run of s12 into the same folder cannot swap or mislabel anything.
latest = {}
for log in logs_in("logs/s12"): # oldest first, so later runs overwrite earlier ones
latest[log.eval.metadata["variant"]] = log
VARIANTS = { # s12's metadata tag -> the short label printed here
"handoff(returns), default filters": "default filters",
"input_filter=remove_tools": "remove_tools",
"output_filter=last_message": "output_filter=last_message",
"input_filter=redact_emails (custom)": "redact_emails",
"input_filter=last_message (misuse), time_limit=5": "last_message misuse",
}
assert set(latest) >= set(VARIANTS), f"missing s12 variants: {set(VARIANTS) - set(latest)}"
required = {"order_id": "ORD-1002", "customer_email": "bo@example.com"}
for variant, label in VARIANTS.items():
log = latest[variant]
trace = trace_from_inspect(log.samples[0], system=f"triage+returns ({label})")
handoffs = trace.handoffs()
seen = fields_in(handoffs[0].attrs["payload_seen"]) if handoffs else {}
ct = context_transfer(seen, required)
print(f"\n{label}: route={trace.route()} pingpong={pingpong(trace)['pingpong']} "
f"field_recall={ct['field_recall']} missing={ct['missing']}")
if label == "default filters":
per_agent = to_trajectories(trace)
print(" per-agent tools:", {a: t.tool_names for a, t in per_agent.items()})
print(" per-agent tokens:", {a: t.tokens_in + t.tokens_out for a, t in per_agent.items()})policy tools=['docs_search'] statuses=['ok'] grades=[('tool_unused', True)]
refund-lost tools=['orders_get', 'refunds_issue'] statuses=['ok', 'ok'] grades=[('required_order', True), ('tool_unused', True)]
unknown-order tools=['orders_get'] statuses=['error'] grades=[('tool_unused', True)]
tool_call_prf vs reference: {'precision': 1.0, 'recall': 1.0, 'f1': 1.0}
default filters: route=['triage', 'returns'] pingpong=0 field_recall=1.0 missing=[]
per-agent tools: {'triage': ['transfer_to_returns', 'submit'], 'returns': ['orders_get', 'refunds_issue', 'submit']}
per-agent tokens: {'triage': 1258, 'returns': 1916}
remove_tools: route=['triage', 'returns'] pingpong=0 field_recall=1.0 missing=[]
output_filter=last_message: route=['triage', 'returns'] pingpong=0 field_recall=1.0 missing=[]
redact_emails: route=['triage', 'returns'] pingpong=0 field_recall=0.5 missing=['customer_email']
last_message misuse: route=['triage', 'returns'] pingpong=0 field_recall=0.0 missing=['order_id', 'customer_email']The single-agent results show the intended pattern. The refund trajectory contains orders_get before refunds_issue; the unknown-order trajectory has an error status but correctly no mutation; the policy trajectory uses only search. tool_call_prf is 1.0 against the reference because the scripted oracle is exact. On a real model, precision and recall separate two different questions: did it avoid unnecessary or wrong calls, and did it make the calls the task required?
The multi-agent results are more interesting. All well-formed variants route ['triage', 'returns'] with no ping-pong, but context transfer differs by filter. The default and remove_tools input pass both required fields. The custom email-redaction filter deliberately loses customer_email, so field recall is 0.5. The last_message misuse loses both fields. This is the correct interpretation discipline: a low context-transfer score is sometimes a defect and sometimes proof that an intentional minimization filter worked. The metric is evidence, not a verdict divorced from design.
Per-agent token counts come from model events inside agent spans. They let you ask the economic question from 10A.12, Part 5: how much coordination cost did the second agent add, and did success improve enough to justify it? In this scripted run the numbers are artificial because mockllm fabricates usage, but the aggregation path is real.
10.6 Validate the measuring instrument before the model#
Agent evals fail in layers. Before comparing models, validate the instrument in this order:
- Tool tests: direct calls prove schema, result shape, domain errors, state mutation and output size.
- Scorer self-tests: oracle passes, null receives the expected low or baseline score, planted process violations fail.
- Transcript audit: inspect several successes and failures by hand. Check whether the evidence supports the scorer's explanation.
- Adversarial or careless controls: confirm that unsupported claims, skipped lookups and forbidden tools light up the intended checks.
- Tool-failure control: break one tool on purpose and replay the oracle's script. An outcome scorer that believes the agent's claim will still pass the sample; one that reads the world will not (the run below).
- Budget control: an agent that loops (the
last_messagemisuse in 9.3 is a free one) must be stopped by a limit and recorded as a limit, not as a quiet failure. 10B.15, 12.4 owns the checks for limit and approval controls. - Reliability design: choose epochs and reducers deliberately. Agent runs are stochastic; one success is an anecdote. Use the statistics in 10B.10, Part 7, not a vibe.
- Cost accounting: count model events by origin and agent span, including retries and helper calls. Logical turns undercount cost.
- Comparability check: same dataset version, model, tools, prompt layers, filters, submit behaviour, limits, compaction and sandbox image. If one differs, say the comparison is scaffold-level, not model-level.
s24_tool_failure_control.py is the tool-failure control for the support desk. It swaps in a refunds_issue with the same name and schema that always raises ToolError, and replays the oracle's script from s18 unchanged, including its claim "Refunded 84.50.":
# s24_tool_failure_control.py: a tool-failure control: does the scorer believe the claim or the world? (lesson 10B.14)
from inspect_ai import Task, eval
from inspect_ai.agent import AgentSubmit, react
from inspect_ai.tool import Tool, ToolError, tool
from desk import call, desk_samples, docs_search, orders_get, refund_outcome, scripted, send_email
@tool(name="refunds_issue") # same name and schema the agent expects...
def refunds_down() -> Tool:
async def execute(order_id: str, amount_cents: int, reason: str, confirm: bool = False) -> str:
"""Refund part or all of an order to the original payment method.
Args:
order_id: The order to refund.
amount_cents: Amount in cents, at most the refundable balance.
reason: Short reason, recorded on the refund.
confirm: False (default) returns a preview and moves no money; True issues the refund.
"""
raise ToolError("refund service unavailable, try again later") # ...but the service is down
return execute
# The oracle's script from s18, unchanged: it claims success whatever the tool said.
ORACLE = {
"ORD-1002": [call("orders_get", order_id="ORD-1002"),
call("refunds_issue", order_id="ORD-1002", amount_cents=8450, reason="lost", confirm=True),
call("submit", answer="Refunded 84.50.")],
"refund policy": [call("docs_search", query="refund policy"), call("submit", answer="30 days.")],
"ORD-9999": [call("orders_get", order_id="ORD-9999"), call("submit", answer="No such order.")],
}
task = Task(dataset=desk_samples(),
solver=react(prompt="You are a support agent for an online shop.",
tools=[orders_get(), refunds_down(), docs_search(), send_email()],
submit=AgentSubmit(answer_only=True)),
scorer=refund_outcome())
log = eval(task, model=scripted(ORACLE), log_dir="logs/s24", display="none")[0]
for s in log.samples:
errors = [(m.function, m.error.type) for m in s.messages if m.role == "tool" and m.error]
print(f"{s.id:14} claim={s.output.completion!r:22} outcome={s.scores['refund_outcome'].value} "
f"tool errors={errors}")policy claim='30 days.' outcome=C tool errors=[]
refund-lost claim='Refunded 84.50.' outcome=I tool errors=[('refunds_issue', 'unknown')]
unknown-order claim='No such order.' outcome=C tool errors=[('orders_get', 'unknown')]The refund-lost sample claims success and scores I, because refund_outcome() reads the store and the store holds no refund. That is the verdict you want, and it is evidence about the instrument rather than the model: the scorer cannot be fooled by narration. Two more readings. The tool error reached the model as unknown (the ToolError row in 2.6), so a real model had the information it needed to tell the customer the truth; grading whether it did is the honesty check from 10A.7, 3.5. And the two samples that expect no refund still pass, so a tool-failure control must be read per sample, like the null control above.
A failure gallery for this lesson's machinery:
| Symptom | Likely layer | First check |
|---|---|---|
| Exact-match scorer fails although the answer is visible | Submit rewriting | Is answer_only=True needed? |
| Scorer sees an empty completion | run() copy semantics |
Did the solver copy back messages and output? |
| Process grader misses a sub-agent call | Message/event confusion | Are you reading sample.events rather than state.messages? |
| Specialist never receives the order id | Handoff input filter or thin delegation brief | Inspect the receiver's first model input |
| Agent never finishes | No live budget, ping-pong, continuation loop or filter misuse | Add message/time/token limits and inspect spans |
| Sample errors before behaviour can be measured | Uncaught tool exception | Should this domain error be ToolError? |
| "No network" run still searches | Provider-run tool or remote MCP | Inspect tool configuration and provider events |
| Multi-agent system wins at double the cost | Coordination overhead | Compare cost per success against the single-agent baseline |
10.7 The evalkit ↔ Inspect mapping, completed#
| evalkit concept | Inspect object or mechanism | What differs in practice |
|---|---|---|
AgentFn |
Agent, usually react() |
Inspect supplies production loop machinery rather than a minimal function seam |
World |
Tool implementations plus sample Store or sandbox state |
No enforced reset interface; design state lifecycle yourself |
Trajectory |
ToolEvents and ModelEvents in sample.events |
Richer evidence, but span ownership must be decoded |
| outcome grader | Scorer reading store_as() or sandbox() |
Runs in the same sample context immediately after solving |
| trajectory grader | Scorer or post-hoc log analysis reading events | Inspect has no built-in library of trajectory metrics; evalkit's graders port cleanly |
| budget grader | Live message/token/turn/time/working/cost limits | Inspect can stop the run, not merely grade the overrun afterwards |
MASTrace |
Agent, handoff and tool spans | Inspect records coordination structurally; adapters can reuse 10A.12's metrics |
pass_at_k() / pass_hat_k() (pass@k, pass^k) |
Epochs with the pass_at(k) and pass_k(k) reducers |
Same estimators, configured in Inspect rather than evalkit; 10B.16, 4.2 checks them by hand |
| run manifest | .eval log plus task metadata |
Include scaffold details yourself; the log cannot infer your experimental intention |
10.8 A checklist before quoting an agent score#
Before writing "the agent scored X" in a report or pull request, answer these aloud:
- Which scaffold, exact package version and prompt layers produced the run?
- Which tools were offered, with which descriptions, filters and output limits?
- Where did each action execute: host, sandbox or provider?
- What submit behaviour produced
output.completion? - Which limits, approval, review, truncation and compaction settings were active?
- What do outcome, process, cost and reliability each say, separately?
- What do oracle, null and careless controls score?
- Did you inspect failures in events rather than inferring them from final prose?
- Is the comparison against a tuned single-agent baseline?
- Can another engineer rerun the eval from the log and task metadata?
If any answer is missing, the number is not yet an evaluation result. It is a demo output.
10.9 Measuring a scaffold change: descriptions, prompts and filters#
Most changes engineers make to an agent eval are not model swaps. They are a reworded tool description (tool_with(), 3.2), a prompt layer switched off (7.2), a filter added to a handoff (9.3), a model_input hook (3.5) or a tool added to the catalogue (4.7). Each is an experiment with one independent variable, and the same rules apply as to any comparison in Module 10A:
- Pair by sample and epoch. Run both variants on the same samples with the same epochs and compare sample by sample, counting the tasks that flipped in each direction, not only the two means. The paired statistics are 10B.10, 8.3; the ablation ladder for scaffold features is 10B.16, 6.4.
- Change one thing. A new tool description plus a new submit setting is two experiments. Inspect makes it easy to change several at once, because every one of them is a keyword argument.
- Predict which metric should move. A clearer
refunds_issuedescription should move process metrics (fewerparsingerrors, fewer previews never confirmed) before it moves outcome. If outcome moves and process does not, look for a second change you did not intend. - Tag the variant in the log. Pass
metadata={"variant": ...}toeval(), ass12does, so analysis code pairs logs by meaning rather than by file time (10.5). - Rerun the null and oracle controls under the new variant. A filter or hook can change what the scorer sees, so the instrument must be revalidated with it, not only the agent.
The scripted samples in this lesson cannot tell you whether a description change helps a real model: the mock does whatever the script says. They do tell you, deterministically, what each variant puts in front of the model and what the scorer reads, which is the half of the experiment you must get right before spending money on the other half.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "The model calls my Python function." | The model emits structured JSON. Inspect validates it, executes the function and appends the result. That indirection is what makes tool use observable. |
| "A custom tool is contained because Inspect runs it." | Custom tool code runs in the Inspect host process with the eval's permissions. Only work done through a sandbox is contained. |
| "The final message list is the full transcript." | messages are conversational state. Submit calls can be removed, handoff output rewritten and as_tool() internals omitted. events are the full evidence. |
"react() is just the ReAct prompt." |
It is a production loop with prompt layers, submission, attempts, continuation, refusal handling, truncation, compaction, approval and review. |
| "If the answer is right, the agent succeeded." | The final claim can be unsupported, the process unsafe, the cost unacceptable or the world unchanged. Grade outcome, process, cost and reliability separately. |
"exact() is the natural scorer for a submit answer." |
By default the completion is accompanying prose plus the submitted answer. Use AgentSubmit(answer_only=True) for a bare answer. |
| "Multi-agent is the advanced option, so it should be better." | Multi-agent adds routing, context-transfer and coordination failure modes. It must beat a tuned single-agent react() baseline on the same eval. |
"handoff() and as_tool() are two spellings of the same delegation." |
Handoff shares filtered conversation history; agent-as-tool isolates the sub-agent behind a string input and string result. |
| "A handoff filter only changes formatting." | Filters decide what the receiver and later agents can know. They are privacy, context and evaluation interventions. |
"deepagent() is the obvious upgrade from react()." |
It adds subagents, memory, planning and compaction, but also prompt, cost and failure surface. Measure it against react() on your tasks. |
| "Provider-run tools are just another tool event." | Provider-native search, code execution and remote MCP run during generation. Inspect cannot observe or approve their individual actions in the same way. |
"Only ToolError keeps a sample alive." |
Inspect also maps timeouts, permission errors, missing files, directories, decoding errors and output limits to recoverable tool messages, each with its own error.type. A missing fixture file therefore looks like agent behaviour unless you re-raise it. |
"messages shows what the model saw." |
A model_input hook, truncation or compaction changes the model's input while the message history keeps the originals. Read ModelEvent inputs for what the model actually received. |
"react(prompt=...) with handoff tools uses only my instructions plus the usual scaffolding." |
A handoff tool adds a whole extra prompt layer, including an instruction not to mention transfers to the user. |
| "A limit is an operational detail unrelated to the score." | Limits change termination and recovery behaviour. They are part of the system under test. |
Key takeaways#
- A tool call is a proposal by the model and an execution by Inspect. The execution location determines what can be observed, approved and contained.
- The tool schema is prompt surface. Write names, descriptions, types, constraints and errors for the model, then enforce them in code.
- Raise
ToolErrorfor recoverable domain failures. Let unexpected harness failures error the sample loudly, and remember that Inspect maps several built-in exceptions (includingFileNotFoundError) to recoverable tool errors on its own. - Keep tool results compact and structured. Truncation is a safety valve, not retrieval design.
react()is the baseline agent. Understand its prompt layers and submit rewriting before interpreting any score.AgentSubmit(answer_only=True)is the simple fix for exact-answer scoring; attempts and continuation are powerful but change the experimental condition.run()copies input and returns a new state. Inside a solver, copymessagesandoutputback or scorers see nothing.- Custom agents are for studying or changing the loop itself. If you filter calls, every proposed call still needs a tool result.
handoff()shares filtered history;as_tool()isolates a subtask;run()andcollect()make orchestration explicit. Choose per information flow, not fashion.- With several attempts, only an exact 1.0 from the task's first scorer stops the loop; order scorers and choose
score_valuedeliberately. - Agent and handoff spans make multi-agent evaluation possible. Grade what the receiver actually saw, not what the sender intended.
- The scaffold is part of the system under test. Report model, agent, tools, prompts, filters, limits, compaction and package version together.
- Outcome, process, cost and reliability are separate measurements. Oracle, null, careless and tool-failure controls keep them honest, and every scaffold change is a paired experiment with one variable.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Tool (Inspect) | A Python callable plus metadata that Inspect exposes to a model as a structured callable interface. |
| Tool factory | The outer function in the @tool pattern; calling it returns the configured tool implementation. |
ToolDef |
Inspect's lower-level tool definition object, used to adapt existing functions or introspect and override metadata. |
ToolResult |
The documented result type of a tool: a scalar, content object or list of content objects. |
ToolError |
An expected, recoverable tool failure reported back to the model instead of ending the sample. |
| Parsing error | A recoverable tool-call failure caused by bad arguments, an unknown tool or schema mismatch. |
parallel tool execution |
Per-tool opt-in that lets independent calls in one assistant turn execute concurrently. |
tool_state_scope() |
A context manager that supplies separate default state instances to concurrent agents or workers. |
| Tool view | A renderer that controls how a call is shown to a human approver or log viewer without changing execution. |
model_input hook |
A per-tool hook that changes how earlier tool results are replayed to the model on every call while the transcript and message history keep the originals. |
use_tools() |
The solver that installs tools and tool-choice settings in ordinary solver chains. |
execute_tools() |
The handoff-aware function that executes calls requested in the latest assistant message. |
| ToolSource | A dynamic source of tools, such as an MCP server connection. |
| Provider-run tool | A capability such as native search or code execution performed by the model provider during generation rather than by Inspect as a normal tool event. |
AgentState |
The narrow state of an Inspect agent: messages plus output. |
react() |
Inspect's built-in tool-using agent loop and the recommended baseline scaffold. |
| Submit tool | The agent-visible tool that explicitly submits an answer and ends a react() run. |
AgentSubmit(answer_only=True) |
Submit configuration that makes the final completion exactly the submitted answer. |
AgentAttempts |
Configuration for scoring submissions inside a run and allowing incorrect attempts to continue. |
on_continue |
The hook that decides whether and how a react() loop continues after an unfinished turn. |
| Compaction | Rewriting the model-visible conversation to fit context while retaining the full history outside model input. |
as_solver() |
Adapter that uses an agent as a solver, copies back state and can curry parameters or limits. |
handoff() |
Delegation mechanism in which a specialist sees filtered shared history and its filtered turns return to that history. |
as_tool() |
Delegation mechanism that wraps an agent as an isolated string-in, string-out tool. |
| Input filter | A handoff filter controlling what the receiving agent sees. |
| Output filter | A handoff filter controlling what the specialist's work contributes back to shared history. |
collect() |
Inspect's backend-independent concurrency helper for running independent agent calls with spans. |
model_origin() |
A marker that distinguishes evaluated-agent model calls from helper or environment calls in the transcript. |
deepagent() |
Inspect's batteries-included long-horizon agent with subagents, memory, planning and compaction. |
| Agent span | A transcript span that attributes nested model and tool events to one agent execution. |
ToolCallError type |
The category Inspect records on a failed tool call (parsing, unknown for a raised ToolError, timeout, file_not_found, limit, approval and others); the key for failure analysis by layer. |
| Handoff prompt | The extra system-prompt layer react() adds when an agent holds handoff tools: it describes the multi-agent system and tells the model not to mention transfers. |
| Tool-failure control | A validation run that breaks one tool on purpose and replays a correct script, to prove the scorer reads the world rather than the agent's claim. |
Exercises#
All exercises are keyless. Save the lesson files in one folder, keep desk.py beside them and run samples as in Setup. Exercises that use s16 require the evalkit modules on the import path and require s02 and s12 to have run first. Exercise 13 needs mcp installed (Setup). Deleting the logs/ folder before rerunning s02 and s12 keeps it readable, though s16 tolerates repeats.
- Schema reading (2.2). Add a
priority: Literal["low", "normal", "high"] = "normal"parameter todocs_search()and reruns01_tool_schema.py. Predict the JSON schema before running. Does the parameter become required? Why not? - Recoverable versus fatal (2.6). Change
orders_get()so an unknown order raisesValueErrorinstead ofToolError, then rerun the unknown-order plan ins02_first_agent.py. What happens to sample status and the other samples? RestoreToolErrorafterwards. - Prompt layers (7.2). Use
AgentPromptto remove onlyassistant_promptwhile keepingsubmit_prompt. Print the system prompt. Which behavioural guidance disappeared, and how would you test whether it mattered? - Submit scoring (7.3). Rerun
s07withexact()only, once with the default submit and once withAgentSubmit(answer_only=True). Explain the two verdicts without quoting the scorer documentation. - Attempts leakage (7.5). Modify
feedbackins08so it includes the target string. Does the oracle improve? Then write one sentence explaining why the resulting score no longer measures the same capability. - Copy-back failure (6.4). In
s10, copy back onlystate.outputand notstate.messages. Predict which scorers and downstream solvers would still work, then inspect the difference. - Blocked-call invariant (8.3). Modify the guarded loop to drop a blocked call entirely instead of appending a
ChatMessageTool. Inspect the next model request or error. Why is the invariant necessary? - Handoff privacy (9.3). Extend
redact_emailsso it also redacts order ids. Reruns12ands16. Which score changes, and is that a failure or the intended effect of the filter? - Delegation brief quality (9.4). In
s13, change the supervisor's input string toRefund it please.and rerun. What happens, and which grader from 10A.12 would detect the thin brief? - Workflow contamination (9.6). In
s14, print every system prompt received by the auditor as well as the drafter. Then implement aclean_history()helper that keeps user and tool evidence but removes system prompts. Compare spans and completions. - Controls (Part 10, section 2). Add a fourth scripted control that uses only
docs_searchfor every sample. Predict its outcome and process scores before runnings18. What does it add beyond the null control? - Adapter ownership (Part 10, section 4). Change
trajectory_from_inspect(..., agent="returns")ins16and compare the tool list withagent=None. Why is the nearest-agent-span walk necessary? - MCP globs (5.3). In
s21_mcp_stdio.pychange the glob list to["*"], then to["get_order"], and rerun. Predict the "offered to the model" line each time. Then change the scripted call todelete_orderunder the original globs: what does the model's call hit, and what does that say about filtering atmcp_tools()versus trusting the prompt? - Replaying old results (3.5). Change
keep_latestins23to keep the two newest results in full. Predict the three lines under "what the model received" before running. Then, usingread_eval_log(), print the tool-message texts from theinputof the lastModelEventand compare them withs.messages. - The hidden prompt layer (7.2). In
s22, passprompt=AgentPrompt(instructions="You are the triage agent.", handoff_prompt="Tell the customer when you pass them to a specialist.")to the supervisor. Print the prompt again. Which evaluation claim from 7.2 does this change, and what would you record in task metadata? - Tool-failure control (Part 10, section 6). In
s24, makerefunds_down()succeed but refund only 1000 cents. Predict the outcome score forrefund-lost, then run it. Which sentence inrefund_outcome()decides it?
Hints and what you should see
Literalbecomes anenum; the default makes the parameter optional, so it is absent fromrequired.- The sample errors instead of receiving a recoverable tool error. Depending on the eval error policy, the whole log can become
error, which is the correct treatment for a broken harness but not for a missing order. - The paragraph about parallel calls, sequencing and reasoning before actions disappears. Test it with tasks that have independent lookups and compare parallel-call frequency, latency and correctness.
- Default completion includes the accompanying prose, so exact matching fails.
answer_only=Trueremoves the prose. - It will usually improve because the agent is told the answer. That measures assisted repair, not unaided task solving.
- Answer scorers may work because
output.completionexists, but transcript readers and later solvers lose the conversation. Copy both fields. - Providers expect every assistant tool call to have a matching tool message. Even with mockllm, the Inspect history becomes semantically malformed and no longer represents a valid provider request.
- Context-transfer field recall falls because the receiver cannot see what you intentionally removed. Interpretation depends on whether privacy minimization was part of the design.
- The specialist lacks the order id and either fails, guesses or asks for clarification depending on the script or real model. Delegation-brief grading and context-transfer grading both target this failure.
- The auditor inherits the returns system prompt unless you strip it. Cleaning prevents role contamination while preserving evidence.
- It may answer the policy question correctly but never act on refund tasks. Unlike the null control, it distinguishes retrieval use from action use.
- With
agent="returns", supervisor tools such as the handoff and submit disappear and only the specialist's world actions remain. Ownership comes from span ancestry, not message order. ["*"]offers all three tools;["get_order"]offers one. A call todelete_orderunder the original globs returnsToolCallError(type='parsing', message='Tool delete_order not found')and never reaches the server; filtering atmcp_tools()removes the capability instead of asking the model not to use it.- The model now receives one placeholder (
(older queue snapshot 1 of 3 omitted)) and two full results. TheModelEventinput shows the same placeholders (the full payloads may appear asattachment://references unless you resolve attachments), whiles.messagesholds three full results. - The "do not mention transfers" instruction disappears, so a transparency rubric now measures the model rather than fighting the scaffold. Record the custom
handoff_prompttext (or its hash) as part of the scaffold. I:refund_outcome()compares the list of refunds with the exact expected(order_id, amount_cents)pair, so a partial refund is not the required end state. Partial credit would be a separate scorer (10A.7, Part 3).
Check yourself#
- Why is it wrong to say that a model "calls" a Python tool in Inspect?The model produces a structured request. Inspect validates it, executes the Python function and appends the result as a tool message.
- Name the three execution locations for tools and one evaluation consequence of each.Host process: full observability but no isolation. Sandbox: contained environment actions with tool and sandbox events. Provider: work happens during generation, so individual actions are not normal Inspect tool events and cannot be approved in the same way.
- What parts of a tool function become the JSON schema shown to the model?The docstring summary becomes the description, Google-style
Args:become parameter descriptions, annotations become types, defaults determinerequired, andadditionalPropertiesis false by default. - What does 0.3.292 actually do when a tool parameter lacks an annotation, and what should you do anyway?It accepts the parameter silently and emits JSON type
None. Annotate every parameter because the model otherwise receives no useful constraint. - When should a tool raise
ToolErrorrather thanRuntimeError?UseToolErrorfor expected domain failures the agent should read and recover from. Use ordinary exceptions for harness failures that invalidate the sample. - Why is
max_output=0appropriate for submit but usually wrong for file or command output?Submit's payload is the answer contract and must not be truncated. File or command output can flood the context if unbounded; prefer pagination, queries or summaries. - What is the difference between
generate(tool_calls="single")andgenerate(tool_calls="none")?"single"executes the current calls but does not generate again automatically."none"leaves proposed calls unresolved so your solver can inspect or execute them. - What are the two fields of
AgentState, and why is the state intentionally narrower thanTaskState?messagesandoutput. The narrow state lets one agent act as a solver, workflow participant, tool or handoff target without owning the whole task. - What exactly must you copy back after
run()inside a solver?state.messages = agent_state.messagesandstate.output = agent_state.output. - Why does the default
react()completion makeexact()fail even when the submitted answer is correct?The default completion is accompanying assistant text plus the answer separated byanswer_delimiter. UseAgentSubmit(answer_only=True)for exact answers. - Where is
{submit}substituted in 0.3.292, and where is it not?It is substituted inassistant_prompt,submit_promptand continuation messages, not ininstructions. - What is the difference between attempts and epochs?Attempts are repeated submissions inside one sample with shared state and feedback. Epochs are independent repetitions of the whole sample.
- What happens after three consecutive content-filter outputs in
react()?The react loop breaks and returns rather than continuing forever. Ins09the sample finishes withstatus=success, the refusal text (I can't help with that.) as the completion and exactly three model calls.retry_refusalsis a separate setting that re-asks the model first (7 model calls ins09when the model refuses the same input every time). - Why can
truncation="auto"undermine a message limit?Truncation removes messages from the visible history, so the run can remain under a message-count budget while consuming far more turns, time and tokens. Pair it with other limits. - Why does the docs' printed custom tool loop fail, and what are the two corrected lines?It uses undefined names
outputandmessage. The corrected loop appendsstate.output.messageand passesstate.messagestoexecute_tools(). - What is the difference in input between
handoff()andas_tool()?handoff()gives the receiver filtered shared conversation history.as_tool()gives it only its prompt and one input string. - In a handoff, what do
input_filterandoutput_filtereach control?input_filtercontrols what the receiving specialist sees.output_filtercontrols how the specialist's messages are represented when control returns to shared history. - Why is
last_messagedangerous as an input filter?It leaves only the transfer-notice tool message as the specialist's whole conversation, so no user request reaches it. In 0.3.292 the specialist never even issues a model request (returns agent requests: 0) and the sample runs until the time limit; this is observed, undocumented behaviour. - How do limit outcomes differ across
as_tool(),handoff(),as_solver()andrun()?as_tool()returns a limit tool error to the supervisor;handoff()appends a user message;as_solver()terminates the sample with a sample limit;run()returns the state plus aLimitExceededErrorfor workflow code to handle. - Why should trajectory graders read events rather than messages?Messages are rewritten for downstream conversation. Events preserve submit calls, sub-agent internals, exact arguments, errors, timings and span ownership.
- What does
mcp_tools(server, tools=["search*", "get*"])do, and what happens if the model calls a tool the globs excluded?It offers the model only the server's tools whose names match the globs, after discovery over an open connection. A call to an excluded tool comes back as aparsingerror (Tool delete_order not found) and never reaches the server. - Why does 0.3.292 refuse a remote MCP server while an approval policy is active?With
execution="remote"the provider calls the server during generation, so Inspect never sees the individual calls and cannot ask an approver about them. Rather than silently waiving approval, it refuses to send the server. - A tool has a
model_inputhook. What does the model receive for older results, and what does the transcript keep?Whatever the hook returns (ins23, a one-line placeholder for every result except the newest), recomputed on every model call. The transcript andmessageskeep the original results, so readModelEventinputs for what the model saw. - What happens to a sample when a host-side tool raises
FileNotFoundError, and why can that mislead an eval?Nothing fatal: Inspect maps it to a recoverable tool message witherror.type == "file_not_found". If the missing file is a broken fixture, the eval records agent behaviour where it should record a harness failure; re-raise asRuntimeErrorin that case. - With
attempts=3and a scorer that returnsP(partial), when does the loop stop?Only when the third submission is made (attempts used up).Pconverts to 0.5 with the defaultvalue_to_float(), and only an exact 1.0 stops the loop early. - What does a supervisor's system prompt gain when you give it one handoff tool, and why does that matter for a transparency rubric?A
handoff_promptlayer of about 520 characters describing a multi-agent system and telling the model not to mention transfers to the user. A rubric that rewards announcing the transfer would then measure the default scaffold instruction, not the model. - Why did the null control score 0.667 on outcome in
s18, and what does that tell you about the dataset?Two of the three samples expect no state change, so doing nothing is correct on them. The dataset is dominated by negative cases; report per sample or per slice and include positive action cases. - What does the tool-failure control in
s24validate: the agent or the scorer?The scorer. The script is identical to the oracle's; only the world changed. A scorer that passedrefund-lostwould be believing the claim "Refunded 84.50." instead of reading the store.
Further resources#
Official Inspect documentation (URLs verified on 24 November 2026; the Markdown form of each page is available by appending .md to the URL):
- Tool Basics, Custom Tools, Standard Tools and MCP Tools: the authoritative tool catalogue, including provider-specific support that changes faster than this lesson.
- Using Agents, ReAct Agent, Multi Agent, Custom Agents, Deep Agent and Compaction: the agent APIs and the current recommendations on choosing among them.
- Reference pages:
inspect_ai.tool,inspect_ai.agent,inspect_ai.utilandinspect_ai.event. Use these for exact signatures in the version you have installed. - CHANGELOG: essential before copying any example, because agent and tool APIs have changed in patch releases.
llms.txt: the machine-friendly index of the official documentation.- UKGovernmentBEIS/inspect_ai: the source. When docs and behaviour disagree, read the installed source for your exact version.
Background and ecosystem:
- ReAct: Synergizing Reasoning and Acting in Language Models: the original pattern behind the name. Read it as history and motivation, not as a description of Inspect's full implementation.
- Model Context Protocol: the protocol behind MCP tools. Inspect adds the sandbox transport and evaluation integration covered here.
- Anthropic: Building Effective Agents: the workflow-first guidance that Inspect's multi-agent documentation also recommends.
Within this course: 03.5 for one provider-level tool round trip, Module 08A for tool and agent design, 10A.7 for agent evaluation methodology, 10A.12 for multi-agent metrics, 10B.10 for scoring, metrics and epochs, 10B.12 for run configuration and errors, 10B.13 for events and log analysis, 10B.15 for sandboxes, approval, limits and long-horizon agents, and 10B.16 for the broader evaluation methodology and ecosystem.
← 10B.13: Inspect Logs, Analysis and Extending Inspect (optional) | Module 10B overview | 10B.15: Sandboxes, Limits, Approval and Long-Horizon Agents in Inspect (optional) →