# 7. Streaming, and seeing what happened

**At the end you can:** show a run while it happens, in a view you wrote yourself, and read
it back from the journal afterwards.

**What you will learn:** how to watch a run while it happens, through the **signals** the
Governor sends to an **output**; how to write your own output, send signals to several
outputs at once, and stream them to a user interface; and where to read a run back
afterwards.

**Before this:** [6. The journal: crash and resume](durability.md).

**Time:** about 10 minutes.

## Where this sits in the big picture

The quickstart's [big picture](../quickstart.md#the-big-picture) left out one box: the
**output**, the place where the Governor reports what a run is doing while it happens. The
journal (tutorial 6) is the durable record you read afterwards; the output is the live view.
Both are fed by the same Governor:

```mermaid
flowchart LR
    governor["<b>Governor</b>"]
    journal[("<b>Journal</b><br/>events, kept")]
    output["<b>Output</b><br/>signals, live"]
    views["a printer · a chat window<br/>· logs · traces"]
    governor -- "records" --> journal
    governor -- "reports" --> output
    output --> views
```

The page starts with what reaches the output, then writes outputs of your own, and ends by
reading the journal back.

## Where you are

So far you have looked at a run after it ended: its outcome, its transcript, its journal. A
person waiting on the help desk wants to see the answer as the model writes it, and you want
to see what the agent is doing while it does it. This page reuses the refund agent of
tutorials 5 and 6, in memory again, with a model that streams its final answer in fragments.

**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 6 or are starting here. Then add each
block of the page below it, in order.

??? example "The refund agent from tutorials 5 and 6"

    ```python
    import asyncio
    import typing

    from gvn.harness.agent import VERDICTS, Agent
    from gvn.harness.events import Event
    from gvn.harness.messages import Message, ToolCall
    from gvn.harness.ports import Output, Reply
    from gvn.harness.tools import Invocation, Tool, Toolbox
    from gvn.kernel.decision import Decision
    from gvn.kernel.schema import Number, Record, Text
    from gvn.kernel.symbols import Alphabet, Symbol
    from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
    from gvn.runtime.governor import Governor, Result
    from gvn.testing.fakes import ManualClock, MemoryJournal, ScriptedModel


    class IssueRefund(Tool):
        """Refunds into a list, in memory: enough for this page."""

        def __init__(self, refunds: list[dict[str, typing.Any]]) -> None:
            self._refunds = refunds

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

        def description(self) -> str:
            return "Refund an amount on an order. Money leaves the shop."

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

        async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
            self._refunds.append(dict(arguments))
            return {"refund": len(self._refunds)}


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

        def judge(self, consultation: object) -> Symbol:
            if consultation.calls_to(issue_refund):
                return VERDICTS.named("needs_approval")
            return VERDICTS.named("cleared")


    issue_refund = IssueRefund(refunds=[])
    toolbox = Toolbox([issue_refund])
    BROKEN = Event(name="started", payload={"prompt": "Order A-17 arrived broken. Refund me."})


    def refund_script() -> ScriptedModel:
        refund = ToolCall(
            call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": 40.0}
        )
        done = "I refunded 40.00 on order A-17."
        return ScriptedModel(
            script=[
                Reply(message=Message.assistant(calls=[refund])),
                (["I refunded ", "40.00 on ", "order A-17."], Reply(message=Message.assistant(text=done))),
            ]
        )
    ```

## Step 1: one port for everything you can observe

Every Governor has exactly one `output`. Whatever happens during a run reaches it as a
**signal**: a small record with a `kind()`, the name of the `actor()` it concerns, and some
`data()`. `build_governor` takes the output as a parameter, so each step below can pass a
different one:

```python
def build_governor(output: Output) -> Governor:
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=refund_script(), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=RefundPolicy()),
        },
        external=["request_approval"],
        journal=MemoryJournal(),
        output=output,
        clock=ManualClock(),
    )
```

There are six kinds of signal:

| Kind | Sent when |
|---|---|
| `event` | the actor handled an event (and which states it moved through) |
| `rejected` | the actor did not expect that event in its current state |
| `request` | the Governor started some work |
| `delta` | work in flight produced a fragment of text |
| `waiting` | the call returned without finishing the actor or leaving work in flight |
| `finished` | the actor reached a final state |

