# 10. A conversation

**At the end you can:** run a chat between a model and a person that waits for each reply
without a process, ends in one of a fixed set of ways, and tells a workflow which way.

**What you will learn:** how to run a **conversation**: an actor that talks with a person over
several turns, parks between turns, and ends only when the model closes it with one of a
fixed set of **closings**.

**Before this:** [9. A deadline](deadline.md). The look-up tool of
[tutorial 4](adding-a-tool.md) comes back.

**Time:** about 10 minutes.

## Where this sits in the big picture

This page is about the **actor** box and the **person** of the quickstart's
[big picture](../quickstart.md#the-big-picture). In tutorial 5 the person only said yes or
no to a tool call. Here the person is the one the run talks to: a conversation is an actor
that sends each of the model's answers to the person and waits for a reply, turn after
turn. The Governor, fulfillers and journal are the same as before.

## Where you are

Every agent so far ended as soon as the model answered without asking for a tool. That suits
a ticket that arrives complete. A chat with a customer is different: the help desk often has
to ask a question first ("which order?"), wait for the answer, and carry on.

**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
    from gvn.harness.events import Event
    from gvn.harness.messages import Message, ToolCall
    from gvn.harness.ports import Exchange, 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, Result
    from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput


    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 conversation actor

`Conversation`, in `gvn.harness.conversation`, thinks and uses tools exactly as the agent
does: the same requests, the same policy and approval. The difference is what happens when
the model replies with plain text. The agent ends; a conversation sends the text to the
person and waits for an answer. Only the model can end it, by calling a built-in tool,
`close`, with one of the `closings` you allow.

```python
from gvn.harness.conversation import Conversation

CLOSINGS = ("resolved", "escalated")

chat = Conversation(
    name="chat-1",
    instructions="Help the customer with their order. Close when it is settled.",
    audience="customer",
    tools=[look_up_order],
    closings=CLOSINGS,
    turns=5,
)
```

- `audience` names who the person is (a lowercase name).
- `closings` is the finite set of ways the conversation can end. A workflow can route on it,
  as you will see in step 5.
- `turns` is how many answers from the person are allowed; after the last, the conversation
  ends `exhausted` instead of running for ever.

As with the agent, `tools=` takes the tool objects, and the conversation stores their
identities. You do not add `close` to the toolbox: the conversation offers it to the model
itself, so none of your tools may have the short name `close`.

## Step 2: a model that asks, looks up, then closes

The model is a `FunctionModel` (from [tutorial 6](durability.md#step-2-a-model-whose-answer-depends-only-on-the-question)):
its reply depends only on the conversation so far. It asks for the order number, looks the
order up once the customer gives it, and closes with `resolved`:

```python
import re

from gvn.harness.messages import TOOL
from gvn.testing.fakes import FunctionModel


def clerk(exchange: Exchange) -> Reply:
    last = exchange.messages()[-1]
    if last.role() == TOOL:
        order = last.results()[0].content()
        close = ToolCall(
            call_id="close-1",
            name="close",
            arguments={"closing": "resolved", "text": f"Your order has {order['status']}."},
        )
        return Reply(message=Message.assistant(calls=[close]))
    order_id = re.search(r"[A-Z]-\d+", last.text())
    if order_id:
        look_up = ToolCall(
            call_id="look-1", name="look_up_order", arguments={"order_id": order_id.group()}
        )
        return Reply(message=Message.assistant(calls=[look_up]))
    return Reply(message=Message.assistant(text="Which order is it? I need its number."))
```

The `close` call carries the closing and a last `text` for the customer.

## Step 3: run until the customer must answer

The person's answer is requested with `request_input`, so that kind is external, as
`request_approval` was in tutorial 5. A conversation starts with the customer's first
message as `text`:

```python
def build_governor() -> Governor:
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=FunctionModel(respond=clerk), toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=AllowEverything()),
        },
        external=["request_input"],
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )


governor = build_governor()
opening = Event(name="started", payload={"text": "Where is my parcel?"})
result = asyncio.run(governor.deliver(actor=chat, event=opening))

question = result.pending()[0]
print(result.status(), question.request_id())  # waiting chat-1/request_input#1
print(question.payload()["text"])  # Which order is it? I need its number.
```

The run parked on the customer, holding no process, exactly like an approval. The request id
ends in the turn number, `#1`. If the question is still pending, recovery keeps that id.
`answer` checks that the request still belongs to the actor and can apply a deadline
before handling the answer.

## Step 4: the customer answers

The answer is an `answered` event with the customer's `text`, delivered with `answer`:

```python
reply = Event(name="answered", payload={"text": "It is A-17."})
result = asyncio.run(governor.answer(actor=chat, request=question, event=reply))

outcome = result.outcome()
print(outcome.state())  # State('closed')
print(outcome.payload()["closing"], outcome.payload()["turns"])  # resolved 1
print(outcome.payload()["text"])  # Your order has shipped.
```

In that one turn the model looked the order up and closed the conversation. The outcome
says how it ended (`closing`), how many answers the customer gave (`turns`) and the closing
text, along with a count of the tool calls made (`tally`, by tool identity) and the
transcript as kept
(`thread`).

## Step 5: route on how it ended

A workflow that hosts a conversation decides what to do next from its ending. `Closing` is a
ready-made Decision for that: its outcomes are your closings plus the other ways a
conversation can end (`exhausted`, `left`, `failed`, and `overflowed`: the conversation
outgrew the room it may use in the model's context window, see
[Context management](../concepts/context-management.md)). It reads only the closing and the final
state, never the text:

```python
from gvn.harness.conversation import Closing

ending = Closing(closings=CLOSINGS)
print(ending.decide(outcome))  # Symbol('resolved')
```

Give it to a stage as `Host(actor_class=Conversation, ..., judge=Closing(closings=...))`,
and the plan checks that the workflow's machine routes every one of its outcomes.

A customer can also walk away. The answer to a question can be `withdrawn` instead of
`answered`:

```python
walked_away = Conversation(
    name="chat-2",
    instructions="Help the customer with their order. Close when it is settled.",
    audience="customer",
    tools=[look_up_order],
    closings=CLOSINGS,
    turns=5,
)


async def customer_leaves() -> Result:
    waiting = await governor.deliver(
        actor=walked_away, event=Event(name="started", payload={"text": "Hello?"})
    )
    return await governor.answer(
        actor=walked_away, request=waiting.pending()[0], event=Event(name="withdrawn")
    )


result = asyncio.run(customer_leaves())
print(result.outcome().state(), ending.decide(result.outcome()))  # State('left') Symbol('left')
```

!!! warning "What to trust"
    The customer's text is untrusted. It enters the transcript, because the model must read
    it, and nothing else: never the [run context](../reference/glossary.md#run-context), never a
    route. Only the closing routes, and
    only through `Closing`, over a finite set. [Conversations](../concepts/conversations.md)
    lists this and the actor's other rules, and its context budget for long chats
    (`context_budget=`, explained in [Context management](../concepts/context-management.md)).

## Change it and run again

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

**1. Give the order number in the first message.** The customer opens with "Where is my
parcel A-17?". Does the run wait for a person? How many turns does the outcome count?

```python
def new_chat(name: str, turns: int) -> Conversation:
    return Conversation(
        name=name,
        instructions="Help the customer with their order. Close when it is settled.",
        audience="customer",
        tools=[look_up_order],
        closings=CLOSINGS,
        turns=turns,
    )


direct = Event(name="started", payload={"text": "Where is my parcel A-17?"})
result = asyncio.run(governor.deliver(actor=new_chat("chat-3", turns=5), event=direct))
outcome = result.outcome()
print(result.status(), outcome.state(), outcome.payload()["closing"], outcome.payload()["turns"])
```

??? note "What happens"

    ```text
    finished State('closed') resolved 0
    ```

    The model had what it needed, looked the order up and closed, all inside `deliver`. The
    run never parked, and `turns` is 0 because the person never answered a question.

**2. Allow one turn, and do not help.** With `turns=1`, the customer answers the question
without the order number. How does the conversation end, and what does `Closing` decide?

```python
async def unhelpful_customer() -> Result:
    chat = new_chat("chat-4", turns=1)
    waiting = await governor.deliver(
        actor=chat, event=Event(name="started", payload={"text": "Where is my parcel?"})
    )
    vague = Event(name="answered", payload={"text": "I do not know the number."})
    return await governor.answer(actor=chat, request=waiting.pending()[0], event=vague)


result = asyncio.run(unhelpful_customer())
outcome = result.outcome()
print(outcome.state(), ending.decide(outcome), outcome.payload()["closing"])
```

??? note "What happens"

    ```text
    State('exhausted') Symbol('exhausted') None
    ```

    The one allowed answer was used up, so the conversation ended `exhausted` without
    asking the model again. No closing was chosen (`None`), and `Closing` reports
    `exhausted`: a workflow hosting this chat must route that ending too.

## Recap

- A `Conversation` sends plain-text replies to a person (`request_input`) and parks until
  the answer; the model ends it by calling `close` with one of your `closings`.
- `turns` bounds the person's answers; the conversation ends `exhausted` past it.
- Answer with `answered` (and `text`) or `withdrawn`, through `governor.answer`.
- `Closing(closings=...)` is the Decision a workflow uses to route on how it ended.

**Next:** [11. Testing your harness](testing.md) turns what you built into fast, offline
tests, including a crash at every journal write.
