Browse documentation
Guides
View Markdown
On this page

Different kinds of child in one stage

This guide runs three different kinds of work side by side in one step of a workflow: an agent that writes, a tool call fixed in code, and a question to a person. At the end you have a workflow that starts all three together, waits for the person without holding a process, and moves on by one rule over the three results.

Where this fits

In the big picture, the actor is the verified state machine the Governor drives. A workflow is an actor whose working states each run a stage: a recipe for which child actors to start there, and a join, the rule that turns the children's endings into one input for the workflow's machine. This guide adds the stage whose children are of different kinds:

flowchart LR
    workflow["<b>Workflow</b><br/>state preparing"]
    stage["<b>Parallel stage</b><br/>a fixed list of branches"]
    agent["Agent<br/>writes the apology"]
    errand["Errand<br/>books the courier"]
    inquiry["Inquiry<br/>asks the warehouse"]
    person(["A person"])
    join["<b>join</b><br/>over the verdicts"]
    workflow --> stage
    stage --> agent
    stage --> errand
    stage --> inquiry
    inquiry -. "question" .-> person
    agent -- "verdict" --> join
    errand -- "verdict" --> join
    inquiry -- "verdict" --> join
    join -- "prepared or not_prepared" --> workflow

Each child reaches the same Governor and fulfillers as any actor: the agent asks the model fulfiller, the errand the policy and tool fulfillers, and the inquiry's question goes to a person, the box at the edge of the big picture.

The problem

A customer's order arrived broken, and the shop will send a replacement. Three things can happen at once:

  • an agent writes the apology (a model is good at that);
  • an errand books the courier to collect the broken parcel (a tool call fixed by code, without a model);
  • an inquiry asks the warehouse whether a replacement is in stock (a ready-made actor that puts a question to a person and waits for the answer).

A FanOut (the stage from Workflows that starts several children at once) runs children all of one class. Running these three one after another would make the customer wait for the slowest person in the chain three times over.

Parallel is the stage for this: a fixed list of branches, each with its own kind of child, all started together. Each branch turns its child's ending into a verdict, a name from a small set you choose (here ready or not_ready), and one join decides on the verdicts, whatever kind of child gave them.

Step 1: the tools and the policy

The courier is one tool, built once as book_pickup: the errand names it, the plan declares it and the runtime's toolbox holds it, always as this object (Tools). The policy clears everything, as in the tutorials:

import asyncio
import typing

from gvn.harness.events import Event
from gvn.harness.tools import VERDICTS, Invocation, Tool, Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol


class BookPickup(Tool):
    def name(self) -> str:
        return "book_pickup"

    def description(self) -> str:
        return "Book the courier to collect a parcel."

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

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        return {"pickup": f"PU-{arguments['order_id']}"}


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

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


book_pickup = BookPickup()

Step 2: three branches

A Branch is one child: its class, how to make and start it, and how its ending becomes a verdict. There are two ways to say that:

  • verdicts: a mapping from each final state of the child's machine to a verdict, when how the child ended is enough;
  • classify: a Decision over the child's outcome, when you must look at what it said.

The agent and the errand use verdicts:

from gvn.harness.agent import Agent
from gvn.harness.errand import Errand
from gvn.harness.tools import FixedCall
from gvn.harness.workflow import Branch

apology = Branch(
    actor_class=Agent,
    make=lambda name, memo: Agent(name=name, instructions="Write a short apology."),
    start=lambda memo: Event("started", payload={"prompt": f"Order {memo.input()['order_id']}."}),
    verdicts={"completed": "ready", "failed": "not_ready", "overflowed": "not_ready"},
)

pickup = Branch(
    actor_class=Errand,
    make=lambda name, memo: Errand(
        name=name,
        calls=[
            FixedCall(
                call_id="pickup",
                tool=book_pickup,
                arguments={"order_id": memo.input()["order_id"]},
            )
        ],
    ),
    start=lambda memo: Event("started"),
    verdicts={
        "done": "ready",
        "failed": "not_ready",
        "refused": "not_ready",
        "declined": "not_ready",
    },
)

An Errand can end in four states, and verdicts must name every one: the plan cannot meet an ending it did not expect.

The warehouse's answer is a choice, and in gvn a branch on data is chosen by a Decision, whose possible answers are declared and checked, so classify is used here. An Inquiry that ends answered with the choice in_stock is ready; anything else is not:

from gvn.harness.inquiry import Inquiry


class InStock(Decision):
    def outcomes(self) -> Alphabet:
        return Alphabet.of("ready", "not_ready")

    def judge(self, outcome: object) -> Symbol:
        answered = outcome.state().name() == "answered"
        in_stock = answered and outcome.payload()["choice"] == "in_stock"
        return Symbol("ready" if in_stock else "not_ready")


