# 3. An agent with a scripted model

**At the end you can:** run gvn's ready-made agent against a scripted model, offline, and
read what it did from the result, the output and the journal.

**What you will learn:** what an **actor** is, how the ready-made agent asks for a model call
instead of making one, and how the **Governor** carries out that request, records it and
streams it.

**Before this:** [2. Decisions and branching](decisions-and-branching.md).

**Time:** about 10 minutes.

## Where this sits in the big picture

Tutorials 1 and 2 stayed inside the **actor** box of the quickstart's
[big picture](../quickstart.md#the-big-picture). This page steps out into the loop around
it, with three boxes at once: an actor (the ready-made agent), the **Governor** that drives
it, and one **fulfiller**, the one that calls the model. The journal appears too, but only
as a list in memory; tutorial 6 is about it.

```mermaid
flowchart LR
    agent["<b>Agent</b><br/>(an actor)"]
    governor["<b>Governor</b>"]
    fulfiller["<b>ModelFulfiller</b>"]
    model["<b>ScriptedModel</b><br/>a fake model"]
    agent -- "request: invoke_model" --> governor
    governor --> fulfiller
    fulfiller -- "calls" --> model
    model -- "reply" --> fulfiller
    fulfiller -- "event: model_replied" --> governor
    governor -- "event" --> agent
```

The page builds that picture from left to right: first the agent on its own, to see that it
only asks; then the fake model; then the Governor that connects the two.

## Where you are

The first two tutorials built a ticket machine with the kernel alone. This tutorial leaves
the ticket aside and starts the help desk's agent: a program that answers customers with a
language model. Nothing from tutorial 2 is needed in code, only two ideas from it: a machine
that must handle every input in every state, and a Decision that picks one of a known set of
answers.

Everything on this page runs offline. The model is a scripted fake, so the output is the same
every time. Tutorial 12 swaps in a real model by changing one object.

**Start a new file for this page.** It uses no code from the earlier pages, so the first
block of step 1 is the first line of the file. Add each block below it, in order.

## Step 1: an agent is a machine with data

An **actor** is a verified machine together with the data it looks after. gvn ships a
reference agent, `Agent`, which keeps a conversation with a model under a budget of model
turns. Its `name` is the stable address of this run: requests and result events use it to
find the right actor. Its `instructions` are the standing directions for the model, separate
from the customer's question, which arrives in the next step. Creating the object neither
starts it nor calls the model.

Create one:

```python
from gvn.harness.agent import Agent

helpdesk = Agent(
    name="helpdesk",
    instructions="Answer customers of the shop briefly and politely.",
)
print(helpdesk.state())  # State('idle')
print(len(Agent.definition().states()))  # 18
```

`Agent.definition()` is the agent's machine, verified exactly like your ticket was, when the
module was imported. It has eighteen states, such as `thinking` (waiting for the model) and
`awaiting_approval` (waiting for a person). The [reference agent](../concepts/reference-agent.md)
page draws all of them; you will meet them one at a time.

## Step 2: hand it an event, and see that it only asks

Things that happen to an actor arrive as **events**. An `Event` is an input symbol, like the
ones you fed the ticket machine, plus an optional `payload` of plain JSON. The first event of
every agent is `started`, carrying the customer's message as its `prompt`.

Hand it to the agent directly, with no runtime around it:

```python
from gvn.harness.events import Event

question = Event(name="started", payload={"prompt": "Where is my order A-17?"})
helpdesk.handle(question)

print(helpdesk.state())  # State('thinking')
for request in helpdesk.pending():
    print(request.request_id(), request.kind().name())  # helpdesk/3 invoke_model
```

The agent moved to `thinking` and now holds one **request**: "please invoke the model". It did
not call a model. It cannot: actors in gvn never do I/O (no model, no tool, no clock, no
database). They only say what should happen next. The request carries everything needed to
do the work, such as the instructions and the conversation so far:

```python
print(helpdesk.pending()[0].payload()["instructions"])
# Answer customers of the shop briefly and politely.
```

The request id, `helpdesk/3`, is the agent's name and its machine's step count: on its way
to `thinking` the agent took three steps (it was started, it checked its turn budget, and it
checked that the conversation still fits the model's context window, the amount of text a
model can read in one call). It
is the same every time the run is replayed, which matters in tutorial 6.

Something must carry out that request and hand the answer back as the next event. That is
the Governor's job.

## Step 3: a model that follows a script

`ScriptedModel`, from gvn's test kit `gvn.testing.fakes`, is a fake model that answers from a
list you give it, one entry per call. Three pieces describe an answer:

- `Message.assistant(text=...)` constructs the model's message, with its complete answer.
- `Reply(message=...)` wraps that message as what a model returns to gvn.
- Streamed fragments are pieces delivered while generation is in progress; their
  concatenation is the message's complete text. A real model produces them as it writes.

An entry in `script` can be just a `Reply`, or a pair: a list of fragments to stream,
then the full `Reply`. This example uses a pair so the next steps can inspect streaming:

```python
from gvn.harness.messages import Message
from gvn.harness.ports import Reply
from gvn.testing.fakes import ScriptedModel

answer = "Order A-17 left our warehouse yesterday."
model = ScriptedModel(
    script=[
        (
            ["Order A-17 left ", "our warehouse yesterday."],
            Reply(message=Message.assistant(text=answer)),
        )
    ]
)
```

## Step 4: the Governor

The **Governor** is gvn's runtime. You give it:

- `fulfillers`: for each kind of request, the object that carries it out. `ModelFulfiller`
  carries out `invoke_model` by calling a `Model`. It also takes a `Toolbox` (the tools the
  model may be offered); this agent has none yet, so it is empty.
- `journal`: where each handled event is written before the Governor starts its resulting
  work. `MemoryJournal` keeps it in memory; tutorial 6 uses a file.
- `output`: where the Governor reports everything that happens. `RecordingOutput` keeps every
  report so you can look at it afterwards.
- `clock`: where time comes from. `ManualClock` is a fake clock that moves only when you tell
  it to.

The model, the journal, the output and the clock are **ports**: interfaces with a real
implementation and a fake one. Swapping a fake for the real thing does not change anything
else in the program.

```python
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

journal = MemoryJournal()
output = RecordingOutput()
governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
    journal=journal,
    output=output,
    clock=ManualClock(),
)
```

## Step 5: run the agent

`deliver(actor=..., event=...)` hands an event to an actor and keeps going, fulfilling every
request the actor makes, until the actor finishes or must wait for something from outside.
It is a coroutine, so run it with `asyncio.run`. Start from a fresh agent, since the one above
has already handled its `started` event:

```python
import asyncio

helpdesk = Agent(
    name="helpdesk",
    instructions="Answer customers of the shop briefly and politely.",
)
result = asyncio.run(governor.deliver(actor=helpdesk, event=question))

print(result.status())  # finished
print(result.outcome())
# Outcome('completed', {'text': 'Order A-17 left our warehouse yesterday.', 'tools': [], 'attempts': [],
#  'reductions': {'trimmed': 0, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0},
#  'recalls': {'asked': 0, 'found': 0, 'failed': 0},
#  'readings': {'taken': 0, 'failed': 0, 'blocked': 0, 'latest': {}}})
```

The `Result` says the run `finished`. Its `outcome()` is the agent's final state,
`completed`, and a payload: the answer's `text`, plus the tools it used and every tool call it
tried (none yet; tutorial 4 adds a tool), and `reductions`, how often the agent made its
conversation smaller to keep it within the model's context window (never, here; see
[Context management](../concepts/context-management.md)). The last two entries, `recalls` and
`readings`, count features this agent does not use, so they stay at zero.

