# 4. Adding a tool

**At the end you can:** give the agent a tool of your own, and read from the transcript and
the outcome what the agent did with it.

**What you will learn:** how to write a **tool**, offer it to the agent, and follow what the
agent does when the model asks for it, including when the tool fails.

**Before this:** [3. An agent with a scripted model](first-agent.md).

**Time:** about 10 minutes for the main idea (steps 1 to 6), and 10 more for "Going further".

## Where this sits in the big picture

In the quickstart's [big picture](../quickstart.md#the-big-picture), the Governor hands each
request to a **fulfiller**. Tutorial 3 used one, for the model. This page adds the other
two the agent needs: one that runs your **tools**, and one that asks a **policy** whether a
tool call may run. The agent itself only gains the identities of the tools it may offer;
the code of the tools stays on the Governor's side, in a toolbox.

```mermaid
flowchart LR
    agent["<b>Agent</b><br/>knows tool identities"]
    governor["<b>Governor</b>"]
    model["ModelFulfiller"]
    policy["PolicyFulfiller<br/><i>new</i>"]
    tools["ToolFulfiller + Toolbox<br/><i>new</i>"]
    agent -- "requests" --> governor
    governor -- "invoke_model" --> model
    governor -- "consult_policy" --> policy
    governor -- "invoke_tools" --> tools
```

## Where you are

At the end of tutorial 3 the help desk agent answered from the model alone.

**Start a new file for this page, and begin it with the block below.** The block holds
everything from the earlier pages that this page uses, imports included. That is the same
first step whether you have just finished tutorial 3 or are starting here. Then add each
block of the page below it, in order.

??? example "The agent from tutorial 3"

    ```python
    import asyncio
    import typing

    from gvn.harness.agent import Agent
    from gvn.harness.events import Event
    from gvn.harness.messages import Message
    from gvn.harness.ports import Reply
    from gvn.harness.tools import Toolbox
    from gvn.runtime.fulfillers import ModelFulfiller
    from gvn.runtime.governor import Governor
    from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel

    model = ScriptedModel(
        script=[Reply(message=Message.assistant(text="Order A-17 left our warehouse yesterday."))]
    )
    governor = Governor(
        fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )
    helpdesk = Agent(name="helpdesk", instructions="Answer customers of the shop briefly.")
    question = Event(name="started", payload={"prompt": "Where is my order A-17?"})
    result = asyncio.run(governor.deliver(actor=helpdesk, event=question))
    print(result.outcome().payload()["text"])  # Order A-17 left our warehouse yesterday.
    ```

That agent made its answer up. A help desk should look the order up first.

## Step 1: the shop's orders

The orders are the outside world the tool will read. In gvn, data lives in an object that
owns it and changes it only through its own methods, so the orders get a small class of their
own rather than a global dict:

```python
class OrderBook:
    """The shop's orders. Not part of the harness: the world the tools act on."""

    def __init__(self, orders: dict[str, dict[str, typing.Any]]) -> None:
        self._orders = {order_id: dict(order) for order_id, order in orders.items()}

    def find(self, order_id: str) -> dict[str, typing.Any]:
        return dict(self._orders[order_id])


order_book = OrderBook(
    orders={
        "A-17": {"status": "shipped", "total": 40.0},
        "B-22": {"status": "delivered", "total": 120.0},
    }
)
```

## Step 2: write the tool

