# 8. A workflow of two actors

**At the end you can:** split a job into stages that each run their own agent, in an order
fixed by code, hand one stage's result to the next, and answer an approval that a stage's
agent asks for.

**What you will learn:** how to compose actors into a **workflow**: a machine of your own
whose states are **stages**, each running a child actor, with the verifier checking that every
way a stage can end is routed.

**Before this:** [7. Streaming, and seeing what happened](streaming.md). You use the look-up
tool from [tutorial 4](adding-a-tool.md) again.

**Time:** about 15 minutes.

## Where this sits in the big picture

In the quickstart's [big picture](../quickstart.md#the-big-picture) there is one **actor**
in a run. So far it was always an agent. A workflow is a different kind of actor: one whose
own state machine runs other actors as its steps. The Governor, fulfillers and journal do
not change at all; only the actor box grows an inside. Step 1 draws that inside.

## Where you are

The help desk agent so far did everything in one conversation: look the order up, decide,
answer. Real support work often splits into steps with different instructions: one agent
investigates and states the facts, another writes the reply to the customer in the shop's
tone. You want the order of those steps to be fixed by code, not left to a model, and you
want to know for certain what happens when a step fails.

### One agent, or a workflow?

One agent is enough when the job is one question: one set of instructions, one set of
tools, and the model may choose the order of its tool calls. Most of the help desk so far
was that.

A workflow earns its place when one of these is true of your job:

- **The parts need different instructions or different tools.** The investigator may look
  orders up; the writer may not.
- **The order must be fixed by code.** The reply is written after the facts are found,
  every time, whatever the model would prefer.
- **Each way a part can end needs its own route.** A failed investigation goes somewhere
  you chose, and the verifier holds you to every ending.
- **Parts run at the same time,** or one part needs a deadline of its own (tutorial 9).

A good stage owns a coherent job, has a meaningful input and result, and can be tested on
its own. If you cannot say what a stage is given and what it hands back, it is still part
of its neighbour.

**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: the look-up tool
and the permissive policy of tutorial 4. Then add each block of the page below it, in
order.

??? example "The look-up tool and policy from tutorial 4"

    ```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 Reply
    from gvn.harness.tools import Invocation, Tool, Toolbox
    from gvn.kernel.decision import Decision
    from gvn.kernel.schema import Record, Text
    from gvn.kernel.symbols import Alphabet, Symbol
    from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
    from gvn.runtime.governor import Governor
    from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


    class OrderBook:
        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])


    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"])


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

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


    order_book = OrderBook(orders={"A-17": {"status": "shipped", "total": 40.0}})
    look_up_order = LookUpOrder(order_book=order_book)
    toolbox = Toolbox([look_up_order])
    ```

## Step 1: the workflow's own machine

A workflow is an actor whose machine you write, exactly as you wrote the ticket in tutorials 1
and 2. Each **stage** is a state of it. The ways a stage can end are input symbols, routed
with `branch` so that the verifier holds you to all of them.

There are three separate descriptions to keep straight:

| Description | What it answers |
|---|---|
| The machine | When investigation succeeds or fails, which stage comes next? |
| A stage (`Host`) | Which actor performs this part of the job, what starts it, and how does its ending become a parent input? |
| The plan (`Plan`) | Which stage implementation belongs to each machine state, and which tools may the children use? |

The workflow owns its active children. The Governor still sees one actor and drives it
through the same interface as the single agent you already ran:

```mermaid
flowchart TD
    G["Governor"] -->|"Actor interface"| W["SupportCase workflow"]
    W --> M["Case machine: investigate, then reply"]
    W -->|"during investigating"| I["Investigator Agent"]
    W -->|"during replying"| R["Writer Agent"]
    I -->|"completed / failed"| W
    R -->|"completed / failed"| W
```

The investigator and writer are active at different times. Their internal thinking/tool
states stay inside each child. The parent routes the child's final state and supplies the
next child's opening data.

```python
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.symbols import Alphabet

CASE_MACHINE = (
    MooreBlueprint(name="case")
    .inputs("started", "investigated", "investigation_failed", "replied", "reply_failed")
    .outputs("idle", "investigate", "reply", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="investigating", output="investigate")
    .state(name="replying", output="reply")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="investigating")
    .branch(
        source="investigating",
        outcomes=Alphabet.of("investigated", "investigation_failed"),
        routes={"investigated": "replying", "investigation_failed": "failed"},
    )
    .branch(
        source="replying",
        outcomes=Alphabet.of("replied", "reply_failed"),
        routes={"replied": "done", "reply_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)
```

