Browse documentation
Concepts
View Markdown
On this page

Actors and events

What you will learn: how gvn attaches real data (a prompt, a model reply, tool arguments) to a purely symbolic machine, and how you drive an actor by hand, playing the part of the model yourself.

Read first: Machines, Decisions, Durable objects. Time: about 15 minutes.

Where this sits. The three pages before this one built the parts of an actor in the kernel: a machine, the decisions it branches on, and data that can be saved. This page puts them together into an actor and shows the two arrows between it and the Governor in the loop that runs: an event goes in, requests come out. This is the first page about the harness layer.

flowchart LR
    governor["Governor"] -- "Event: input name + data" --> actor["<b>Actor</b><br/>machine + data"]
    actor -- "Requests: output name + data" --> governor

The problem: machines carry names, work needs data

A kernel machine is purely symbolic: it consumes input names and emits output names. Real work needs data. "Call the model" is useless without the instructions and the transcript; "the model replied" is useless without the reply.

Picture a helper that answers a prompt. Its machine says invoke_model. Something outside has to actually call the model, with the right text, and then come back with the reply and say model_replied. So the data has to travel next to the names, in both directions, and the reply has to find its way back to the right helper even when hundreds are running.

An actor is an object that owns a machine plus the data that goes with it, and is durable as a whole. The runtime is the code that does the actual work (calls the model, runs the tool) and feeds the results back; you meet its central object on The Governor page.

The harness layer (gvn.harness) adds the data with three small value types and one interface:

Type What it is
Event an input name and payload, with an optional address and answering principal
Request an output symbol naming work, plus the data needed to do it, plus a stable id
Reaction what handling one event did: the machine steps taken and the requests now wanted
Actor the interface the runtime drives: it turns events into requests and never does I/O

What the interface hides

The runtime needs to know what an actor wants, whether it has finished, and how to restore it. It does not need to know how the actor stores a transcript or how many children it owns. An agent and a workflow can therefore have the same runtime-facing interface while keeping different implementations.

flowchart LR
    Governor["Governor"] -->|"handle(event), pending(), outcome()"| Interface["Actor interface"]
    subgraph Owned["State owned by one actor"]
        Interface --> Control["Machine: current control state"]
        Interface --> Data["Data: transcript, budget, or child actors"]
    end
    Interface -->|"to_dto() / from_dto()"| Saved["Dto: saved state"]

The arrows show access and ownership. They are not transitions of the actor's machine. Event and Outcome (how an actor ended: the final state it reached and its result data) are data crossing this interface; their payload meanings are an agreement between producer and consumer. An actor takes another's place in an application when it meets the obligations in Interface contracts.

Step 1: an event is an input with data

An Event takes a name, the input it is (a Symbol or its name as a str), a payload of plain JSON (default None) and an optional address to (which actor the event is for when actors are nested; see Deeper: addresses). name() gives the input's name as a str. The actor looks up that name in its machine's input alphabet.

from gvn.harness.events import Event, Request

started = Event(name="started", payload={"prompt": "Say hi."})
print(started.name(), started.payload(), started.to())
started {'prompt': 'Say hi.'} None

An event is immutable and durable. Equality includes its name, payload, address and answering principal. For an authenticated answer, the application passes a Principal to Governor.answer(..., by=principal) and the Governor stamps it onto the event. Read it back with event.by() or see Trust.

Step 2: a request is an output with data

A Request is the payload-carrying form of an output. It has a kind (the output symbol), a payload, and a request_id (read back with request_id()). The reference agent uses "<actor name>/<step count>":

model_call = Request(
    request_id="helper/3",
    kind="invoke_model",
    payload={"instructions": "Be brief."},
)
print(model_call.origin(), model_call.kind())
helper Symbol('invoke_model')