A **tool** is work the model can ask for. The `FunctionTool` of the
[quickstart](../quickstart.md#step-3-run-a-real-agent-through-the-whole-loop) is one: it is
a ready-made `Tool` that wraps a plain function, and it goes in a `Toolbox` and to an agent
exactly like the tool you write here. Write a `Tool` subclass, as on this page, when the
tool needs the facts about the call that only `run` receives (its `invocation`, described
below), or when you want the tool to be an object of your own that is handed what it works
with (here, the order book).

You subclass `Tool` and fill in four methods:

- `name()`: the tool's **short name**, the one the model sees and calls it by.
- `description()`: what it does, written for the model.
- `arguments()`: the arguments it takes, as an explicit **schema**: an object that says what
  a value must look like and checks it. `Record` describes a dict with named fields; `Text()`
  is a string.
- `run(arguments, invocation)`: the work itself. It is a coroutine (`async def`) and returns plain
  JSON.

`arguments` passed to `run` is this call's data, already checked against the schema returned
by `arguments()`. `invocation` describes the call: which agent asked, the
[run context](../reference/glossary.md#run-context) (trusted facts your code gave the agent)
and a key that stays the same if the call is repeated; tutorial 6 uses the key to make
repeated effects safe. The order-book dependency is supplied to the
tool's constructor, so the tool can read orders without the agent owning that service.

gvn also gives every tool an **identity**: its **namespace**, a dot and its short name. The
namespace is the Python module that defines the tool's class. This script runs as
`__main__`, so here the identity is `__main__.look_up_order`; defined in a module of your own
package it would be, for example, `shop.orders.look_up_order`. The identity is what gvn
stores and matches on, so two packages that both ship a `look_up_order` are never confused.

A **Toolbox** groups the concrete tools the runtime can run. You build each tool once, as an
object, put it in the toolbox, and give the same object to the agent. The agent stores only
the identities of the tools it is given; the runtime holds the objects. Before the run
starts, the Governor checks that the toolbox holds every tool the agent was given.
[Tools](../concepts/tools.md#two-names-the-short-name-and-the-identity) explains the two
names in full.

```python
from gvn.harness.tools import Invocation, Tool, Toolbox
from gvn.kernel.schema import Record, Text


class LookUpOrder(Tool):
    def __init__(self, order_book: OrderBook) -> None:
        self._order_book = order_book

    def name(self) -> str:
        return "look_up_order"

    def description(self) -> str:
        return "Look up one order by its id. Returns its status and total."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        return self._order_book.find(arguments["order_id"])


look_up_order = LookUpOrder(order_book=order_book)
toolbox = Toolbox([look_up_order])
print(look_up_order.name())  # look_up_order
print(look_up_order.identity())  # __main__.look_up_order
print(toolbox.identities())  # ('__main__.look_up_order',)
```

## Step 3: a policy, for now one that allows everything

Before any tool runs, the agent asks a **policy** whether the calls may go ahead. The policy is
a [Decision](decisions-and-branching.md#step-1-write-a-decision) with exactly three possible
answers, gvn's `VERDICTS`: `cleared`, `needs_approval` and `forbidden`. Tutorial 5 writes a
real policy. Until then, clear everything:

```python
from gvn.harness.agent import VERDICTS
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol


class AllowEverything(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")
```

## Step 4: a model that asks for the tool

The script now has two replies. The first asks for the tool: an assistant message with no
text and one `ToolCall`. A tool call has a `call_id` (invented by the model, so that the
result can answer it), the tool's short `name` (the model only ever sees short names) and
its `arguments`. The second reply is the answer, written
after the model has seen the tool's result.

```python
import asyncio

from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Model, Reply
from gvn.testing.fakes import ScriptedModel

look_up_a17 = ToolCall(call_id="call-1", name="look_up_order", arguments={"order_id": "A-17"})
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(calls=[look_up_a17])),
        Reply(message=Message.assistant(text="Order A-17 has shipped.")),
    ]
)
```

## Step 5: wire the Governor and run

The agent now makes two more kinds of request, so the Governor needs two more fulfillers:
`ToolFulfiller` runs the tools in the toolbox (`invoke_tools`), and `PolicyFulfiller` asks
the policy (`consult_policy`). The agent is given the tools it may offer the model with
`tools=[...]`: the tool objects, the same ones the toolbox holds.

```python
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput


def build_governor(model: Model, policy: Decision) -> Governor:
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=policy),
        },
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )


helpdesk = Agent(
    name="helpdesk",
    instructions="Answer customers of the shop. Look orders up before answering.",
    tools=[look_up_order],
)
question = Event(name="started", payload={"prompt": "Where is my order A-17?"})
result = asyncio.run(
    build_governor(model=model, policy=AllowEverything()).deliver(actor=helpdesk, event=question)
)
print(result.outcome().payload()["text"])  # Order A-17 has shipped.
```

The function `build_governor` will be reused below and in the next tutorials, each time with
a different model or policy.

## Step 6: follow what the agent did

The agent went round its machine twice: once to get the tool call, once to get the answer.
Its **transcript** is the conversation the model saw, one message per turn:

```python
for message in helpdesk.transcript():
    called = [call.name() for call in message.calls()]
    returned = [tool_result.content() for tool_result in message.results()]
    print(f"{message.role():<9} {message.text()!r} {called or ''}{returned or ''}")
```

```text
user      'Where is my order A-17?' 
assistant '' ['look_up_order']
tool      '' [{'status': 'shipped', 'total': 40.0}]
assistant 'Order A-17 has shipped.' 
```

The `tool` message holds the tool's result, which the Governor turned into an event and the
agent added to the transcript before asking the model again.

The outcome also records what the agent *did*, not only what it said. `"attempts"` lists
every tool call the model made, in order, with the tool's short `"name"` and its
`"identity"`, a status and a `"detail"`; `"tools"` repeats
the successful ones with their content:

```python
print(result.outcome().payload()["attempts"])
# [{'name': 'look_up_order', 'identity': '__main__.look_up_order', 'arguments': {'order_id': 'A-17'}, 'status': 'ok', 'detail': {'status': 'shipped', 'total': 40.0}}]
```

## You have the main idea

You can now write a tool, put it in a toolbox, offer it to an agent, wire the three
fulfillers, and read what happened from the transcript and from the outcome's `attempts`.
That is all the next tutorial needs.

## Going further

The rest of the page covers what a tool does beyond returning JSON:

- **Step 7, a tool that fails.** You need it as soon as a tool talks to something that can
  say no or be out of reach: how to tell the model why, and how to have the call tried
  again.
- **Step 8, a tool that returns an image.** You need it when the model should look at a
  picture or a PDF, not only read JSON.

### Step 7: a tool that fails

What if the model asks for an order that does not exist? `OrderBook.find` raises `KeyError`.
Nothing crashes: the Governor catches it, and the model receives a failed tool result saying
why, so it can decide what to tell the customer.

```python
model = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(
                calls=[ToolCall(call_id="call-1", name="look_up_order", arguments={"order_id": "Z-99"})]
            )
        ),
        Reply(message=Message.assistant(text="I cannot find order Z-99. Could you check it?")),
    ]
)
lost_order = Agent(
    name="helpdesk-2",
    instructions="Answer customers of the shop. Look orders up before answering.",
    tools=[look_up_order],
)
result = asyncio.run(
    build_governor(model=model, policy=AllowEverything()).deliver(
        actor=lost_order,
        event=Event(name="started", payload={"prompt": "Where is order Z-99?"}),
    )
)
print(lost_order.transcript()[2].results()[0].content())
# {'error': 'tool_raised', 'detail': "KeyError: 'Z-99'"}
print(result.outcome().payload()["attempts"][0]["status"])  # failed
```

The agent's name changed to `helpdesk-2`: an agent's name identifies its run, and two runs
must not share a name in one journal.

#### Saying why a call failed

The failed result's content is always `{"error": <kind>, "detail": <text>}`, and the kind
says who is at fault. `tool_raised` means the tool raised an exception gvn knows nothing
about, which gvn reads as a defect in the tool: a `KeyError` from a lookup is exactly that.
A tool that *understands* a failure says so by raising `ToolFailure(reason, retryable=...)`
instead, and the kind says which of two things happened:

| The tool raised | The result's `"error"` | Meaning |
|---|---|---|
| `ToolFailure(reason)` | `tool_rejected` | the service answered and said no (not found, not permitted, invalid for it); asking again would get the same answer |
| `ToolFailure(reason, retryable=True, retry_after=None)` | `tool_unavailable` | the service could not be reached or asked to wait (an outage, a timeout, a rate limit); the same call may succeed later. `retry_after` is the seconds it asked to wait, when it said |
| any other exception | `tool_raised` | a defect in the tool |

The `reason` is the `"detail"` the model reads, so write it for the model. Here is the
lookup again, saying what went wrong:

```python
from gvn.harness.tools import ToolFailure


class LookUpOrder(Tool):
    def __init__(self, order_book: OrderBook) -> None:
        self._order_book = order_book

    def name(self) -> str:
        return "look_up_order"

    def description(self) -> str:
        return "Look up one order by its id. Returns its status and total."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        try:
            return self._order_book.find(arguments["order_id"])
        except KeyError:
            raise ToolFailure(f"there is no order {arguments['order_id']}") from None


look_up_order = LookUpOrder(order_book=order_book)
toolbox = Toolbox([look_up_order])
model = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(
                calls=[ToolCall(call_id="call-1", name="look_up_order", arguments={"order_id": "Z-99"})]
            )
        ),
        Reply(message=Message.assistant(text="I cannot find order Z-99. Could you check it?")),
    ]
)
told_why = Agent(
    name="helpdesk-3",
    instructions="Answer customers of the shop. Look orders up before answering.",
    tools=[look_up_order],
)
asyncio.run(
    build_governor(model=model, policy=AllowEverything()).deliver(
        actor=told_why,
        event=Event(name="started", payload={"prompt": "Where is order Z-99?"}),
    )
)
print(told_why.transcript()[2].results()[0].content())
# {'error': 'tool_rejected', 'detail': 'there is no order Z-99'}
```

#### Saying whether a call may be tried again

A tool over a network service raises `ToolFailure(..., retryable=True)` when the service is
down or busy. By default that call fails once, as `tool_unavailable`. Whether it should be
sent again is for the tool to say, because only the tool knows whether repeating it is safe:
looking an order up twice is harmless, refunding it twice is not, unless the payment service
recognises the call's key (the key of step 2, which stays the same when a call is repeated;
such a key is called an **idempotency key**) and acts once. A tool says so with `retry()`, which returns None (the
default: one attempt) or a `Retry` from `gvn.harness.ports` (how many attempts in all,
and how long to wait between them, on a clock). The `ToolFulfiller` reads it for every call
and runs a retryable failure again, with the same key, until the `Retry` gives up. Here
the lookup takes the retry it declares when it is made:

```python
from gvn.adapters.clock import SystemClock
from gvn.harness.ports import Retry


class LookUpOrder(Tool):
    def __init__(self, order_book: OrderBook, retry: Retry | None = None) -> None:
        self._order_book = order_book
        self._retry = retry

    def name(self) -> str:
        return "look_up_order"

    def description(self) -> str:
        return "Look up one order by its id. Returns its status and total."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    def retry(self) -> Retry | None:
        return self._retry

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        try:
            return self._order_book.find(arguments["order_id"])
        except KeyError:
            raise ToolFailure(f"there is no order {arguments['order_id']}") from None


patient = Retry(attempts=3, clock=SystemClock(), first_delay=0.5, longest_delay=5.0)
print(LookUpOrder(order_book=order_book, retry=patient).retry())
# Retry(attempts=3, first_delay=0.5, longest_delay=5.0)
print(LookUpOrder(order_book=order_book).retry())
# None
```

A failure the service gave (`there is no order Z-99`) is still not retried, whatever the
`Retry` says: only `retryable=True` is.

`retry()` must return the same thing for the tool's whole life; anything other than None or
a `Retry` is a `TypeError` naming the tool. Every attempt carries the same `Invocation`, so
the same idempotency key: declare a `Retry` only when a repeat under that key is harmless (a
pure read, or a service that honours the key).
[Fan-out over items, with retries](../guides/items-and-retries.md#retrying-a-tool-call)
shows a retried call end to end.

### Step 8: a tool that returns an image

Some tools produce something the model should *look at*: a screenshot, a photo of a damaged
parcel, a rendered chart. JSON cannot carry that, so such a tool returns a `ToolOutput`
instead: its `content` is the JSON the model reads, as before, and its `attachments` are
images or PDF documents the model sees right after it. Each one is an `Attachment`, the same
value a user's message uses for images (the
[vendors guide](../guides/vendors.md#images-and-documents) shows that use).

Here the shop keeps a photo of each parcel when it leaves. The bytes below stand in for a
real PNG file:

```python
from gvn.harness.messages import Attachment
from gvn.harness.tools import ToolOutput

parcel_photo = b"\x89PNG\r\n\x1a\n" + bytes(56)  # a real tool reads or captures a PNG


class ShowParcelPhoto(Tool):
    def name(self) -> str:
        return "show_parcel_photo"

    def description(self) -> str:
        return "Show the photo taken of an order's parcel when it left the warehouse."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        photo = Attachment.image(data=parcel_photo, media_type="image/png")
        return ToolOutput(content={"order_id": arguments["order_id"]}, attachments=[photo])
```

`Attachment.image` checks the bytes before anything is sent: a supported type (PNG, JPEG,
GIF or WebP), bytes that start the way that type's files start, at most 5 MB. One result
carries at most 20 attachments and 5 MB together. A tool that returns plain JSON, like
`LookUpOrder`, is unaffected.

Run it the way you ran the order lookup, with its own toolbox:

```python
show_parcel_photo = ShowParcelPhoto()
photo_toolbox = Toolbox([show_parcel_photo])
show_photo = ToolCall(call_id="call-1", name="show_parcel_photo", arguments={"order_id": "A-17"})
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(calls=[show_photo])),
        Reply(message=Message.assistant(text="The parcel left in one piece.")),
    ]
)
photo_governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=photo_toolbox),
        "invoke_tools": ToolFulfiller(toolbox=photo_toolbox),
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
inspector = Agent(name="inspector", instructions="Check parcels.", tools=[show_parcel_photo])
photo_run = asyncio.run(
    photo_governor.deliver(
        actor=inspector,
        event=Event(name="started", payload={"prompt": "Did A-17 leave undamaged?"}),
    )
)
photo_result = inspector.transcript()[2].results()[0]
print(photo_result.content())  # {'order_id': 'A-17'}
print(photo_result.attachments())  # (Attachment(image, 'image/png', <64 bytes>),)
print(photo_run.outcome().payload()["attempts"][0]["detail"])  # {'order_id': 'A-17'}
```

The tool's result in the transcript carries the photo next to its JSON, and the vendor
adapters (gvn's connections to real models, tutorial 12) send both to a real model in the vendor's own shape for tool results. Notice what
does *not* carry the photo: the outcome's `attempts` record the JSON content only, and the
policy never sees results at all. The photo is data for the model, nothing more.

!!! note "Images are stored with the run"
    The photo is written into the journal with the tool's result, as base64 (about 1.33
    bytes per byte of image), and it is sent again on every later model call of the run.
    Keep images small; the [vendors guide](../guides/vendors.md#images-and-documents-from-tools)
    has the measured numbers.

## Change it and run again

Predict the answer first, then run the code and open the block.

**1. The model gets an argument name wrong.** The tool takes `order_id`; this model sends
`order`. Does `run` get called? What does the model read?

```python
wrong_name = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(
                calls=[ToolCall(call_id="call-1", name="look_up_order", arguments={"order": "A-17"})]
            )
        ),
        Reply(message=Message.assistant(text="Could you give me the order id?")),
    ]
)
confused = Agent(
    name="helpdesk-4",
    instructions="Answer customers of the shop. Look orders up before answering.",
    tools=[look_up_order],
)
result = asyncio.run(
    build_governor(model=wrong_name, policy=AllowEverything()).deliver(
        actor=confused,
        event=Event(name="started", payload={"prompt": "Where is my order?"}),
    )
)
print(confused.transcript()[2].results()[0].content())
print(result.outcome().payload()["attempts"][0]["status"])
```

??? note "What happens"

    ```text
    {'error': 'invalid_arguments', 'detail': '$.order_id: missing required field; $.order: unknown field'}
    failed
    ```

    `run` is never called. gvn checks the arguments against the schema from `arguments()`
    first, and the model reads a failed result that names both mistakes, so it can correct
    the call.

**2. Offer a tool the toolbox does not hold.** `build_governor` uses `toolbox`, which holds
only the order lookup. Give an agent the parcel photo tool as well, and deliver a question.
How far does the run get?

```python
from gvn.runtime.governor import Unfulfillable

two_tools = Agent(
    name="helpdesk-5",
    instructions="Answer customers of the shop.",
    tools=[look_up_order, show_parcel_photo],
)
try:
    asyncio.run(
        build_governor(model=wrong_name, policy=AllowEverything()).deliver(
            actor=two_tools,
            event=Event(name="started", payload={"prompt": "Where is my order?"}),
        )
    )
except Unfulfillable as refusal:
    print(refusal)
print(two_tools.state())
```

??? note "What happens"

    ```text
    actor 'helpdesk-5' cannot be driven: the 'invoke_model' fulfiller lacks what it needs: the tool '__main__.show_parcel_photo', which the toolbox does not hold
    State('idle')
    ```

    Nowhere: this is the check from step 2. The Governor compares the agent's tools with
    the toolbox before anything happens, so the agent is still `idle` and the model was not
    called.

## Recap

- A **tool** is a `Tool` subclass with a short name, a description, an argument schema and an
  `async run`. Its short name, `name()`, is what the model sees; its identity (namespace,
  a dot, short name) is what gvn stores and matches on.
- You build each tool once and pass the object: to the `Toolbox` on the runtime side, and to
  the agent, which stores only the identities. Before the run, the Governor checks that the
  toolbox holds every tool the agent was given.
- Before tools run, the agent consults a **policy**, a Decision over the three `VERDICTS`.
- The Governor needs one fulfiller per kind of request: `invoke_model`, `invoke_tools` and
  `consult_policy`.
- A tool that raises becomes a failed result for the model, not a crash. The outcome's
  `attempts` records every call and how it ended.
- A tool that knows why a call failed raises `ToolFailure`: `tool_rejected` when the
  service said no, `tool_unavailable` (`retryable=True`) when it could not be reached. Any
  other exception is `tool_raised`, a defect in the tool.
- A tool whose calls are safe to repeat under one key declares `retry()`, a `Retry`; the
  `ToolFulfiller` then tries a `retryable=True` failure again. The default is one attempt.
- A tool that should show the model an image or a PDF returns a `ToolOutput`: JSON content
  plus attachments.

**Next:** [5. A policy and approval by a person](agent-with-approval.md) adds a refund tool
that a person must approve, and one the policy forbids outright.