`event` and `rejected` signals match journal records, which are durable. `delta` signals are
not journaled: they exist only while the run happens. The
[Streaming and observability](../concepts/streaming-and-observability.md) page lists the
data each kind carries.

## Step 2: write your own output

An output is a subclass of `Output` with one method, `emit(signal)`. Here is one that prints
a line a person can follow:

```python
from gvn.harness.ports import Output, Signal


class ProgressPrinter(Output):
    def emit(self, signal: Signal) -> None:
        data = signal.data()
        if signal.kind() == "request":
            print(f"[{signal.actor()}] working: {data['kind']}")
        elif signal.kind() == "delta":
            print(f"[{signal.actor()}] says: {data['text']!r}")
        elif signal.kind() == "waiting":
            print(f"[{signal.actor()}] waiting in {data['state']} for {data['pending']}")
        elif signal.kind() == "finished":
            print(f"[{signal.actor()}] finished: {data['state']}")


governor = build_governor(output=ProgressPrinter())
agent = Agent(name="refunds", instructions="Help customers.", tools=[issue_refund])


async def run_with_approval() -> None:
    waiting = await governor.deliver(actor=agent, event=BROKEN)
    print("-- a person approves --")
    await governor.answer(actor=agent, request=waiting.pending()[0], event=Event(name="approved"))


asyncio.run(run_with_approval())
```

```text
[refunds] working: invoke_model
[refunds] working: consult_policy
[refunds] waiting in awaiting_approval for ['request_approval']
-- a person approves --
[refunds] working: invoke_tools
[refunds] working: invoke_model
[refunds] says: 'I refunded '
[refunds] says: '40.00 on '
[refunds] says: 'order A-17.'
[refunds] finished: completed
```

`emit` runs synchronously, so return quickly and put I/O in a separate task. The Governor
counts ordinary exceptions from an output in `output_errors()` and carries on.

## Step 3: several outputs at once

You usually want more than one view: a stream for the user, a log for you. `Fanout`, in
`gvn.runtime.outputs`, sends every signal to several outputs in order. Here it feeds the
printer and a `RecordingOutput`, which keeps every signal so you can check it afterwards:

```python
from gvn.runtime.outputs import Fanout
from gvn.testing.fakes import RecordingOutput

recorder = RecordingOutput()
governor = build_governor(output=Fanout(outputs=[ProgressPrinter(), recorder]))
agent = Agent(name="refunds-2", instructions="Help customers.", tools=[issue_refund])
asyncio.run(governor.deliver(actor=agent, event=BROKEN))

print(recorder.kinds())
# ('event', 'request', 'event', 'request', 'event', 'waiting')
```

The printer printed the first three lines of step 2 again; the recorder kept the same
signals. If one output raises, the others still receive the signal.

## Step 4: a stream for a user interface

A chat window or a web response wants the signals as an asynchronous stream. `StreamOutput`
is an output you read with `async for`. You drive the run in one task and read the stream in
another; `close()` tells the reader nothing more will come.

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


async def answer_in_a_chat_window() -> Result:
    stream = StreamOutput()
    governor = build_governor(output=stream)
    agent = Agent(name="refunds-3", instructions="Help customers.", tools=[issue_refund])

    async def drive() -> Result:
        try:
            waiting = await governor.deliver(actor=agent, event=BROKEN)
            approval = Event(name="approved")
            return await governor.answer(actor=agent, request=waiting.pending()[0], event=approval)
        finally:
            stream.close()

    driving = asyncio.create_task(drive())
    shown = ""
    async for signal in stream:
        if signal.kind() == "delta":
            shown += signal.data()["text"]
            print(shown)
    return await driving


