About this notebook

Companion to Module 4: The ReAct agent. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)

Notebook 1 wrote an agent loop in about 25 lines. This notebook turns that sketch into the agent the rest of the course extends, and checks each part as it goes. You will

  1. run ReAct the 2022 way, as a text protocol (Thought: / Action: / Observation:) that your code parses, and break it in the three ways it usually breaks;
  2. see what moved into the model when providers added native tool calling;
  3. build an agent from its parts: an execution context that records events, tools as objects, and the run / step / think / act methods;
  4. look closely at the one decision every loop makes, when to stop;
  5. get structured output by giving the model a final_answer tool;
  6. write a mini benchmark: tasks, a grader, a concurrent runner, and error analysis.

Which model answers here?

With no MODEL set, the offline policy model answers. Its rules for this notebook (agentlab/llm/fake_packs/nb04_react.py) know this shop’s question types: lookups, totals, discounts, and price comparisons. That makes the trajectories readable and repeatable, but every pass rate below measures those rules and the harness, not any real model. Set MODEL and re-run to measure a real one.

from agentlab.nbsetup import setup
 
nb = setup("04_react_agent", packs=["react"])
llm = nb.llm

LLM backend

offline policy model (deterministic, rule-based, no API key used)

0. A small shop

Every task in this notebook is about a made-up shop with five products. The data is invented on purpose: no model can know these prices from training, so a correct answer needs a tool. (GAIA, the benchmark the book uses in this chapter, is built on the same principle: questions that are easy for a person with tools and hard without them.)

import json
 
CATALOG = {
    "trail mug": {"name": "Trail Mug", "price_usd": 18.50, "stock": 42},
    "field notebook": {"name": "Field Notebook", "price_usd": 9.75, "stock": 120},
    "desk lamp": {"name": "Desk Lamp", "price_usd": 64.00, "stock": 7},
    "canvas tote": {"name": "Canvas Tote", "price_usd": 22.00, "stock": 0},
    "wool beanie": {"name": "Wool Beanie", "price_usd": 15.25, "stock": 31},
}
 
 
def lookup_product(name: str) -> dict:
    """Look up one product in the shop's catalog: name, price in USD, and units in stock.
 
    Args:
        name: The product's name, for example "Trail Mug". Case does not matter.
    """
    key = name.strip().lower()
    if key not in CATALOG and key.endswith("s"):
        key = key[:-1]  # "Trail Mugs" -> "trail mug"
    if key not in CATALOG:
        known = ", ".join(p["name"] for p in CATALOG.values())
        raise LookupError(f"no product named {name!r}; known products: {known}")
    return dict(CATALOG[key])
 
 
print(json.dumps(lookup_product("Trail Mugs")))
{"name": "Trail Mug", "price_usd": 18.5, "stock": 42}

The second tool is the course’s safe calculator (Module 1): it parses the expression and evaluates only numbers and arithmetic, so a model cannot run arbitrary Python through it.

from agentlab.tools import calculator
 
print(calculator("3 * 18.5"), calculator("sqrt(2)"))
55.5 1.4142135623730951

1. ReAct as a text protocol

ReAct (Yao et al., 2022) asks a model to alternate between a thought (free text about what to do next) and an action (a tool name and an input, in a fixed format). Your code reads the action, runs the tool, and appends an observation. The whole history is one growing block of text, the scratchpad, and the model writes the next lines of it:

  Question: What would 3 Trail Mugs cost in total?
  Thought: I need the catalog entry for the Trail Mug.       <- model
  Action: lookup_product[Trail Mug]                          <- model
  Observation: {"name": "Trail Mug", "price_usd": 18.5, ...} <- your code
  Thought: Now I compute 3 * 18.5.                           <- model
  Action: calculator[3 * 18.5]                               <- model
  Observation: 55.5                                          <- your code
  Thought: I have the result.                                <- model
  Action: finish[USD 55.50]                                  <- model: the answer

In 2022 the models had no tool-calling interface, so this text format was the interface. The prompt describes it, and a parser turns the model’s text back into a function call.

REACT_PROMPT = """Answer the question by interleaving Thought, Action and Observation lines.
Thought: reason about what to do next
Action: exactly one of
  lookup_product[product name]  look up a product's price and stock
  calculator[expression]        evaluate arithmetic, e.g. calculator[2 * 9.75]
  finish[answer]                give the final answer and stop
Observation: the result of the action (added for you; never write it yourself)
Write one Thought line and one Action line, then stop."""
import re
 
 
class ParseError(ValueError):
    pass
 
 
ACTION = re.compile(r"^Action:\s*(\w+)\[(.*)\]\s*$", re.M)
 
 
def parse_action(text: str) -> tuple[str, str]:
    """Return (tool, input) for the first Action line, or raise ParseError."""
    m = ACTION.search(text)
    if m is None:
        raise ParseError("no line of the form 'Action: tool_name[input]'")
    return m.group(1), m.group(2).strip()
 
 
print(parse_action("Thought: I need the price.\nAction: lookup_product[Trail Mug]"))
('lookup_product', 'Trail Mug')

