# Model-backed choices

This guide lets a model make a decision for your program: it picks one of a fixed set of
options, such as "refund or replace?". At the end you have a workflow that routes on the
model's pick, with a declared route for the case where the model picks something else.

- **You will be able to:** let a model pick one of a fixed set of options, route a workflow
  on that pick, decide about an image or a document, and know exactly what happens when the
  model picks something else.
- **Read first:** [Structured answers](structured-answers.md), whose mechanism this uses.
  [2. Decisions and branching](../tutorials/decisions-and-branching.md) and
  [8. A workflow of two actors](../tutorials/workflow.md) build a branch and a workflow
  step by step; this page names each part where it appears.
- **Time:** about 15 minutes.

## Why

This guide works on the **actor** box of the quickstart's
[big picture](../quickstart.md#the-big-picture). An
[**actor**](../reference/glossary.md#actor) is a
[state machine](../reference/glossary.md#state-machine) with a job, such as an agent; the
**Governor** drives it, handing the work it asks for to a **fulfiller** (here, the one that
calls the model) and feeding the result back as an **event**.

In gvn, a branch in a machine is chosen by a [**Decision**](../reference/glossary.md#decision):
an object that looks at data and answers with one **symbol** (a name, such as an input of a
machine) from a finite set it declares up front, so the
[verifier](../reference/glossary.md#verifier) can check that every answer has a route. Text
from a model never routes, because text is not a finite set.

Some decisions are still best made by a model: "refund or replace?", "is this photo of a
cracked lid?". With a vendor's structured output a model can be made to answer with one
member of an enum, so its answer *is* a member of a finite set. A **`Choice`** is the small
actor that does exactly that: it asks the model to pick one of its declared options, checks
the pick, records it in the journal with the reply, and ends `chosen` or `failed`. A
[workflow](../tutorials/workflow.md) (an actor whose states run other actors, its
**children**, in **stages**) then routes on the pick with **`Chosen`**, a Decision over the
same options.

## How the parts fit

```mermaid
flowchart LR
    subgraph workflow ["Workflow (a verified machine)"]
        deciding["stage <b>deciding</b><br/>a Host"]
        refunded["refunded"]
        replaced["replaced"]
        escalated["escalated"]
    end
    choice["<b>Choice</b><br/>a child actor"]
    model(["Model<br/>constrained to the options"])
    deciding -- "runs" --> choice
    choice -- "one call, with the options as an enum" --> model
    model -- "the pick" --> choice
    choice -- "outcome: chosen or failed" --> chosen{{"<b>Chosen</b><br/>the stage's judge"}}
    chosen -- "refund" --> refunded
    chosen -- "replace" --> replaced
    chosen -- "failed: undecided" --> escalated
```

The Choice is the only part here that talks to the model. It ends in `chosen` with one of
the declared options in its outcome, or in `failed` with a reason. `Chosen` turns the
option or failure into an input of the workflow's machine. The verifier checks that each
of those inputs has a route. Step 1 runs a Choice on its own. Step 2 puts it in a workflow.

## Step 1: a choice on its own

```python
from gvn.harness.choice import Choice

resolution = Choice(
    name="resolution",
    instructions="A customer reports a damaged item. Decide how to resolve it.",
    options=("refund", "replace"),
)
print(resolution.answer().to_json_schema()["properties"]["choice"])  # {'enum': ['refund', 'replace']}
```

The options must be valid symbol names (letters, digits, `_`, `.`, `-`, starting with a
letter), at least two, and no two may differ only in letter case, because a pick is checked
against the options exactly. The Choice's answer schema is
`{"choice": <one of the options>, "explanation": <text>}`; the explanation is one sentence
for people to read and is never routed on.

Run it with a scripted model, as any actor. `ScriptedModel` is a fake that replies from a
script, so the example runs offline, and `answer_reply` builds a reply whose text is the
given data as JSON. The Governor gets a `ModelFulfiller` for the Choice's `invoke_model`
requests, and in-memory test stand-ins for the journal (where every event is recorded), the
output (where live signals go) and the clock. `deliver` feeds the Choice its first event,
`started`, and drives it to its end:

```python
import asyncio

from gvn.harness.events import Event
from gvn.harness.ports import Reply
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, RecordingOutput, ScriptedModel, answer_reply

model = ScriptedModel(
    script=[answer_reply(data={"choice": "replace", "explanation": "The item is in stock."})]
)
governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
complaint = Event(name="started", payload={"prompt": "My kettle arrived with a cracked lid."})
result = asyncio.run(governor.deliver(actor=resolution, event=complaint))
print(result.outcome().state())  # State('chosen')
print(result.outcome().payload())  # {'choice': 'replace', 'explanation': 'The item is in stock.'}
print(model.exchanges()[0].instructions())
```

```text
State('chosen')
{'choice': 'replace', 'explanation': 'The item is in stock.'}
A customer reports a damaged item. Decide how to resolve it.

Choose exactly one of: refund, replace. Give a one-sentence explanation.
```

The Choice adds one sentence to your instructions naming the options; the schema sent with
the request is what actually holds the model to them. It offers the model no tools and
makes one model call. A pick is often a job for a smaller model than the rest of the harness
uses: `Choice(..., model_role="triage")` asks for the model your wiring gives that role
([A model per role](vendors.md#a-model-per-role)). Its machine is small:

| State | Output | Input → next state |
|-------|--------|--------------------|
| idle | idle | started → asking |
| asking | invoke_model | model_replied → checking; model_failed → failed |
| checking | check_choice (internal decision) | chosen → chosen; unchosen → failed |
| suspended | suspended | resumed → asking |
| chosen, failed | final | — |

`interrupted` while asking leads to suspended, and resuming asks again under the same
request id (see [Humans and interruption](../concepts/human-in-the-loop.md) for how a run is
interrupted and resumed). Every other pair of state and input stays where it is, as
`otherwise_stay()` declared in the quickstart.

## Step 2: route a workflow on the pick

Here is an order workflow whose `deciding` stage hosts a Choice. Its machine names the two
options as inputs, plus a third, `undecided`, for when the Choice fails. `.branch(...)`
declares that the `deciding` state is left by whichever of those three `outcomes` the stage
answers, and `routes` says where each one leads:

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

ORDER_MACHINE = (
    MooreBlueprint(name="order")
    .inputs("started", "refund", "replace", "undecided")
    .outputs("idle", "decide", "refunding", "replacing", "asking_a_person")
    .state(name="idle", output="idle")
    .state(name="deciding", output="decide")
    .state(name="refunded", output="refunding", final=True)
    .state(name="replaced", output="replacing", final=True)
    .state(name="escalated", output="asking_a_person", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="deciding")
    .branch(
        source="deciding",
        outcomes=Alphabet.of("refund", "replace", "undecided"),
        routes={"refund": "refunded", "replace": "replaced", "undecided": "escalated"},
    )
    .otherwise_stay()
    .build()
)
```

The stage is a `Host`: a stage that runs one child. As in
[tutorial 8](../tutorials/workflow.md), `actor_class` is the child's class, `make(name,
memo)` builds the child and `start(memo)` builds its opening event; the **memo** is a
read-only view of the workflow's data, and `memo.input()` is the payload that started the
workflow. Here the Host has a `judge` instead of `routes`: a Decision that looks at the
child's outcome and answers the workflow's next input. `Chosen(options=..., failed=...)` is
that judge: its outcomes are the options and the `failed` symbol, so the verifier holds the
machine to a route for each, exactly as for any Decision:

```python
from gvn.harness.choice import Chosen
from gvn.harness.workflow import Host, Memo, Plan, Workflow


def make_decider(name: str, memo: Memo) -> Choice:
    return Choice(
        name=name,
        instructions="A customer reports a damaged item. Decide how to resolve it.",
        options=("refund", "replace"),
    )


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


deciding = Host(
    actor_class=Choice,
    make=make_decider,
    start=start_decider,
    judge=Chosen(options=("refund", "replace"), failed="undecided"),
)


class DamagedOrder(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(definition=ORDER_MACHINE, stages={"deciding": deciding})
```

Now run two orders, one where the model picks an option and one where it picks something
that is not on the list:

```python
def run_order(name: str, script: list[Reply]) -> Result:
    model = ScriptedModel(script=script)
    governor = Governor(
        fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )
    start = Event(name="started", payload={"complaint": "My kettle arrived with a cracked lid."})
    return asyncio.run(governor.deliver(actor=DamagedOrder(name=name), event=start))


picked = run_order(
    name="order-1",
    script=[answer_reply(data={"choice": "refund", "explanation": "Out of stock."})],
)
print(picked.outcome().state())  # State('refunded')
off_the_list = run_order(
    name="order-2",
    script=[answer_reply(data={"choice": "discount", "explanation": "Cheaper."})],
)
print(off_the_list.outcome().state())  # State('escalated')
```

The first order went to `refunded`. In the second, the (scripted) model answered
`"discount"`. A real vendor's enum constraint should prevent that; if it ever happens, the
Choice does not guess: it ends `failed`, and the workflow takes the `undecided` route you
declared. The reason is kept in the stage's results. `Report` reads a workflow's outcome,
and `results(stage)` gives the outcomes of that stage's children:

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

print(Report(outcome=off_the_list.outcome()).results("deciding")[0].payload())
```

```text
{'reason': "the reply is not a choice: the reply does not match the answer schema: $.choice: 'discount' is not one of ['refund', 'replace']"}
```

## Step 3: decide about an image or a document

A Choice's `started` event may carry **attachments**: images and PDF documents, sent to the
model after the prompt (see [Using a vendor model](vendors.md#images-and-documents)). An
attachment is an `Attachment` from `gvn.harness.messages`. An event's payload holds only
plain JSON data, so the attachment rides in it as its [Dto](../reference/glossary.md#dto)
(a plain-data copy of an object, which gvn can store and rebuild) in plain form.

Here the Choice is fed the event directly with `handle`, without a Governor, and `pending()`
shows the request it now makes, so you can see the attachment in it:

```python
from gvn.harness.messages import Attachment

photo = Attachment.image(data=b"\x89PNG\r\n\x1a\n" + bytes(32), media_type="image/png")
with_photo = Event(
    name="started",
    payload={"prompt": "Here is a photo of the lid.", "attachments": [photo.to_dto().to_plain()]},
)
looker = Choice(name="looker", instructions="Is the lid cracked?", options=("cracked", "intact"))
looker.handle(with_photo)
(request,) = looker.pending()
print(len(request.payload()["messages"][0]["attachments"]))  # 1
```

The bytes here are only the start of a PNG, enough for gvn's check of the media type (an
attachment's first bytes must match its declared type). The live runs used a real
32-pixel image made in code; see [Live runs](../reference/live-runs.md).

## Working with a Choice

- **One model request, no tools.** A Choice decides on what it is given. To gather facts first, run
  an `Agent` in an earlier stage and pass its findings in the prompt.
- **A failed Choice is a declared route.** To try again, loop back to the stage from the
  workflow; the workflow's machine bounds the loop.
- **The shape is checked, the judgement is yours to evaluate.** gvn guarantees that the pick
  is one of the options. Whether it is the right one is model behaviour: evaluate it like
  any other (see [Replay and evaluation](replay-and-evaluation.md)).
- **Letter case.** The check against the options is exact, so a pick in another case fails.
  Options that are lower-case identifiers keep the pick and the options in agreement.

## Recap

- `Choice(name=..., instructions=..., options=...)` asks a model to pick one option through
  the vendor's constrained output, checks it, and ends `chosen` or `failed`.
- `Chosen(options=..., failed=...)` is the `Host` judge that turns the pick into a workflow
  symbol; the verifier holds the workflow to every option and to the failure.
- The pick is journaled with the reply; replay and recovery see the same pick.

## Next

Choose by what you need now:

- **The pick from a real model.** [Using a vendor model](vendors.md) builds the adapter, and
  covers [images and documents](vendors.md#images-and-documents) and
  [a smaller model for the pick](vendors.md#a-model-per-role).
- **Whether the picks are right.** [Replay and evaluation](replay-and-evaluation.md) reads
  finished runs back and grades them against checks.
- **More stages around the pick.** [Different kinds of child in one stage](mixed-stages.md)
  and [Fan-out over items, with retries](items-and-retries.md) compose further children.