The machine knows nothing about agents. It only says that investigating ends in one of two
ways and where each leads. What happens *inside* each state is the next step.

## Step 2: a stage that hosts one agent

`Host` runs one child actor in a stage. You give it:

- `actor_class`: the class of the child, here `Agent`;
- `make(name, memo)`: a function that builds the child, with exactly the name it is given;
- `start(memo)`: a function that builds the child's opening event;
- `routes`: for each final state of the child, the workflow input it becomes.

Both functions receive the workflow's **memo**: a read-only view of its data.
`memo.input()` is the payload that started the workflow, and `memo.results(stage)` the
results of a stage that has finished.

```python
from gvn.harness.workflow import Host, Memo


def make_investigator(name: str, memo: Memo) -> Agent:
    return Agent(
        name=name,
        instructions="Find the facts about the customer's order. State them in one line.",
        tools=[look_up_order],
    )


def start_investigator(memo: Memo) -> Event:
    return Event(name="started", payload={"prompt": memo.input()["complaint"]})


investigating = Host(
    actor_class=Agent,
    make=make_investigator,
    start=start_investigator,
    routes={
        "completed": "investigated",
        "failed": "investigation_failed",
        "overflowed": "investigation_failed",
    },
)
```

`Host` checks `routes` when it is built: it must name exactly the final states of the child's
machine. An agent ends `completed`, `failed` or `overflowed` (it ran out of the room it may
use in its model's context window; [Context management](../concepts/context-management.md)
explains it), so all three are routed, and here running out of room counts as a failed
investigation. Leave one out and `Host` raises `ValueError` at once, long before any run.

The writer is a second agent, with no tools. Its opening event carries the complaint and the
investigator's findings, read from the memo:

```python
def make_writer(name: str, memo: Memo) -> Agent:
    return Agent(name=name, instructions="Write a short, kind reply to the customer.")


def start_writer(memo: Memo) -> Event:
    facts = memo.results("investigating")[0].payload()["text"]
    complaint = memo.input()["complaint"]
    return Event(name="started", payload={"prompt": f"Complaint: {complaint}\nFacts: {facts}"})


replying = Host(
    actor_class=Agent,
    make=make_writer,
    start=start_writer,
    routes={"completed": "replied", "failed": "reply_failed", "overflowed": "reply_failed"},
)
```

## Step 3: the plan and the workflow class

A `Plan` ties the machine to its stages, and checks them together: every stage must sit on a
state that is neither initial nor final, and every route must have a declared transition out
of its state. A workflow is a subclass of `Workflow` that returns its plan:

`definition` is the checked control machine. `stages` maps its state names to the `Host`
objects you just built; it does not map child state names. `tools` lists every tool any
child may be offered or call: here the investigator's look-up. The children are built only
while the workflow runs, so the Governor cannot look at them beforehand; it checks the
plan's tools instead, before the run starts, against its toolbox, the way it checked the
single agent's tools in tutorial 4. Building a child that is given a tool the plan does not
list is a `ValueError`. [Tools](../concepts/tools.md#what-a-workflow-declares) says more.
The subclass gives recovery a stable place to find that plan again, because Python functions
are code rather than saved run data.

```python
from gvn.harness.workflow import Plan, Workflow

CASE_PLAN = Plan(
    definition=CASE_MACHINE,
    stages={"investigating": investigating, "replying": replying},
    tools=[look_up_order],
)


class SupportCase(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return CASE_PLAN
```

The plan is code (classes and functions), so it is not saved with the run; the class is what
knows how to rebuild the children when a run is recovered.

A plan can also declare `settings=`, plain data saying what its functions were built from
(instructions, limits, model choices), so that a stored run is only continued by plans built
from the same data. [Workflows in depth](../concepts/workflows-in-depth.md#settings) shows it.

## Step 4: run it

A workflow is an actor, so the Governor runs it like the agent. One model serves both agents;
because the stages run one after the other, the script is simply in that order: the
investigator's tool call, its findings, then the writer's reply.

```python
def asks_for(
    short_name: str, arguments: dict[str, typing.Any], call_id: str = "call-1"
) -> Reply:
    call = ToolCall(call_id=call_id, name=short_name, arguments=arguments)
    return Reply(message=Message.assistant(calls=[call]))


model = ScriptedModel(
    script=[
        asks_for("look_up_order", {"order_id": "A-17"}),
        Reply(message=Message.assistant(text="A-17 has shipped; its total is 40.00.")),
        Reply(message=Message.assistant(text="Good news: your order A-17 is on its way.")),
    ]
)
journal = MemoryJournal()
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
    },
    journal=journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
case = SupportCase(name="case-1")
complaint = Event(name="started", payload={"complaint": "Where is my order A-17?"})
result = asyncio.run(governor.deliver(actor=case, event=complaint))
print(result.status(), result.outcome().state())  # finished State('done')
```

## Step 5: read the outcome

A workflow's outcome holds every stage's results. `Report` reads it:

```python
from gvn.harness.workflow import Report

report = Report(result.outcome())
print(report.stages())  # ('investigating', 'replying')
print(report.results("replying")[0].payload()["text"])
# Good news: your order A-17 is on its way.
print(model.exchanges()[2].messages()[0].text())
# Complaint: Where is my order A-17?
# Facts: A-17 has shipped; its total is 40.00.
```

The last line is what the writer was asked: `start_writer` passed the investigator's findings
on.

## Step 6: one run, one journal

The children are not separate runs. They live inside the workflow, which is one actor with
one journal and one saved state. Each event says which child it was for:

```python
for record in asyncio.run(journal.read("case-1")):
    print(record["event"]["name"], record["event"]["to"])
```

```text
started None
model_replied case-1/investigating.1
cleared case-1/investigating.1
tools_returned case-1/investigating.1
model_replied case-1/investigating.1
model_replied case-1/replying.1
```

Children are named after the workflow, the stage and the visit: `case-1/investigating.1` is
the first visit of the investigating stage. So everything from tutorial 6 still holds:
`Recovery` rebuilds the whole tree from this journal, and a waiting workflow costs nothing.

## Step 7: a stage's agent asks a person

A child agent inside a workflow asks for approval exactly as the single agent of
[tutorial 5](agent-with-approval.md) did. Three things carry over:

- the request kind is declared external **on the Governor**, with
  `external=["request_approval"]`: the workflow needs no change;
- `deliver` on the workflow returns a waiting result whose pending request belongs to the
  child;
- you answer that request **on the workflow**, and the Governor routes the answer to the
  child that asked.

To see it, run the same `SupportCase` under a policy that sends every call to a person:

```python
class AskFirst(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

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


careful_model = ScriptedModel(
    script=[
        asks_for("look_up_order", {"order_id": "A-17"}),
        Reply(message=Message.assistant(text="A-17 has shipped; its total is 40.00.")),
        Reply(message=Message.assistant(text="Good news: your order A-17 is on its way.")),
    ]
)
careful = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=careful_model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=AskFirst()),
    },
    external=["request_approval"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
asking_case = SupportCase(name="case-2")
waiting = asyncio.run(careful.deliver(actor=asking_case, event=complaint))
request = waiting.pending()[0]
print(waiting.status(), asking_case.state())  # waiting State('investigating')
print(request.request_id(), request.kind().name())
# case-2/investigating.1/6 request_approval
print(request.payload()["calls"][0]["name"])  # look_up_order

result = asyncio.run(
    careful.answer(actor=asking_case, request=request, event=Event(name="approved"))
)
print(result.status(), result.outcome().state())  # finished State('done')
```

The workflow stood in `investigating` while its child waited. The request id starts with
the child's name, `case-2/investigating.1`, and that is how the answer finds it. Without
`external=["request_approval"]` the Governor has nobody to send the request to, and
`deliver` raises `Unfulfillable`, naming the kind and the child that asked.

## Step 8: hand a structured answer to the next stage

`start_writer` read the investigator's findings as text. When the next stage needs
**fields**, give the child an answer schema with `answer=`: the agent then ends
`completed` only with data that fits the schema, and `failed` otherwise. The checked data
is in the child's result under `"answer"`, beside `"text"`:

```python
from gvn.kernel.schema import Number
from gvn.testing.fakes import answer_reply

FACTS = Record({"status": Text(), "total": Number()})


def make_fact_finder(name: str, memo: Memo) -> Agent:
    return Agent(
        name=name,
        instructions="Find the order's status and total.",
        tools=[look_up_order],
        answer=FACTS,
    )


def start_writer_from_facts(memo: Memo) -> Event:
    facts = memo.results("investigating")[0].payload()["answer"]
    prompt = f"The order has {facts['status']}; its total is {facts['total']:.2f}."
    return Event(name="started", payload={"prompt": prompt})


agent_routes = {
    "completed": "investigated",
    "failed": "investigation_failed",
    "overflowed": "investigation_failed",
}
FACT_PLAN = Plan(
    definition=CASE_MACHINE,
    stages={
        "investigating": Host(
            actor_class=Agent, make=make_fact_finder, start=start_investigator, routes=agent_routes
        ),
        "replying": Host(
            actor_class=Agent,
            make=make_writer,
            start=start_writer_from_facts,
            routes={"completed": "replied", "failed": "reply_failed", "overflowed": "reply_failed"},
        ),
    },
    tools=[look_up_order],
)


class FactCase(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return FACT_PLAN


fact_model = ScriptedModel(
    script=[
        asks_for("look_up_order", {"order_id": "A-17"}),
        answer_reply(data={"status": "shipped", "total": 40.0}),
        Reply(message=Message.assistant(text="Good news: your order A-17 is on its way.")),
    ]
)
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=fact_model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(governor.deliver(actor=FactCase(name="case-3"), event=complaint))
print(Report(result.outcome()).results("investigating")[0].payload()["answer"])
# {'status': 'shipped', 'total': 40.0}
print(fact_model.exchanges()[2].messages()[0].text())
# The order has shipped; its total is 40.00.
```

`answer_reply` is the fake model's way of replying with data, as a vendor's structured
output does. The writer's prompt was built from two checked fields, with no parsing of
prose. A reply that does not fit the schema ends the investigator `failed`, which this
workflow already routes to `investigation_failed`.
[Structured answers](../guides/structured-answers.md) covers the schema classes, what the
model is sent, and a real vendor.

## Change it and run again

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

**1. Forget one ending.** Build the writer's stage without a route for `overflowed`. Does
anything fail, and when: now, when the plan is built, or during a run?

```python
try:
    Host(
        actor_class=Agent,
        make=make_writer,
        start=start_writer,
        routes={"completed": "replied", "failed": "reply_failed"},
    )
except ValueError as error:
    print("ValueError:", error)
```

??? note "What happens"

    ```text
    ValueError: routes must name exactly the final states of Agent ['completed', 'failed', 'overflowed']; missing ['overflowed'], extra []
    ```

    It fails at once, when the `Host` is built. No plan, Governor or run is needed to find
    an ending you did not route.

**2. Leave the tool out of the plan.** Build the plan of step 3 without `tools=`, and run
a case on it. The investigator is still given the look-up tool. Which line fails: the
`Plan(...)`, or the run?

```python
bare_plan = Plan(
    definition=CASE_MACHINE,
    stages={"investigating": investigating, "replying": replying},
)
print("plan built")


class BareCase(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return bare_plan


try:
    asyncio.run(governor.deliver(actor=BareCase(name="case-4"), event=complaint))
except ValueError as error:
    print("ValueError:", error)
```

??? note "What happens"

    ```text
    plan built
    ValueError: workflow 'case-4', stage 'investigating': child 'case-4/investigating.1' names tools ['__main__.look_up_order'] that plan 'case' does not declare (Plan(tools=...) declares [])
    ```

    The plan is built: it cannot know what tools `make_investigator` will hand out, because
    children are built only while the workflow runs. The run fails when the stage builds
    its child, before the child does any work. The message names the tool by its
    [identity](../concepts/tools.md#two-names-the-short-name-and-the-identity), which
    starts with the module that defines it: `__main__` for a file you run directly.

## Recap

- A **workflow** is an actor whose machine you write; each **stage** is a state that hosts
  children.
- `Host(actor_class=..., make=..., start=..., routes=...)` runs one child; `routes` must cover
  every final state of the child's class.
- The **memo** gives stage functions the starting input and earlier stages' results.
- A `Plan` is checked as a whole, and declares with `tools=` every tool its children use; the
  `Workflow` subclass supplies it.
- The whole tree is one actor with one journal.
- A child's approval is declared external on the Governor and answered on the workflow;
  the request id names the child.
- A child built with `answer=` hands the next stage checked fields under `"answer"`.

Workflows can do much more: run several children at once with a `FanOut`, route on what a
child did (not just how it ended) with a `judge`, loop back to an earlier stage, and run a
workflow inside another as a child. [Workflows](../concepts/workflows.md) explains each.

**Next:** [9. A deadline](deadline.md) gives the investigating stage a day to finish, and
says what happens when it does not.