The loop keeps the scratchpad as a string. Each step sends the prompt and the scratchpad (no tool schemas: as far as the API is concerned, this is plain text completion), parses the reply, runs the tool, and appends the observation. Errors, including parse errors, become observations, exactly as in Notebook 1.

from agentlab import LlmRequest, Message
 
TEXT_TOOLS = {"lookup_product": lookup_product, "calculator": calculator}
 
 
async def react_text(question, model=llm, max_steps=6, cut_at_observation=True):
    pad = f"Question: {question}\n"
    for _ in range(max_steps):
        request = LlmRequest(instructions=[REACT_PROMPT],
                             contents=[Message(role="user", content=pad)])
        reply = (await model.generate(request)).text
        if cut_at_observation:  # what a stop sequence does on the provider's side
            reply = reply.split("\nObservation:")[0]
        pad += reply.strip() + "\n"
        try:
            tool, arg = parse_action(reply)
            if tool == "finish":
                return arg, pad
            output = TEXT_TOOLS[tool](arg)
            observation = json.dumps(output) if isinstance(output, dict) else str(output)
        except ParseError as exc:
            observation = f"Error: {exc}. Write the action as tool_name[input]."
        except Exception as exc:
            observation = f"Error: {type(exc).__name__}: {exc}"
        pad += f"Observation: {observation}\n"
    return None, pad
 
 