## Step 6: see what happened

Three places tell you what the run did. The output streamed the text as the model wrote it:

```python
print(output.text())  # Order A-17 left our warehouse yesterday.
print(output.kinds())
# ('event', 'request', 'delta', 'delta', 'event', 'finished')
```

Each report is a **signal** of one kind: `event` (the agent handled an event), `request` (the
Governor started some work), `delta` (a fragment of text arrived), `finished`. Tutorial 7
looks at signals in detail.

The journal holds every event the agent handled, in order:

```python
records = asyncio.run(journal.read("helpdesk"))
print([record["event"]["name"] for record in records])  # ['started', 'model_replied']
```

`model_replied` is the event the Governor built from the model's reply and handed to the
agent. Those two events are the whole run: replaying them through a fresh agent rebuilds it
exactly.

And the fake model kept what it was asked:

```python
exchange = model.exchanges()[0]
print(exchange.instructions())  # Answer customers of the shop briefly and politely.
print([message.text() for message in exchange.messages()])  # ['Where is my order A-17?']
```

## Change it and run again

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

**1. A reply with no fragments.** Step 3 said a script entry can be just a `Reply`. Run a
second agent against such a model. Which kinds of signal reach the output now, and does
`output.text()` still hold the answer?

```python
plain_model = ScriptedModel(script=[Reply(message=Message.assistant(text=answer))])
plain_output = RecordingOutput()
plain_governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=plain_model, toolbox=Toolbox())},
    journal=MemoryJournal(),
    output=plain_output,
    clock=ManualClock(),
)
second = Agent(
    name="helpdesk-2",
    instructions="Answer customers of the shop briefly and politely.",
)
asyncio.run(plain_governor.deliver(actor=second, event=question))
print(plain_output.kinds())
print(plain_output.text())
```

??? note "What happens"

    ```text
    ('event', 'request', 'delta', 'event', 'finished')
    Order A-17 left our warehouse yesterday.
    ```

    There is one `delta` instead of two: the whole answer arrives as a single fragment.
    A view that shows `delta` signals works the same with a model that streams and one that
    answers in one piece.

**2. Ask a second question.** The script of `plain_model` had one entry, and the run above
used it. Deliver `question` to a third agent, `Agent(name="helpdesk-3", instructions="...")`,
through `plain_governor`. What happens?

??? note "What happens"

    ```text
    ScriptExhausted: the script has no entries left
    ```

    `deliver` raises `ScriptExhausted`. A scripted model answers exactly the calls you
    wrote for it, so a run that asks the model more often than you planned fails loudly
    in a test.

## Recap

- An **actor** is a verified machine plus its data. `Agent` is gvn's ready-made one.
- An actor handles **events** and answers with **requests**; it never does I/O itself.
- The **Governor** fulfils requests through **ports** (model, journal, output, clock),
  journals every event, and reports every step as a signal.
- `ScriptedModel` and the other fakes make a run offline and repeatable.

**Next:** [4. Adding a tool](adding-a-tool.md) lets the agent look up the order instead of
guessing.