stock = Branch(
    actor_class=Inquiry,
    make=lambda name, memo: Inquiry(
        name=name, audience="warehouse", choices=("in_stock", "out_of_stock")
    ),
    start=lambda memo: Event(
        "started", payload={"question": f"Is {memo.input()['order_id']} in stock?"}
    ),
    classify=InStock(),
)

Step 3: the stage and the workflow

The Parallel stage joins the verdicts with an ordinary join. AllOf waits for every branch and answers reached only when all three are ready. The workflow's machine routes the two answers, and a Plan puts machine and stage together, as in Workflows. Its tools declares every tool a child calls, here the courier, so the runtime can check its toolbox before the run starts (Tools):

from gvn.harness.workflow import AllOf, Parallel, Plan, Workflow
from gvn.kernel.blueprint import MooreBlueprint

preparing = Parallel(
    branches=[apology, pickup, stock],
    join=AllOf(success="ready", reached="prepared", missed="not_prepared"),
)

REPLACEMENT_MACHINE = (
    MooreBlueprint(name="replacement")
    .inputs("started", "prepared", "not_prepared")
    .outputs("idle", "prepare", "replaced", "escalated")
    .state(name="idle", output="idle")
    .state(name="preparing", output="prepare")
    .state(name="replaced", output="replaced", final=True)
    .state(name="escalated", output="escalated", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="preparing")
    .branch(
        source="preparing",
        outcomes=Alphabet.of("prepared", "not_prepared"),
        routes={"prepared": "replaced", "not_prepared": "escalated"},
    )
    .otherwise_stay()
    .build()
)

REPLACEMENT = Plan(
    definition=REPLACEMENT_MACHINE, stages={"preparing": preparing}, tools=[book_pickup]
)


class Replacement(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return REPLACEMENT

The join counts verdicts, so it must not classify anything itself: AllOf(..., classify=...) in a Parallel is refused when the plan is built, with a message that says to give each branch its own classify. The other joins (Workflows in depth describes them) are checked too: a Worst join must rank every verdict some branch can give, and a Quorum's veto verdicts must be ones a branch can give.

Step 4: run it until the warehouse is asked

The model writes the apology, the courier is booked, and the run parks (stops, with its state saved, until an answer arrives) on the question to the warehouse. Two new pieces make that happen:

  • FunctionModel is a fake model whose reply is computed by a function of yours, here apologise, instead of read from a script.
  • external=["request_input"] tells the Governor that requests of that kind are answered from outside, by a person, so no fulfiller handles them: the call returns waiting with the question among its pending requests.
from gvn.harness.messages import Message
from gvn.harness.ports import Exchange, Reply
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput


def apologise(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text="We are sorry. A new one is on its way."))


toolbox = Toolbox(tools=[book_pickup])
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=FunctionModel(respond=apologise), toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
    },
    external=["request_input"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
case = Replacement(name="case-31")
waiting = asyncio.run(
    governor.deliver(actor=case, event=Event("started", payload={"order_id": "A-17"}))
)
(question,) = waiting.pending()
print(waiting.status(), question.origin(), question.kind().name())
waiting case-31/preparing.1.2 request_input

Children are named <workflow>/<stage>.<visit>.<index>, as in a FanOut: the index is the branch's place in the list. The agent and the errand have finished; the inquiry, branch 2, waits.

Step 5: the warehouse answers

governor.answer delivers the person's answer as the event that ends the pending request, addressed (to=) to the child that asked. Report then reads the finished workflow's outcome, stage by stage:

from gvn.harness.workflow import Report

answer = Event(
    "answered", payload={"text": "Two left.", "choice": "in_stock"}, to=question.origin()
)
finished = asyncio.run(governor.answer(actor=case, request=question, event=answer))
print(finished.outcome().state())
for child in Report(outcome=finished.outcome()).results("preparing"):
    print(child.index(), child.name(), child.state().name())
State('replaced')
0 case-31/preparing.1.0 completed
1 case-31/preparing.1.1 done
2 case-31/preparing.1.2 answered

The join decided on three ready verdicts; the results keep each child's real outcome (the agent's text, the errand's attempts, the inquiry's answer) for the stages that follow.

What else to know

  • Parallel takes deadline= and expired= like the other stages: at the deadline every branch still running is cut, whatever its kind, and recorded as abandoned.
  • The stored form (the saved data a run is revived from; see Durable objects) holds each running child's own stored form; reviving a run rebuilds each child with its branch's class.
  • The branches are fixed by the plan. When the kinds of child depend on data, see Different kinds at once.

Recap

  • Parallel runs a fixed list of Branches at once, each with its own kind of child.
  • Each branch turns its child's ending into a verdict, through verdicts or classify.
  • An ordinary join (AllOf, AnyOf, Quorum, Worst) decides on the verdicts.

Next: to undo what one branch did when another fails, read Undo that the verifier checks; to keep a run that waits on a person in a shared journal and answer it from a web handler, read Running as a service.