answer, pad = await react_text("What would 3 Trail Mugs cost in total?")
print(pad)
print("answer:", answer)
Question: What would 3 Trail Mugs cost in total?
Thought: I need the catalog entry for the Trail Mug.
Action: lookup_product[Trail Mug]
Observation: {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
Thought: Now I compute 3 * 18.5.
Action: calculator[3 * 18.5]
Observation: 55.5
Thought: I have the result.
Action: finish[USD 55.50]

answer: USD 55.50

It works, and the scratchpad is easy to read: you can see why each action was taken. The same loop handles a question with two lookups, one per step, because the format has room for a single action at a time.

answer, pad = await react_text("Which costs more, the Desk Lamp or the Canvas Tote?")
print(pad)
print("answer:", answer)
Question: Which costs more, the Desk Lamp or the Canvas Tote?
Thought: I need the catalog entry for the Desk Lamp and the Canvas Tote.
Action: lookup_product[Desk Lamp]
Observation: {"name": "Desk Lamp", "price_usd": 64.0, "stock": 7}
Thought: I need the catalog entry for the Canvas Tote.
Action: lookup_product[Canvas Tote]
Observation: {"name": "Canvas Tote", "price_usd": 22.0, "stock": 0}
Thought: I can compare the two prices.
Action: finish[The Desk Lamp costs more (Desk Lamp USD 64.00, Canvas Tote USD 22.00).]

answer: The Desk Lamp costs more (Desk Lamp USD 64.00, Canvas Tote USD 22.00).

Three ways the text protocol breaks

Each failure below is staged with a ScriptedLLM, which replays fixed replies, so you can see the exact text that causes it. All three are common with real models.

1. The model writes the observation itself. A text model continues the pattern it sees, and the pattern says an Observation: line comes next. Without a stop sequence it writes one, with a made-up price, and then reasons from its own invention.

from agentlab.llm.scripted import ScriptedLLM
 
runaway_text = (
    "Thought: I need the price of the Trail Mug.\n"
    "Action: lookup_product[Trail Mug]\n"
    'Observation: {"name": "Trail Mug", "price_usd": 15.0, "stock": 10}\n'
    "Thought: 3 * 15 = 45.\n"
    "Action: finish[USD 45.00]"
)
 
 
def naive_parse(text):
    """Look for a finish action anywhere in the reply."""
    m = re.search(r"Action:\s*finish\[(.*)\]", text)
    return m.group(1) if m else None
 
 
print("naive parser returns:", naive_parse(runaway_text), "(true total: USD 55.50)")
 
scripted = nb.track(ScriptedLLM([runaway_text, "Thought: Now I compute 3 * 18.5.\n"
                                 "Action: calculator[3 * 18.5]",
                                 "Thought: Done.\nAction: finish[USD 55.50]"]))
answer, pad = await react_text("What would 3 Trail Mugs cost in total?", model=scripted)
print("\nwith the reply cut at 'Observation:':\n" + pad)
naive parser returns: USD 45.00 (true total: USD 55.50)

with the reply cut at 'Observation:':
Question: What would 3 Trail Mugs cost in total?
Thought: I need the price of the Trail Mug.
Action: lookup_product[Trail Mug]
Observation: {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
Thought: Now I compute 3 * 18.5.
Action: calculator[3 * 18.5]
Observation: 55.5
Thought: Done.
Action: finish[USD 55.50]

Cutting the reply at the first Observation: throws the invented lines away and runs the real lookup. The original ReAct code did this with the API’s stop parameter, so the model stopped generating at that string. If the stop sequence is missing, or the model spells the line slightly differently, the invented observation gets through.

2. The action is malformed. The model writes calculator(3 * 18.5) with parentheses. The parser fails, and the error goes back as an observation, so the model gets a chance to fix it. The repair costs a whole extra step.

scripted = nb.track(ScriptedLLM([
    "Thought: I need the price.\nAction: lookup_product[Trail Mug]",
    "Thought: Multiply.\nAction: calculator(3 * 18.5)",
    "Thought: I used the wrong format.\nAction: calculator[3 * 18.5]",
    "Thought: Done.\nAction: finish[USD 55.50]",
]))
answer, pad = await react_text("What would 3 Trail Mugs cost in total?", model=scripted)
print(pad)
Question: What would 3 Trail Mugs cost in total?
Thought: I need the price.
Action: lookup_product[Trail Mug]
Observation: {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
Thought: Multiply.
Action: calculator(3 * 18.5)
Observation: Error: no line of the form 'Action: tool_name[input]'. Write the action as tool_name[input].
Thought: I used the wrong format.
Action: calculator[3 * 18.5]
Observation: 55.5
Thought: Done.
Action: finish[USD 55.50]

3. One string per action. tool[input] has room for one string. A tool with several arguments, such as Module 3’s convert_currency(amount, from_currency, to_currency), needs a format inside the brackets (commas? JSON?) and a parser for that format, and every new tool adds edge cases: an input that contains ], or a comma inside a name.

2. What moved into the model

Native tool calling, which every major provider now supports, removes all three problems. Instead of text to parse, the reply carries structured tool calls, with arguments as JSON that the provider has parsed (and, with a strict mode, constrained to the tool’s schema during decoding). The model was trained on this format, so the parsing and much of the format discipline moved from your code into the model and the provider’s API.

ReAct as textnative tool calls
who parses the actionyour regexthe provider, into JSON arguments
argumentsone stringan object that matches a JSON Schema
several actions in one stepnoyes (parallel calls)
invented observationspossible; needs a stop sequenceno: the reply ends at the call
the reasoningvisible Thought: text you pay foroptional text, or a reasoning model’s internal thinking
works withany text modelmodels trained for tool calling

The loop did not change. Thought, action and observation are still there: the thought is the text (or hidden reasoning) before a call, the action is the call, and the observation is the tool result. Here is the same question with native calls. Note that the two lookups now happen in one step.

from agentlab import Agent, tool
from agentlab.display import show_trajectory
 
lookup_tool, calculator_tool = tool(lookup_product), tool(calculator)
SYSTEM = "You are a shop assistant. Use the tools to look up facts, then answer briefly."
 
agent = Agent(model=llm, tools=[lookup_tool, calculator_tool], instructions=SYSTEM)
result = await agent.run("Which costs more, the Desk Lamp or the Canvas Tote?")
show_trajectory(result)
[user] Which costs more, the Desk Lamp or the Canvas Tote?
[agent -> lookup_product] {"name": "Desk Lamp"}
[agent -> lookup_product] {"name": "Canvas Tote"}
    [lookup_product ok] {"name": "Desk Lamp", "price_usd": 64.0, "stock": 7}
    [lookup_product ok] {"name": "Canvas Tote", "price_usd": 22.0, "stock": 0}
[agent] The Desk Lamp costs more (Desk Lamp USD 64.00, Canvas Tote USD 22.00).
--- status: complete, steps: 2

3. An agent, built from its parts

agentlab.Agent (the class above) follows the structure of the book’s agent. Rather than read its 250 lines, this section rebuilds the core in about 50 and checks that the result behaves identically. Four parts:

  ExecutionContext                       the run's state, in one place
    events: [Event, Event, ...]          append-only log: who said what, in order
    current_step, state, final_result
 
  Event(author, content=[...])           one occurrence: a user turn, a model reply,
    content items: Message | ToolCall | ToolResult     or a batch of tool results
 
  BaseTool                               name + JSON-Schema definition + async execute()
 
  Agent.run ── loop: while not should_stop(context): step(context)
       step ── request = context -> LlmRequest
               think(request) -> LlmResponse          the model call
               act(context, tool_calls)               run tools, record results

The execution context and its events

Why not keep a plain list of messages, as Notebook 1 did? Because later modules need more than the messages: who wrote each item (several agents may share a run), when, how many steps have run, what is waiting for a human’s approval, and the final result. The context holds all of it, and the message list the model sees is derived from it (context.contents()). The log is the source of truth; the request is a view of it.

from agentlab import Event, ExecutionContext, ToolCall, ToolResult
 
context = ExecutionContext()
context.add_event(Event(execution_id=context.execution_id, author="user",
                        content=[Message(role="user", content="How many Desk Lamps?")]))
call = ToolCall(name="lookup_product", arguments={"name": "Desk Lamp"})
context.add_event(Event(execution_id=context.execution_id, author="agent", content=[call]))
print(context.execution_id, "steps:", context.current_step)
for e in context.events:
    print(f"  {e.id} by {e.author}: {[type(i).__name__ for i in e.content]}")
exec_0001 steps: 0
  evt_0004 by user: ['Message']
  evt_0005 by agent: ['ToolCall']

Every id comes from agentlab.ids, which counts instead of drawing random UUIDs when the notebook runs headless, so two runs of this notebook print the same ids.

Tools as objects

FunctionTool (used by tool(...)) wraps a function. Subclassing BaseTool directly is for tools that carry state or configuration. The tool below owns its catalog, counts its calls, and uses the process_llm_request hook to add a line to every request it is part of: a tool can shape the prompt, not only answer calls.

from agentlab import BaseTool
from agentlab.tools.schema import format_tool_definition, function_to_input_schema
 
 
class CatalogTool(BaseTool):
    """Look up one product in the shop's catalog: name, price in USD, and units in stock."""
 
    def __init__(self, catalog):
        super().__init__(name="lookup_product")
        self.catalog, self.calls = catalog, 0
        self._tool_definition = format_tool_definition(
            self.name, self.description, function_to_input_schema(lookup_product))
 
    async def process_llm_request(self, context, request):
        request.append_instructions(f"The catalog has {len(self.catalog)} products; "
                                    "product names are case-insensitive.")
 
    async def execute(self, context, name: str) -> dict:
        self.calls += 1
        return lookup_product(name)
 
 
catalog_tool = CatalogTool(CATALOG)
print(catalog_tool, "->", await catalog_tool(None, name="wool beanie"))
<CatalogTool lookup_product> -> {'name': 'Wool Beanie', 'price_usd': 15.25, 'stock': 31}

run, step, think, act

Now the agent. run records the user’s message and loops; step builds the request from the context, calls think, records the reply, and calls act if the reply asked for tools; act runs each call and records the results as one event. A reply with no tool calls is the final answer.

class MiniAgent:
    def __init__(self, model, tools, instructions="", max_steps=8, name="agent"):
        self.model, self.tools, self.name = model, tools, name
        self.instructions, self.max_steps = instructions, max_steps
        self.by_name = {t.name: t for t in tools}
 
    async def run(self, user_input: str) -> ExecutionContext:
        context = ExecutionContext()
        context.add_event(Event(execution_id=context.execution_id, author="user",
                                content=[Message(role="user", content=user_input)]))
        while self.should_stop(context) is None:
            await self.step(context)
        return context
 
    def should_stop(self, context) -> str | None:
        if context.final_result is not None:
            return "final"
        if context.current_step >= self.max_steps:
            return "max_steps"
        return None
 
    async def step(self, context) -> None:
        request = LlmRequest(instructions=[self.instructions], contents=context.contents(),
                             tools=self.tools, tool_choice="auto")
        for t in self.tools:
            await t.process_llm_request(context, request)
        response = await self.think(request)
        context.add_event(Event(execution_id=context.execution_id, author=self.name,
                                content=response.content))
        if response.tool_calls:
            await self.act(context, response.tool_calls)
        else:
            context.final_result = response.text
        context.increment_step()
 
    async def think(self, request):
        return await self.model.generate(request)
 
    async def act(self, context, tool_calls) -> None:
        results = []
        for tc in tool_calls:
            try:
                if tc.name not in self.by_name:
                    raise LookupError(f"no tool named {tc.name!r}")
                output = await self.by_name[tc.name](context, **tc.arguments)
                status, content = "success", [output]
            except Exception as exc:  # an error is an observation, not a crash
                status, content = "error", [f"{type(exc).__name__}: {exc}"]
            results.append(ToolResult(tool_call_id=tc.tool_call_id, name=tc.name,
                                      status=status, content=content))
        context.add_event(Event(execution_id=context.execution_id, author=self.name,
                                content=results))
 
 
mini = MiniAgent(llm, [catalog_tool, calculator_tool], instructions=SYSTEM)
context = await mini.run("How many Trail Mugs and Field Notebooks are in stock in total?")
show_trajectory(context)
print("final:", context.final_result, "| steps:", context.current_step,
      "| catalog calls:", catalog_tool.calls)
[user] How many Trail Mugs and Field Notebooks are in stock in total?
[agent -> lookup_product] {"name": "Trail Mug"}
[agent -> lookup_product] {"name": "Field Notebook"}
    [lookup_product ok] {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
    [lookup_product ok] {"name": "Field Notebook", "price_usd": 9.75, "stock": 120}
[agent -> calculator] {"expression": "42 + 120"}
    [calculator ok] 162
[agent] 162 in total
final: 162 in total | steps: 3 | catalog calls: 3

Three steps: two lookups in parallel, the addition, the answer. The tool’s extra instruction really was sent: here are the system messages of the last request.

last_request, _ = llm.calls[-1]
for line in last_request.instructions:
    print("system:", line)
system: You are a shop assistant. Use the tools to look up facts, then answer briefly.
system: The catalog has 5 products; product names are case-insensitive.

Does the 50-line agent behave like the library’s? Run both on the same questions and compare the trajectories line by line (the printout leaves out ids, which differ).

from agentlab.display import trajectory_lines
 
library = Agent(model=llm, tools=[catalog_tool, calculator_tool], instructions=SYSTEM)
for q in ["What would 3 Trail Mugs cost in total?",
          "What does a Field Notebook cost after a 20% discount?",
          "How much is a Quantum Kettle?"]:
    ours = trajectory_lines(await mini.run(q))
    theirs = trajectory_lines(await library.run(q))
    print(f"{'same' if ours == theirs else 'DIFFERENT'}: {len(ours)} lines  {q}")
same: 6 lines  What would 3 Trail Mugs cost in total?
same: 6 lines  What does a Field Notebook cost after a 20% discount?
same: 4 lines  How much is a Quantum Kettle?

The library class adds what this sketch leaves out: model errors, callbacks before and after each tool and model call, pausing for a human’s approval (Module 5), and structured output (Section 5). None of them change the shape of the loop.

4. When to stop

should_stop is the agent’s termination policy, and it is the one place where a small change has large effects. agentlab.Agent._should_stop returns a reason or None:

import inspect
 
print(inspect.getsource(Agent._should_stop))
    def _should_stop(self, context: ExecutionContext) -> str | None:
        """Why the loop should stop now, or ``None`` to keep going.

        ``"final"``     a final result exists (a plain answer, or a successful final_answer call)
        ``"error"``     the model call failed
        ``"max_steps"`` the step budget is spent: the guard against a model that never stops
        """
        if context.final_result is not None:
            return "final"
        if context.state.get("error"):
            return "error"
        if context.current_step >= self.max_steps:
            return "max_steps"
        return None

Each reason becomes the run’s status. To see all three, stage them: a model that answers, a model that never stops calling tools, and a model whose API call fails (here a rate-limit error, the most common failure of a real model call).

from agentlab import LlmResponse
from agentlab.llm.scripted import ToolCallSpec
 
rate_limited = lambda request: LlmResponse(error_message="RateLimitError: 429, retry later")
scripts = {
    "answers": ScriptedLLM([ToolCallSpec("lookup_product", {"name": "Desk Lamp"}),
                            "7 in stock."]),
    "loops": ScriptedLLM([ToolCallSpec("lookup_product", {"name": "Desk Lamp"})],
                         repeat_last=True),
    "API error": ScriptedLLM([ToolCallSpec("lookup_product", {"name": "Desk Lamp"}),
                              rate_limited]),
}
for label, model in scripts.items():
    staged = Agent(model=nb.track(model), tools=[lookup_tool], max_steps=5)
    r = await staged.run("How many Desk Lamps are in stock?")
    print(f"{label:>9}: status={r.status:<9} steps={r.context.current_step}  "
          f"output={r.output!r}")
  answers: status=complete  steps=2  output='7 in stock.'
    loops: status=max_steps steps=5  output=None
API error: status=error     steps=2  output='RateLimitError: 429, retry later'

The looping model used the whole budget, five identical lookups, and returned nothing. A budget is a blunt guard: it stops every loop, but only after paying for all of it. A sharper rule notices the repetition. Here it is as a subclass, since _should_stop is meant to be overridden:

class RepeatGuardAgent(Agent):
    """Also stop when the model makes the same call (same tool, same arguments) 3 times."""
 
    def _should_stop(self, context):
        reason = super()._should_stop(context)
        if reason is not None:
            return reason
        calls = [(i.name, json.dumps(i.arguments, sort_keys=True))
                 for e in context.events for i in e.content if isinstance(i, ToolCall)]
        if len(calls) >= 3 and len(set(calls[-3:])) == 1:
            context.state["error"] = f"stopped: {calls[-1][0]} called 3 times, same input"
            return "error"
        return None
 
 
guarded = RepeatGuardAgent(model=nb.track(ScriptedLLM(
    [ToolCallSpec("lookup_product", {"name": "Desk Lamp"})], repeat_last=True)),
    tools=[lookup_tool], max_steps=5)
r = await guarded.run("How many Desk Lamps are in stock?")
print(f"status={r.status} steps={r.context.current_step} output={r.output!r}")
status=error steps=3 output='stopped: lookup_product called 3 times, same input'

Is a repeated call always a mistake? No: a tool that polls a long-running job (job_status(id)) is supposed to be called with the same input until the job finishes. A stop rule encodes a belief about your tools, so it belongs to the agent you build, not to a framework default.

5. Structured output through a final-answer tool

A program that calls an agent usually wants a value, not a sentence. Module 2 got JSON from a single model call with a response schema. An agent has a complication: on every step the model either calls a tool or finishes, so the schema must apply only to the finish. The book’s solution is neat: make finishing itself a tool.

Pass output_type and the agent adds a tool named final_answer whose only argument is the schema you want. It also sets tool_choice="required", so every reply must be a tool call: either real work, or final_answer. A run is complete only when final_answer succeeds, and its validated argument becomes the result.

from typing import Literal
 
from pydantic import BaseModel, Field
 
 
class ShopAnswer(BaseModel):
    answer: str = Field(description="One short sentence for the customer.")
    value: float | None = Field(description="The number the question asks for, if any.")
    unit: Literal["USD", "items", "none"] = Field(description="The unit of value.")
 
 
typed = Agent(model=llm, tools=[catalog_tool, calculator_tool], instructions=SYSTEM,
              output_type=ShopAnswer)
final_tool = typed.tools[-1]
print(json.dumps(final_tool.tool_definition, indent=2))
{
  "type": "function",
  "function": {
    "name": "final_answer",
    "description": "Return the final structured answer matching the required schema.",
    "parameters": {
      "type": "object",
      "properties": {
        "output": {
          "properties": {
            "answer": {
              "description": "One short sentence for the customer.",
              "title": "Answer",
              "type": "string"
            },
            "value": {
              "anyOf": [
                {
                  "type": "number"
                },
                {
                  "type": "null"
                }
              ],
              "description": "The number the question asks for, if any.",
              "title": "Value"
            },
            "unit": {
              "description": "The unit of value.",
              "enum": [
                "USD",
                "items",
                "none"
              ],
              "title": "Unit",
              "type": "string"
            }
          },
          "required": [
            "answer",
            "value",
            "unit"
          ],
          "type": "object"
        }
      },
      "required": [
        "output"
      ]
    }
  }
}
result = await typed.run("What would 3 Trail Mugs cost in total?")
show_trajectory(result)
print("\noutput:", repr(result.output))
print("value + 1 =", result.output.value + 1)
print("tool_choice sent:", llm.calls[-1][0].tool_choice)
[user] What would 3 Trail Mugs cost in total?
[agent -> lookup_product] {"name": "Trail Mug"}
    [lookup_product ok] {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
[agent -> calculator] {"expression": "3 * 18.5"}
    [calculator ok] 55.5
[agent -> final_answer] {"output": {"answer": "USD 55.50", "value": 55.5, "unit": "USD"}}
    [final_answer ok] {"answer":"USD 55.50","value":55.5,"unit":"USD"}
--- status: complete, steps: 3

output: ShopAnswer(answer='USD 55.50', value=55.5, unit='USD')
value + 1 = 56.5
tool_choice sent: required

result.output is a ShopAnswer instance, so the caller can use .value directly. What if the model fills the schema wrongly? final_answer validates its argument with Pydantic; a validation error is an ordinary tool error, so it goes back to the model as an observation and the run continues. Staged:

fix_it = nb.track(ScriptedLLM([
    ToolCallSpec("lookup_product", {"name": "Trail Mug"}),
    ToolCallSpec("final_answer", {"output": {"answer": "About 55 dollars.",
                                             "value": "fifty-five", "unit": "dollars"}}),
    ToolCallSpec("final_answer", {"output": {"answer": "3 Trail Mugs cost USD 55.50.",
                                             "value": 55.5, "unit": "USD"}}),
]))
staged = Agent(model=fix_it, tools=[catalog_tool, calculator_tool], output_type=ShopAnswer)
result = await staged.run("What would 3 Trail Mugs cost in total?")
show_trajectory(result)
error = next(i for e in result.context.events for i in e.content
             if isinstance(i, ToolResult) and i.status == "error")
print("\nthe error the model saw:\n" + error.content[0])
print("\noutput:", repr(result.output))
[user] What would 3 Trail Mugs cost in total?
[agent -> lookup_product] {"name": "Trail Mug"}
    [lookup_product ok] {"name": "Trail Mug", "price_usd": 18.5, "stock": 42}
[agent -> final_answer] {"output": {"answer": "About 55 dollars.", "value": "fifty-five", "unit": "dollars"}}
    [final_answer ERROR] ValidationError: 2 validation errors for ShopAnswer value Input should be a valid number, una...
[agent -> final_answer] {"output": {"answer": "3 Trail Mugs cost USD 55.50.", "value": 55.5, "unit": "USD"}}
    [final_answer ok] {"answer":"3 Trail Mugs cost USD 55.50.","value":55.5,"unit":"USD"}
--- status: complete, steps: 3

the error the model saw:
ValidationError: 2 validation errors for ShopAnswer
value
  Input should be a valid number, unable to parse string as a number [type=float_parsing, input_value='fifty-five', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/float_parsing
unit
  Input should be 'USD', 'items' or 'none' [type=literal_error, input_value='dollars', input_type=str]
    For further information visit https://errors.pydantic.dev/2.14/v/literal_error

output: ShopAnswer(answer='3 Trail Mugs cost USD 55.50.', value=55.5, unit='USD')

The error message names both bad fields and the allowed values, which gives a real model what it needs to repair the call in one try. This is the same idea as Module 3’s argument validation, applied to the answer.

6. A mini benchmark

Is the agent any good? “It answered the three questions I tried” is not an answer. A benchmark, even a small one, needs four things:

  tasks      questions with known, checkable answers
  runner     runs every task the same way, a few at a time, and keeps each trace
  grader     decides pass/fail for one answer, the same way every time
  report     pass rate, plus enough per-task detail to explain each failure

Eight tasks, from one tool call to three steps, and one the catalog cannot answer:

TASKS = [
    {"id": "t1", "q": "What is 1234 * 5678?", "expect": 7006652},
    {"id": "t2", "q": "How many Desk Lamps are in stock?", "expect": 7},
    {"id": "t3", "q": "What would 3 Trail Mugs cost in total?", "expect": 55.5},
    {"id": "t4", "q": "What does a Field Notebook cost after a 20% discount?",
     "expect": 7.8},
    {"id": "t5", "q": "Which costs more, the Desk Lamp or the Canvas Tote?",
     "expect": "Desk Lamp"},
    {"id": "t6", "q": "How many Trail Mugs and Field Notebooks are in stock in total?",
     "expect": 162},
    {"id": "t7", "q": "Is the Canvas Tote in stock?", "expect": "no"},
    {"id": "t8", "q": "How much is a Quantum Kettle?", "expect": "REFUSE"},
]

The grader is plain code, three cases. A number passes if it appears in the answer (within a relative tolerance of ); a word passes if it appears as a whole word; REFUSE passes if the answer says it could not find the product. Plain-code graders are fast, free and repeatable, and their blind spots are easy to state, which matters later.

NUMBER = re.compile(r"-?\d[\d,]*(?:\.\d+)?")
REFUSAL = re.compile(r"could not|cannot|no product|not (?:find|in the catalog)", re.I)
 
 
def grade(task: dict, answer) -> bool:
    if answer is None:
        return False
    text, expect = str(answer), task["expect"]
    if expect == "REFUSE":
        return bool(REFUSAL.search(text))
    if isinstance(expect, (int, float)):
        numbers = [float(n.replace(",", "")) for n in NUMBER.findall(text)]
        return any(abs(n - expect) <= 1e-6 * max(1.0, abs(expect)) for n in numbers)
    return re.search(rf"\b{re.escape(expect)}\b", text, re.I) is not None
 
 
assert grade(TASKS[2], "USD 55.50") and not grade(TASKS[2], "USD 18.50")
assert grade(TASKS[6], "No, it is sold out.")
assert not grade(TASKS[6], "None left? Not sure.")

The runner gives each task a fresh run and its own token meter, and runs up to three tasks at once. The semaphore matters with a live model: it caps how many requests are in flight, which keeps you under the provider’s rate limit. Offline it changes nothing, since the policy model answers instantly.

import asyncio
 
from agentlab.llm.base import BaseLLM
 
 
class Metered(BaseLLM):
    """Pass calls through to another client, keeping a separate usage count."""
 
    def __init__(self, inner):
        super().__init__()
        self.inner, self.mode, self.model = inner, inner.mode, inner.model
 
    async def _generate(self, request):
        return await self.inner.generate(request)
 
 
async def run_suite(make_agent, tasks=TASKS, concurrency=3):
    gate = asyncio.Semaphore(concurrency)
 
    async def one(task):
        async with gate:
            meter = Metered(llm)
            result = await make_agent(meter).run(task["q"])
        return {"id": task["id"], "passed": grade(task, result.output),
                "status": result.status, "steps": result.context.current_step,
                "tokens": meter.usage.input_tokens, "answer": result.output,
                "result": result}
 
    return await asyncio.gather(*(one(t) for t in tasks))
 
 
CONFIGS = {
    "no tools": lambda m: Agent(model=m, tools=[], instructions=SYSTEM),
    "tools, max 2 steps": lambda m: Agent(model=m, tools=[catalog_tool, calculator_tool],
                                          instructions=SYSTEM, max_steps=2),
    "tools, max 8 steps": lambda m: Agent(model=m, tools=[catalog_tool, calculator_tool],
                                          instructions=SYSTEM, max_steps=8),
}
runs = {name: await run_suite(make) for name, make in CONFIGS.items()}
from IPython.display import Markdown
 
 
def short(x, n=58):
    s = " ".join(str(x).split())
    return s if len(s) <= n else s[: n - 3] + "..."
 
 
rows = ["| task | " + " | ".join(CONFIGS) + " |", "|---|" + "---|" * len(CONFIGS)]
for i, task in enumerate(TASKS):
    cells = [("pass" if r[i]["passed"] else "fail")
             + f" ({r[i]['steps']} step{'s' if r[i]['steps'] != 1 else ''})"
             for r in runs.values()]
    rows.append(f"| {task['id']} | " + " | ".join(cells) + " |")
rows.append("| **passed** | " + " | ".join(
    f"**{sum(x['passed'] for x in r)}/{len(r)}**" for r in runs.values()) + " |")
rows.append("| input tokens (est.) | " + " | ".join(
    f"{sum(x['tokens'] for x in r):,}" for r in runs.values()) + " |")
Markdown("\n".join(rows))
taskno toolstools, max 2 stepstools, max 8 steps
t1fail (1 step)pass (2 steps)pass (2 steps)
t2fail (1 step)pass (2 steps)pass (2 steps)
t3fail (1 step)fail (2 steps)pass (3 steps)
t4fail (1 step)fail (2 steps)pass (3 steps)
t5pass (1 step)pass (2 steps)pass (2 steps)
t6fail (1 step)fail (2 steps)pass (3 steps)
t7fail (1 step)fail (2 steps)fail (2 steps)
t8fail (1 step)pass (2 steps)pass (2 steps)
passed1/84/87/8
input tokens (est.)3064,2975,352

Read these numbers as mechanics

These rows say how far the offline rules get, not how good any agent design is. A real model without tools would get t1 right by arithmetic and would likely invent prices for the rest, which is worse than failing visibly. What does carry over is the procedure: the same harness, pointed at a real model, gives a real measurement.

Start with the one pass in the “no tools” column: it is not real. Without tools the offline model replies with a canned sentence that repeats the question, t5’s question contains “Desk Lamp”, and the grader looks for “Desk Lamp”. The grader passed an answer that answers nothing. Keep that in mind; it comes back below.

Two patterns are worth reading anyway. The 2-step budget fails exactly the tasks that need three steps (t3, t4, t6): the agent did not run out of ideas, it ran out of budget, and the status column says so. And one task fails under every configuration. Look at its trace before blaming anyone:

best = runs["tools, max 8 steps"]
for row in best:
    if not row["passed"]:
        print(f"{row['id']}: status={row['status']}, answer={short(row['answer'], 90)!r}")
        show_trajectory(row["result"])
t7: status=complete, answer='According to `lookup_product`: {"name": "Canvas Tote", "price_usd": 22.0, "stock": 0}'
[user] Is the Canvas Tote in stock?
[agent -> lookup_product] {"name": "Canvas Tote"}
    [lookup_product ok] {"name": "Canvas Tote", "price_usd": 22.0, "stock": 0}
[agent] According to `lookup_product`: {"name": "Canvas Tote", "price_usd": 22.0, "stock": 0}
--- status: complete, steps: 2

The answer contains the right fact ("stock": 0), but not in a form the grader accepts: it never says “no”. Is that the agent’s failure or the grader’s? Both readings are defensible, and a benchmark has to decide. Two fixes, from the sections above and ahead:

  • ask for structured output (Section 5) with a field such as in_stock: bool, so that grading compares a value instead of searching prose;
  • grade with a rubric and an LLM judge (Module 10), which reads meaning but costs money and needs its own validation.

The grader also errs the other way, as the t5 “pass” without tools showed: it checks that the right words appear, not that the answer says the right thing. A wrong answer that names the right product passes too:

wrong = "The Canvas Tote costs more than the Desk Lamp."
print("grader says:", "pass" if grade(TASKS[4], wrong) else "fail", "<- a false pass")
grader says: pass <- a false pass

Finally, cost. Each step resends the whole conversation, so a task’s input tokens grow faster than its step count (Module 1). The chart shows the estimated input tokens per task for the 8-step configuration.

import matplotlib.pyplot as plt
from matplotlib.patches import Patch
 
ids = [r["id"] for r in best][::-1]
tokens = [r["tokens"] for r in best][::-1]
colors = ["#2c5f9e" if r["passed"] else "#b5523b" for r in best][::-1]
fig, ax = plt.subplots(figsize=(6.4, 3.4))
bars = ax.barh(ids, tokens, color=colors)
for bar, r in zip(bars, best[::-1]):
    ax.text(bar.get_width() + 15, bar.get_y() + bar.get_height() / 2,
            f"{r['steps']} steps", va="center", fontsize=9)
ax.set_xlabel("input tokens (estimated)")
ax.set_xlim(0, max(tokens) * 1.22)
ax.spines[["top", "right"]].set_visible(False)
legend = [Patch(color="#2c5f9e", label="pass"), Patch(color="#b5523b", label="fail")]
ax.legend(handles=legend, frameon=False, loc="lower right")
fig.tight_layout()
plt.show()
Estimated input tokens per task (tools, 8-step budget), labelled with the number of steps. Tasks that need more steps cost more than proportionally, because each request resends the conversation so far.

Estimated input tokens per task (tools, 8-step budget), labelled with the number of steps. Tasks that need more steps cost more than proportionally, because each request resends the conversation so far.

A last caution about size. With eight tasks, one task moves the pass rate by 12.5 points, so a difference of one or two tasks between configurations says very little. Module 10 returns to this: more tasks, repeated runs (pass@k and pass^k), and confidence intervals.

Try this

  • Add in_stock: bool | None to ShopAnswer, rerun the benchmark with output_type=ShopAnswer, and change grade to compare fields. Which tasks change?
  • Add a task the rules do not cover (“What is the cheapest product?”). Read the trace. What would a model need to answer it: a new tool (list_products), or more steps?
  • Replace max_steps=8 with RepeatGuardAgent and a budget of 20. Does any task’s result change? Would it with a real model?
  • Set MODEL and rerun the whole notebook. Compare the text-protocol section first: does a real model follow tool[input] without the stop-sequence cut?
nb.usage()
model callsinput tokensoutput tokenscost
95 (fake: 73, scripted: 22)≈ 23,084≈ 1,308≈ USD 0.0283 (reference price)