result = asyncio.run(answer_in_a_chat_window())
```

```text
I refunded 
I refunded 40.00 on 
I refunded 40.00 on order A-17.
```

Each time a fragment arrives, the "window" shows the text so far. In a real application,
`print` would be a write to a websocket or a server-sent event. Create and read a
`StreamOutput` on one event loop.

## Step 5: reading a run back afterwards

Signals are for the moment. For the record, read the journal, as in tutorial 6. Every record
has its position (`sequence`), the clock's time (`at`) and the event:

```python
async def journal_of_a_run() -> None:
    journal = MemoryJournal()
    governor = Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=refund_script(), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=RefundPolicy()),
        },
        external=["request_approval"],
        journal=journal,
        output=RecordingOutput(),
        clock=ManualClock(),
    )
    agent = Agent(name="refunds-4", instructions="Help customers.", tools=[issue_refund])
    waiting = await governor.deliver(actor=agent, event=BROKEN)
    await governor.answer(actor=agent, request=waiting.pending()[0], event=Event(name="approved"))
    for record in await journal.read("refunds-4"):
        print(record["sequence"], record["at"], record["event"]["name"])


asyncio.run(journal_of_a_run())
```

```text
0 0.0 started
1 0.0 model_replied
2 0.0 needs_approval
3 0.0 approved
4 0.0 tools_returned
5 0.0 model_replied
```

The time is always `0.0` because the `ManualClock` never moved. The journal is also what
gvn's replay tools read: [Replay and evaluation](../guides/replay-and-evaluation.md) turns a
recorded run into a trace (the run read back event by event, with what the agent did at each), and runs a changed agent against it.

For a deployment, two more outputs ship with gvn, in `gvn.adapters`:

```python {.no-run}
from gvn.adapters.logs import LoggingOutput
from gvn.adapters.otel import TracingOutput
```

`LoggingOutput` writes structured log records through Python's `logging`. `TracingOutput`
turns signals into OpenTelemetry spans (the timed records of the OpenTelemetry tracing
standard): one span for the run, a `chat` span for each model call and an `execute_tool`
span for each tool call, named as LLM trace viewers expect. Each is an `Output` like the ones
above, so it goes to the Governor directly or through a `Fanout`.
[Logs, traces and streams](../guides/observability.md) wires each one up.

## Change it and run again

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

**1. An output that breaks.** `Fragile` raises on every `delta`, as a chat window might when
the user closes it. It shares a `Fanout` with a recorder. Does the run finish? Does the
recorder still get the text?

```python
class Fragile(Output):
    def emit(self, signal: Signal) -> None:
        if signal.kind() == "delta":
            raise RuntimeError("the chat window closed")


recorder = RecordingOutput()
governor = build_governor(output=Fanout(outputs=[Fragile(), recorder]))
agent = Agent(name="refunds-5", instructions="Help customers.", tools=[issue_refund])


async def run_with_a_fragile_output() -> Result:
    waiting = await governor.deliver(actor=agent, event=BROKEN)
    return await governor.answer(
        actor=agent, request=waiting.pending()[0], event=Event(name="approved")
    )


result = asyncio.run(run_with_a_fragile_output())
print(result.status(), governor.output_errors())
print(recorder.text())
```

??? note "What happens"

    ```text
    finished 3
    I refunded 40.00 on order A-17.
    ```

    The run finished. The model streamed three fragments, `Fragile` raised three times, and
    the Governor counted each one in `output_errors()`. The recorder, next in the `Fanout`,
    received every signal.

**2. Print the events too.** `ProgressPrinter` ignores `event` signals. Add this branch to
its `emit`, and run step 2 again with an agent named `refunds-6`. Which lines appear before
the run waits?

```python {.no-run}
        elif signal.kind() == "event":
            print(f"[{signal.actor()}] event: {data['event']}")
```

??? note "What happens"

    ```text
    [refunds-6] event: started
    [refunds-6] working: invoke_model
    [refunds-6] event: model_replied
    [refunds-6] working: consult_policy
    [refunds-6] event: needs_approval
    [refunds-6] waiting in awaiting_approval for ['request_approval']
    ```

    Each `event` line is one record of the journal, seen live: the same three names step 5
    reads back as records 0 to 2.

## Recap

- Everything observable about a run reaches **one output** as **signals** of six kinds.
- An output is a class with one quick `emit(signal)`; an output that raises cannot break a
  run.
- `Fanout(outputs=[...])` feeds several outputs; `StreamOutput` is read with `async for`;
  `RecordingOutput` keeps everything for tests.
- `delta` signals are ephemeral; the journal is the durable record.

**Next:** [8. A workflow of two actors](workflow.md) splits the help desk's work between two
agents, run one after the other by a machine of your own.