An actor assigns a deterministic id so the same request reissued after a crash keeps it. The part before the last / is the origin, the name of the actor that wants the work. Actor names may contain / (for example, a workflow's child may be named report/researching.1.0). The suffix can be another stable name, such as wake_at for a workflow deadline.

Step 3: drive an actor by hand

You do not need the runtime to see an actor work. Here is the reference agent, gvn's built-in model-and-tools agent, driven directly. Start it with a prompt:

from gvn.harness.agent import Agent

helper = Agent(name="helper", instructions="Be brief.")
reaction = helper.handle(Event(name="started", payload={"prompt": "Say hi."}))
for step in reaction.steps():
    print(step)

request = reaction.request()  # the single request, or None
print(request.request_id(), request.kind())
Step(idle --started--> admitting / check_budget, declared)
Step(admitting --within_budget--> measuring / check_context, declared)
Step(measuring --context_fits--> thinking / invoke_model, declared)
helper/3 Symbol('invoke_model')

One handle call took three steps. Notice the difference between their outputs:

  • check_budget and check_context are internal outputs: Decisions the agent makes itself, from its own data, with no I/O. The agent resolved each on the spot by feeding the answer (within_budget, then context_fits: the conversation still fits the share of the model's context window the agent may use; see Context management) to its own machine.
  • invoke_model is external: it became a Request for the outside world.

An actor keeps stepping until it reaches an external output or one that names no work.

Now answer as the model would. Message is gvn's form of one chat message, and Message.assistant(...) builds a message from the model (the assistant). The event's payload is the plain form of that message:

from gvn.harness.messages import Message

reply = Message.assistant(text="Hi.")
reaction = helper.handle(
    Event(name="model_replied", payload={"message": reply.to_dto().to_plain()})
)
print(helper.finished(), helper.outcome())
print(reaction.requests())
True Outcome('completed', {'text': 'Hi.', '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 agent finished. Its outcome is the final state it reached plus a result payload, and it wants nothing more from the outside world.

Step 4: the Actor interface

Actor is an ABC (an abstract base class: a class that declares the methods every implementation must provide) in gvn.harness.actor. The runtime knows nothing else about what it drives.

Method Returns
name() the actor's address, stable for its whole life
handle(event) a Reaction; synchronous, no I/O
pending() the tuple of Requests the actor wants from the outside world
definition() the kernel Definition of its control machine (callable on the class)
state(), expected(), finished() as for a machine
settles(event) whether this event could finish the actor; the default True is safe for a custom actor
outcome() an Outcome (final state + result payload); NotFinished before that
to_dto(), from_dto() the Dto protocol

Two laws hold for every actor:

  1. After any handle call, reaction.requests() == actor.pending(). A reaction always carries all the requests the actor wants, not only new ones.
  2. An event that raises, or is rejected, changes nothing, data included.

pending() is what makes recovery possible. A revived actor still knows what it was waiting for, so the runtime can re-issue that work.

Step 5: events that do not fit

An event can go wrong in two ways, and they are treated differently.

Not expected here. The symbol is a valid input, but the current state does not declare it. That is not an error: handle returns a rejected reaction whose one step is the undeclared step, and the actor is unchanged.

waiting_helper = Agent(name="helper", instructions="Be brief.")
waiting_helper.handle(Event(name="started", payload={"prompt": "Say hi."}))
reaction = waiting_helper.handle(Event(name="approved"))  # nobody asked for approval
print(reaction.rejected())
print(reaction.requests() == waiting_helper.pending())
True
True

The second line shows the first law: the rejected reaction still carries the model call the agent was already waiting for.

Not valid at all. An unknown symbol raises UnknownSymbol; a payload that does not fit the symbol raises ValueError; a wrong address raises ValueError. The actor is unchanged in every case.

from gvn.kernel.symbols import UnknownSymbol

try:
    waiting_helper.handle(Event(name="model_replied", payload={"message": "not a message"}))
except ValueError as error:
    print("ValueError:", error)

try:
    waiting_helper.handle(Event(name="teleported"))
except UnknownSymbol as error:
    print("UnknownSymbol:", error)
ValueError: invalid payload for 'model_replied': $.message: expected an object, got str
UnknownSymbol: 'teleported' is not an input of the agent machine

That is the 80% you need. The rest is about nesting and writing your own actor.

Deeper: addresses

Actors nest. A workflow contains agents, and those agents emit requests. When the result comes back, it has to reach the right agent. The rule is simple:

  • A request's id starts with the name of the actor that issued it.
  • The runtime addresses each result event to that origin (Event.to()).
  • An actor delivers an event addressed beneath it to the right child. An event addressed to something that is neither itself nor beneath it is a ValueError.

Event.addressed(to) returns a new event with that address, keeping the name, payload and principal.

Deeper: writing your own actor

The reference agent and Workflow are two of the actors gvn ships; errands, conversations, inquiries, approvals, timers and choices implement the same interface. Most harnesses are built by composing ready-made actors in workflows. You can implement Actor directly when you need a different control machine: own a Machine, keep your data in durable objects, validate payloads in handle, and derive pending() from the current state's output. The source of gvn.harness.agent is a complete, commented example of the pattern.

Recap

  • An Event carries an input name, payload, optional address and optional principal. A Request carries an output, its payload and a deterministic id whose prefix is the origin.
  • An actor owns a machine and its data, turns events into requests, and never does I/O.
  • Internal outputs are resolved inside handle; external ones become requests.
  • reaction.requests() == actor.pending() after every call, and a rejected or failing event changes nothing.

Next: Tools, the work an actor asks for and the runtime runs; then the reference agent, the built-in agent you just drove, in full.