# Streaming and observability

**What you will learn:** how you watch a run while it happens: show a model's text as it
arrives, write logs, record traces, and check in a test what happened. All of these go
through one small interface, and you will write your own in a few lines.

**Read first:** [The Governor](governor.md) and [The reference agent](reference-agent.md).
**Time:** about 15 minutes.

## Where outputs sit

In the [loop that runs](index.md#picture-1-the-loop-that-runs), everything passes through
the Governor. This page is about one more thing the Governor does as it goes: it reports each
step to the **output**, one of the four parts you gave it on [the Governor's
page](governor.md#four-things-the-governor-needs). The output only watches. It cannot change
the run, and an output that fails cannot break it. In the
[layers of code](index.md#picture-2-the-layers-of-code), the `Output` interface is in the
harness, the stream and fan-out outputs are in the runtime, and logs and traces are adapters.

```mermaid
flowchart LR
    governor["Governor"] -- "a signal per step" --> output["Output"]
    output --> screen["text on a screen"]
    output --> logs["structured logs"]
    output --> traces["traces"]
    output --> test["a test's assertions"]
```

## The problem: many watchers, one run

Once an agent runs, different people want to see different things. The user wants the
model's answer to appear word by word. An operator wants structured logs. A platform team
wants OpenTelemetry traces (OpenTelemetry is a standard format for recording timed pieces of
work, called *spans*, across services). A test wants to assert on what happened. If each of these were
wired into the harness separately, the harness would grow a hook for every one.

gvn has one port instead. A **port** is an interface the framework calls and you implement
(or pick a ready-made implementation of). Everything observable about a run goes through the
`Output` port, in `gvn.harness.ports`. The Governor sends it a `Signal` for every transition,
every request it starts, every text fragment a model produces, and every time a call ends. A
user-facing stream, structured logs and OpenTelemetry tracing are three implementations of
that one port. The harness knows only the port.

## Step 1: a run to watch

To have something to watch, here is a small helper that runs the reference agent once
against a `ScriptedModel`, a fake model that replies from a script instead of calling a
vendor. The script says: stream these text fragments, then reply with this message. The
helper takes the `Output` to send signals to:

```python
import asyncio

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


def run_explainer(
    output: Output, fragments: tuple[str, ...] = ("Mo", "ore ", "machines.")
) -> Result:
    reply = Reply(message=Message.assistant(text="".join(fragments)))
    model = ScriptedModel(script=[(list(fragments), reply)])
    governor = Governor(
        fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
        journal=MemoryJournal(),
        output=output,
        clock=ManualClock(),
    )
    explainer = Agent(name="explainer", instructions="Answer in three words.")
    started = Event("started", payload={"prompt": "What?"})
    return asyncio.run(governor.deliver(actor=explainer, event=started))
```

Nothing has run yet. The only new idea is the `output=` argument: whatever you pass there
sees every signal of the run.

## Step 2: record the signals

The simplest output is **`RecordingOutput`** (`gvn.testing.fakes`). It keeps every signal, for
tests: `signals()`, `kinds()` and `text()` (all delta text, concatenated).

```python
from gvn.testing.fakes import RecordingOutput

recorded = RecordingOutput()
run_explainer(output=recorded)
print(recorded.kinds())
print(recorded.text())
```

```text
('event', 'request', 'delta', 'delta', 'delta', 'event', 'finished')
Moore machines.
```

Read the kinds in order: the agent handled its `started` **event**; the Governor started a
**request** (the model call); the model streamed three text fragments, each a **delta**; the
agent handled the model's reply (another **event**); and the agent **finished**.

## Step 3: what a signal carries

Each item in `signals()` is a `Signal` with five parts:

- `kind()`: one of the six kinds in the table below.
- `actor()`: the name of the actor it concerns.
- `sequence()`: a counter per Governor, from 0, so you can order signals and detect gaps.
- `at()`: the Clock's time.
- `data()`: plain JSON, shaped by the kind.

```python
request_signal = recorded.signals()[1]
print(request_signal.kind(), request_signal.actor(), request_signal.sequence())
print(request_signal.data())
```

```text
request explainer 1
{'request_id': 'explainer/3', 'kind': 'invoke_model'}
```

| Kind | When | `data()` |
|---|---|---|
| `event` | the actor handled an event | `{"event": name, "to": address or None, "steps": [{"source", "symbol", "target", "output"}, ...]}`, plus `"usage": {"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"}` for a `model_replied` or `model_failed` that carries usage ([what the figures mean](../guides/vendors.md#what-a-call-cost-usage)), `"retries"` for either when the model call was retried, `"model"` and `"provider"` for either when the answer names them, `"by": {"subject", "issuer"}` when the event says who it came from ([Trust](trust.md)), and `"citations"` for a `model_replied` whose message has citations |
| `rejected` | the event was not expected in that state | `{"event": name, "state": name}` |
| `request` | the Governor started some work | `{"request_id": str, "kind": name}`, plus `"tools": [{"call_id", "name", "identity"}, ...]`, one per call that will run, for `invoke_tools` |
| `delta` | work in flight reported progress | `{"request": id, "text": str}` |
| `waiting` | the call ended with the actor waiting | `{"state": name, "pending": [kind names of external requests], "requests": [<Request.Dto plain> of each external request], "due": earliest time of a parked wake-up, or None}` |
| `finished` | the actor reached a final state | `{"state": name, "payload": ...}` |

Under an [allowance](../guides/spending-and-rate-limits.md), `waiting` and `finished` also
carry `"spent"` (the tokens and calls so far, and `"cost"` when the allowance has rates) and,
when it was exceeded, `"overspent"`.

In the `waiting` row, a *parked wake-up* is a time the run asked to be woken at while no
process waits for it ([Time](time.md), later, explains it).

`event` and `rejected` signals correspond to journal records, which are durable. `delta`
signals are ephemeral: they are never journaled, and a recovered run does not replay them.

## Step 4: write your own output

`Output` has one method, `emit(signal)`. It is synchronous, and it must return promptly
without blocking on I/O. If it raises, the Governor swallows and counts the exception
(`governor.output_errors()`): an observer can never break a run.

Here is a minimal output that prints the model's text as it streams, and a newline when the
agent finishes:

```python
class Printer(Output):
    def emit(self, signal: Signal) -> None:
        if signal.kind() == "delta":
            print(signal.data()["text"], end="")
        elif signal.kind() == "finished":
            print()


run_explainer(output=Printer())
```

```text
Moore machines.
```

The three fragments arrived as three `delta` signals and were printed one after another.

## Step 5: stream to a consumer

A printer works inside the Governor's own loop. A web handler or a UI usually wants to *pull*
signals instead, with `async for`. **`StreamOutput`** (`gvn.runtime.outputs`) is that: an
output you iterate while the run is in flight. `emit` adds to an unbounded buffer without
blocking, so consume signals while the run is active. Iteration ends after `close()` once the
buffer is drained. Create and consume it on one event loop.

Below, one task drives the run and closes the stream when it is done, while the caller
iterates:

```python
from gvn.runtime.outputs import StreamOutput


async def stream_one() -> list[str]:
    stream = StreamOutput()

    async def drive() -> None:
        try:
            reply = Reply(message=Message.assistant(text="Hello."))
            model = ScriptedModel(script=[(["Hel", "lo."], reply)])
            governor = Governor(
                fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
                journal=MemoryJournal(),
                output=stream,
                clock=ManualClock(),
            )
            greeter = Agent(name="greeter", instructions="Be brief.")
            await governor.deliver(actor=greeter, event=Event("started", payload={"prompt": "Hi"}))
        finally:
            stream.close()

    driving = asyncio.create_task(drive())
    kinds = [signal.kind() async for signal in stream]
    await driving
    return kinds


print(asyncio.run(stream_one()))
```

```text
['event', 'request', 'delta', 'delta', 'event', 'finished']
```

The `finally` matters: without `close()`, the `async for` would wait forever for more
signals.

That is the 80% you need. The rest of this page lists the other ready-made outputs and how
signals are addressed inside a workflow.

## Deeper: ready-made outputs

Three more ship with gvn, and [Logs, traces and streams](../guides/observability.md) shows
each one wired up:

- **`Fanout`** (`gvn.runtime.outputs`) sends every signal to several outputs in order. If
  one raises, the others still receive the signal.
- **`LoggingOutput`** (`gvn.adapters.logs`) writes one structured record per signal through
  the standard `logging` module, and `JsonFormatter` renders records as JSON lines. No extra
  needed.
- **`TracingOutput`** (`gvn.adapters.otel`, the `otel` extra: an optional install that adds
  the OpenTelemetry library) turns signals into
  OpenTelemetry spans named by the OpenTelemetry GenAI conventions: an `invoke_agent` span
  per driven stretch of an actor, a `chat` span per model call, and a `gvn.request` span for
  each other request, with an `execute_tool` span for each tool call. Payload contents are
  never recorded.

## Deeper: addresses in signals

Every signal names its actor. In a [workflow](workflows.md) (an actor that runs other actors
as stages, taught later in [Workflows](workflows.md)), the actor is the workflow itself, and the `event`
signal's `to` field names the child the event was for, such as `report/researching.1.0`.
Children's request ids begin with the child's name, so a consumer can tell which child is
streaming which text.

## Recap

- Everything observable goes through one port, `Output`, with one synchronous method,
  `emit(signal)`. An output that raises cannot break a run; the Governor counts it.
- A `Signal` has a kind, an actor, a sequence number, a time and JSON data.
- `delta` signals carry streamed text and are never journaled; `event` and `rejected`
  signals match durable journal records.
- `RecordingOutput` is for tests, `StreamOutput` for `async for` consumers, `Fanout`,
  `LoggingOutput` and `TracingOutput` for production.

**Next:** [Humans and interruption](human-in-the-loop.md), how a run waits for a person and
how it is stopped.
