Conversations¶
What you will learn: how to run a model that talks with a person over many turns, how the conversation ends, how a workflow routes on the way it ended, how a long conversation stays within its model's context window, and how your code tells the model something with authority while the conversation is under way.
Read first: the reference agent, Asking a person and Workflows. Time: about 20 minutes.
Where this sits¶
A conversation is one more actor in the harness layer (the big picture). It combines two you have met: it thinks and uses tools like the reference agent, through the same fulfillers, and it waits for a person like an Inquiry. Each turn of the conversation goes once round the loop below; the run parks, costing nothing, while the person has the word:
flowchart LR
governor["Governor"]
conversation["<b>Conversation</b><br/>a verified machine"]
fulfillers["model, policy and<br/>tool fulfillers"]
person(["the person"])
governor -- "events" --> conversation
conversation -- "requests" --> governor
governor -- "invoke_model, tools…" --> fulfillers
fulfillers -- "model_replied…" --> governor
governor -.->|"request_input: parks"| person
person -- "answered" --> governor
The page goes from the problem, to running one conversation, to how a workflow uses its ending; the arguments, the machine, the context budget, the trusted channel and what to trust come last.
The problem: an agent stops when it answers¶
An agent ends when it answers. Some jobs are a conversation instead: a tutor and a learner, a clerk and a customer, many turns until something is settled.
Picture a shop clerk. A customer writes "Where is my order?". The clerk needs the order number, so it asks. The customer answers, maybe an hour later. The clerk looks it up and says it ships tomorrow. That is three messages, two of them from the model, and the run must wait for a person in the middle.
gvn.harness.conversation.Conversation is that actor. It thinks and uses tools exactly as the
agent does (the same request kinds, the same policy, approval and
attempt statuses), but a
reply without tool calls goes to a person instead of ending the run: it asks
request_input, as an Inquiry does, and the run parks until the person
answers. The model ends the conversation by calling a built-in close tool with one of a
finite set of closings: the named ways this conversation is allowed to end.
Step 1: a clerk model¶
For a runnable example you need a model. FunctionModel (a fake from gvn.testing.fakes)
turns a plain function into one: the function receives the exchange so far and returns the
reply. This clerk asks for the order number until it sees one, then calls close:
import asyncio
from gvn.harness.conversation import Closing, Conversation
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 Toolbox
from gvn.runtime.fulfillers import ModelFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput
def clerk(exchange: Exchange) -> Reply:
"""Asks for the order number, then closes the conversation."""
said = [message.text() for message in exchange.messages() if message.role() == "user"]
if any("A-17" in text for text in said):
close = ToolCall(
call_id="c1",
name="close",
arguments={"closing": "found", "text": "Order A-17 ships tomorrow."},
)
return Reply(message=Message.assistant(text="", calls=[close]))
return Reply(message=Message.assistant(text="Which order is it? I need its number."))
The close call names a closing (found) and a final text for the person.
Step 2: start the conversation¶
The Governor fulfils invoke_model and treats request_input as external, so it parks on the
customer:
governor = Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=FunctionModel(respond=clerk), toolbox=Toolbox())
},
external=["request_input"],
journal=MemoryJournal(),
output=RecordingOutput(),
clock=ManualClock(),
)
chat = Conversation(
name="chat-9",
instructions="Find the customer's order.",
audience="customer",
closings=("found", "not_found"),
turns=5,
)
result = asyncio.run(
governor.deliver(actor=chat, event=Event("started", {"text": "Where is my order?"}))
)
question = result.pending()[0]
print(result.status(), question.request_id(), question.payload()["text"])
The model spoke without calling a tool, so its words went to the customer as a question. The
request id ends in #1: it is the first turn's question.
Step 3: the customer answers¶
Whenever the answer comes, in this process or another, it is delivered as the answer to that request:
result = asyncio.run(
governor.answer(actor=chat, request=question, event=Event("answered", {"text": "It is A-17."}))
)
payload = result.outcome().payload()
print(result.outcome().state(), payload["closing"], payload["turns"], payload["text"])
The model saw the order number and called close with found. The conversation is
closed, after one answer from the person.
Step 4: route on the closing¶
A workflow often needs to know how a conversation ended. Read the final
state and these fields from the Outcome payload:
closing: the closing the model chose, orNoneunless the conversationclosed;text: the closing message or the last thing the model said;turns: the number of answers received from the person;attempts: the tool calls of the last turn, as for an agent (each with its tool's shortnameand itsidentity);tally: a count per tool, keyed by the tool's identity ("close"for the built-in close,"*"for calls to tools it was not offered), and per status, over the whole conversation, so the outcome stays small;reductions: how many times the transcript was made smaller, by kind, and how many of those losses a memory took (see the context budget below);recalls:{"asked", "found", "failed"}, how often a conversation built withrecall=Trueasked a memory by itself, how many entries it showed the model, and how many of those requests failed (all 0 otherwise);readings: the sensor summary, withtaken,failed,blocked, andlatest;thread: the transcript without vendor-sealed content, for a later conversation to continue;reason, only forfailedoroverflowed: why the conversation ended;exposure, only when not empty: the untrusted sources its model read (tools whose results may hold text from outside, recalled notes), which a later conversation that continues the thread is given with it (Trust).
A workflow routes on the closing with Closing(closings=...), a Decision over
the closings plus exhausted, left, failed and overflowed (the conversation no longer
fits its context budget; see below). It reads only the closing and the final
state, never the text. In the workflow it is the hosting stage's judge: a Decision the
Host applies to the finished child's outcome to pick the stage's next input, used instead of
routes (Judges has the
details): Host(actor_class=Conversation, make=..., start=..., judge=Closing(closings=("found", "not_found"))).
That is the 80% you need. The rest covers every argument, the machine, the context budget, the trusted channel and what to trust.
Deeper: every argument¶
Conversation(name, instructions, audience, tools=(), closings=("closed",), turns=20,
steps=10, context_budget=None, thread=None, context=None, limit=None, model_role=None,
recall=False, recall_limit=5, sensors=(), thread_exposure=())
audience: who the person is, as for an Inquiry.name: the conversation's address, which also prefixes its request ids.instructions: the model's standing directions, fixed for the whole conversation.tools: the tools the model may use, as Tool objects or aToolbox, as for an agent: the conversation keeps their identities (Tools).closeis added automatically: its spec travels in theinvoke_modelrequest as"provided", soModelFulfilleroffers it without your toolbox holding it. So no offered tool may have the short nameclose.closings: the finite set of ways the conversation can end. Aclosecall naming anything else is an unoffered call (one the model was not offered; the agent's machine treats it the same way).turns: how many answers from the person; after the last, the conversation endsexhausted.steps: how many model calls one turn may use; past it,failed.context_budget: how much of the model's context window the conversation may use, and how it is made smaller (below).thread: a transcript to continue (below).context: the run context, trusted data for the policy and the tools.limit: the longest answer text accepted.model_role:None, or the name of the role whose model serves the conversation's calls, as for an agent.recall,recall_limit: whether the conversation asks a memory, by itself, for entries matching each message of the person (see Memory).sensors: fixed measurements taken after a watched tool succeeds, as for an agent; a blocking one blocks the closing, never a reply to the person (below and Sensors).thread_exposure: the untrusted sources the model of the conversation that leftthreadhad read, its outcome's"exposure"; given only withthread(below and Trust).
Deeper: the machine¶
This is the conversation's definition as Table renders it (see
Machines): > marks the initial state and *
the final ones.
state output transitions
acting invoke_tools interrupted -> suspended, tools_returned -> checking_sensors
admitting check_steps steps_exhausted -> failed, within_steps -> measuring
awaiting_approval request_approval approved -> acting, denied -> admitting, interrupted -> suspended
checking_sensors check_sensors nothing_due -> admitting, sensors_due -> sensing
* closed closed -
counting check_turns turns_exhausted -> exhausted, turns_remain -> admitting
diagnosing classify_failure context_exceeded -> admitting, failure_final -> failed
* exhausted exhausted -
* failed failed -
> idle idle started -> admitting
interpreting classify_reply requested_close -> closed, requested_close_while_blocked -> admitting, requested_tools -> vetting, requested_unoffered -> admitting, spoke -> listening
* left left -
listening request_input answered -> counting, instructed -> listening, interrupted -> suspended_listening, withdrawn -> left
measuring check_context context_exhausted -> overflowed, context_fits -> thinking, recall_due -> recalling, remember_due -> remembering, summary_due -> summarising, trim_due -> measuring
* overflowed overflowed -
recalling recall interrupted -> suspended, recall_failed -> measuring, recalled -> measuring
remembering remember interrupted -> suspended, remember_failed -> measuring, remembered -> measuring
sensing sense interrupted -> suspended, sense_failed -> admitting, sensed -> admitting
summarising invoke_model interrupted -> suspended, model_failed -> measuring, model_replied -> measuring
suspended suspended resumed -> checking_sensors
suspended_listening suspended resumed -> listening
thinking invoke_model interrupted -> suspended, model_failed -> diagnosing, model_replied -> interpreting
vetting consult_policy cleared -> acting, forbidden -> admitting, interrupted -> suspended, needs_approval -> awaiting_approval
otherwise: stay
admitting, measuring, diagnosing, interpreting, counting and checking_sensors are
internal decisions. After every batch of tool calls, checking_sensors decides whether a
sensor is due and sensing asks for its readings, exactly as in the
agent. A blocking sensor that still
reads not clean blocks the closing, not the replies to the person: a valid close is
then requested_close_while_blocked, its call is settled with the status blocked and a
result naming the sensors, and the conversation goes back through admitting, within its
steps; a turn whose steps run out that way ends failed, naming the sensors.
measuring, remembering, summarising and diagnosing keep the conversation within its
context budget, as the next section says (remembering only for a budget that hands what it
drops to a memory), and overflowed is the final state for a conversation that no
longer fits it. recalling is used only by a conversation built with recall=True: before
the model answers each message of the person, it asks a memory for entries matching that
message and shows the model what it found as one note (see
Memory); the note is never counted as a turn of the
person's. instructed while listening is the trusted channel described
further down. interrupted while
listening leads to suspended_listening, so resuming asks the person the same question again
rather than the model. The request_input request has id "<name>/request_input#<turn>": the
same Request for as long as that turn's question stands, across instructions, interrupts,
crashes and revival, so an answer tied to it stays valid while the run is parked.
Its payload is {"audience", "text", "choices", "limit", "turn", "context"}: text is the
model's reply, the question the person answers, and turn says which exchange with the
person this is, counting from 1. Code that needs the turn reads payload()["turn"] rather
than taking the request id apart.
Deeper: the context budget¶
Every model call sends the whole conversation, and a model can read only so much in one call:
its context window, counted in tokens. A conversation with a person can run for many
turns and outgrow it. context_budget says how much of that window the conversation may use
and how it is made smaller when it fills: a ContextBudget from
gvn.harness.context_window, exactly as for the
reference agent.
The conversation reads the size of its conversation from the token counts each model reply
reports; it never counts tokens itself.
from gvn.harness.context_window import ClearToolResults, ContextBudget, KeepRecent, Summarise
recent_chat = Conversation(
name="chat-10",
instructions="Find the customer's order.",
audience="customer",
context_budget=ContextBudget(reduce_over=6, steps=[KeepRecent(messages=6)]),
)
summarising_chat = Conversation(
name="chat-11",
instructions="Find the customer's order.",
audience="customer",
context_budget=ContextBudget(
reduce_at=0.5, reduce_over=12, steps=[ClearToolResults(keep=1), Summarise(keep=4)]
),
)
print(recent_chat.state(), summarising_chat.state())
The first keeps the last six messages once there are more than six. When those six start
with the model's reply rather than the customer's message, a short user message saying that
the earlier conversation was dropped goes before them, so the model knows something came
first and every vendor accepts the conversation; that note is not one of the six. The
second, once the conversation reaches half the model's window or holds more than twelve
messages, first clears old tool results and, if that is not enough, has the model summarise
all but the last four messages. Without a context_budget, nothing is reduced, and a
conversation the vendor refuses as too large ends overflowed.
Before every model call the conversation passes through measuring; a summary is a model
call of its own, in summarising, that spends no step. Reducing on gvn's side drops the
model's carried thinking and restarts the vendor's cache of the conversation. With a budget
whose steps bound the transcript (KeepRecent, or Summarise with reduce_over), the
conversation's Dto (its saved form) is bounded by the budget and one
turn's work, not by the conversation's length. The journal still holds every event, so replay
rebuilds the same state. Context management, the next page, explains
the budget, the steps, the costs and the vendor's own alternative in full.
A budget built with remember_dropped=True hands what each reduction is about to drop to a
memory first, in the state remembering, through a remember request; the outcome's
"reductions" then counts "remembered" and "unremembered" beside "trimmed",
"summarised" and "fell_back". The conversation's saved form keeps whether the loss now
due was handed over (loss_handed_over) and its model_role. Memory explains it.
A conversation built with recall=True (and recall_limit=, 5 by default) asks a memory,
before its model answers, for entries that match the text the person just sent (the opening
text and each answer that is not blank). It does this in measuring, after counting and
admitting, so an answer that uses the last turn recalls nothing. What comes back is one user
message under the fixed header RECALLED, after the person's message and any instruction
given with it. That note is not the person's: it never counts as a turn, the limit does not
apply to it, and a reduction never hands it back to the memory. It stays in the transcript,
so a thread carried to a next conversation contains it; code that reads "the person's last
message" from a thread skips notes with gvn.harness.context_window.is_recalled_note. Its
saved form adds recall, recall_limit, recall_query (the text whose recall is owed) and
recalls. Memory explains when to use it.
Deeper: a trusted channel into a running conversation¶
A conversation's instructions are fixed when it is built, and everything else in it comes
from the model or the person. Sometimes your code learns something during the conversation
that the model must take with authority: the last answer was graded wrong, the order was just
refunded, the person has been verified. Writing it into the person's text would make it
untrusted; ending the conversation to start a new one would lose the turn.
So a conversation takes one more event while it is listening: instructed, with
{"text": ...}, from your code (never from the person or a model). The conversation holds the
text and, when the person's next answer arrives, appends it right after their message as an
instruction message (Message.instruction(text), a fourth message role beside user,
assistant and tool). An adapter sends an instruction message with the vendor's own authority
for text from the developer (Anthropic: a system message inside the conversation; OpenAI: a
developer message), never as the person's words.
Built as in steps 1 and 2 (a fake model, and a Governor that parks on request_input), with a
model that records what it is sent, this conversation is told something while it waits for
the customer:
from gvn.harness.ports import Reply
seen = []
def recording_clerk(exchange: Exchange) -> Reply:
seen.append([(message.role(), message.text()) for message in exchange.messages()])
return Reply(message=Message.assistant(text="Thank you. Anything else?"))
told_governor = Governor(
fulfillers={
"invoke_model": ModelFulfiller(
model=FunctionModel(respond=recording_clerk), toolbox=Toolbox()
)
},
external=["request_input"],
journal=MemoryJournal(),
output=RecordingOutput(),
clock=ManualClock(),
)
told_chat = Conversation(name="chat-12", instructions="Help the customer.", audience="customer")
waiting = asyncio.run(
told_governor.deliver(actor=told_chat, event=Event("started", {"text": "Hello."}))
)
question = waiting.pending()[0]
told = asyncio.run(
told_governor.deliver(
actor=told_chat,
event=Event("instructed", {"text": "The customer's identity has been verified."}),
)
)
print(told.status(), told.pending()[0] == question)
asyncio.run(
told_governor.answer(
actor=told_chat, request=question, event=Event("answered", {"text": "Refund A-17."})
)
)
print(seen[-1])
waiting True
[('user', 'Hello.'), ('assistant', 'Thank you. Anything else?'), ('user', 'Refund A-17.'), ('instruction', "The customer's identity has been verified.")]
The question did not change: the instruction waits for the answer, so the person is not asked again and the answer tied to the request stays valid. What to know:
- Only while listening. In any other state
instructedis rejected and changes nothing (the Governor's result saysrejected()). Several instructions before one answer are joined, in order, with a blank line.withdrawndrops what is held. What is held survives an interrupt, a crash and revival. - Only your code creates one. No model reply, tool result or person's answer ever becomes an instruction message. Its text never routes.
- It is part of the transcript at the point it was given. A later reduction may drop it
or summarise it like any other message (a cut never separates it from the user message
before it). What must hold for the whole conversation belongs in
instructions.
Deeper: code between turns with thread=¶
Sometimes code must run between turns, where the model cannot skip it: a tutor's answers are
graded by an errand after every turn. Give the conversation turns=1: it ends
exhausted after one answer, the workflow runs its own stages, and the next stage starts a
new Conversation with thread=<the previous outcome's thread> (and its own name). The
education harness works this way. In a loop like that (a stage the
workflow visits again and again, see Loops), a Host
with retain=N keeps full outcomes for only the last N visits of the stage.
A thread carries what the earlier conversation's model read, so the next conversation is
also given its exposure: thread_exposure=<the previous outcome's "exposure">, the
untrusted sources (tools whose results may hold text from outside, and recalled notes) that
earlier model had read (Trust). A model handed a transcript that holds untrusted
text has read it, so the new conversation's exposure starts there and only grows; its policy
and its approver see it from the first call. The outcome has "exposure" only when it is not
empty, and thread_exposure= is given only with a thread:
finished = result.outcome().payload()
follow_up = Conversation(
name="chat-9/follow-up",
instructions="Answer questions about the order.",
audience="customer",
thread=finished["thread"],
thread_exposure=finished.get("exposure", ()),
)
print(follow_up.exposure()) # frozenset(): the clerk read nothing from outside
Deeper: images and documents from the person¶
A customer often shows rather than tells: a photo of a damaged parcel, a PDF receipt. Both
started and answered take an optional "attachments" list, each the plain form of an
Attachment (an image or a PDF), and the conversation appends them to
the user message after the text, exactly as Message.user(text, attachments=...) would:
from gvn.harness.messages import Attachment
photo = Attachment.image(data=b"\x89PNG\r\n\x1a\n" + bytes(40), media_type="image/png")
parcel_chat = Conversation(
name="chat-10", instructions="Help with damaged parcels.", audience="customer"
)
parcel_chat.handle(
Event(
"started",
{"text": "My parcel arrived like this.", "attachments": [photo.to_dto().to_plain()]},
)
)
print(len(parcel_chat.transcript()[-1].attachments())) # 1
The model receives the photo with the text in its next invoke_model request. An answer
carries them the same way: Event("answered", {"text": "Here is the receipt.", "attachments":
[...]}). Each attachment is rebuilt and checked as Attachment.image and
Attachment.document check what they are given (an accepted media type, leading bytes that
match it, at most 5 MB of data, or an https:// URL); one that does not pass is a
ValueError that changes nothing. With attachments, started may have empty text. An
answer's limit counts its text only. A payload without "attachments" is stored exactly
as before.
When a Summarise step of the context budget summarises, the summariser is not sent the attachments of the messages it
summarises (a person's or a tool's):
it sees a description of each in its place (kind, media type and size, or its URL), so a
summary can mention a photo without the photo being sent again.
What to trust and what to put where¶
- The person's text is untrusted. It enters the transcript, because the model must read
it, and nothing else: never a run context, never a route, never a request other than
invoke_model.byanddataon the answer are checked and dropped. The same holds for the attachments a person sends: they reach the model and nothing else. - An instruction message is trusted, because only your code can send
instructed. Keep the person's words out of it. - A summary is model-written content, and as untrusted as the text it summarises.
- Only the closing routes, and only through
Closing, over a finite set. - A sensor's reading is untrusted data, like a tool result: it reaches the model as one marked user message and never the instructions.
- An instruction lasts as long as the transcript keeps it. The trusted channel adds a
message at one point of the conversation, after the person's next answer, and a later
reduction may drop or summarise it. Code that must change the standing directions ends the
conversation and starts the next with
thread=and newinstructions. An instruction is given while the conversation waits for the person. - The context budget belongs to one conversation. What one conversation learned reaches
another through
thread=or a memory, and from a memory when the model recalls it. Measuring and reducing are described on Context management. - Request ids other than
request_inputchange across an interrupt. As for the agent, resuming asks the model again under a new id; an effect that must happen at most once is keyed by trusted data.
Recap¶
- A
Conversationis an agent whose plain replies go to a person (request_input) instead of ending the run. - The model ends it by calling
closewith one of the declaredclosings; it can also endexhausted,left,failedoroverflowed. - Deliver each answer with
Governor.answer; the turn's request id is stable while it waits. - Workflows route on
Closing(closings=...), never on the text. context_budget=ContextBudget(...)keeps a long conversation within its model's window;thread=continues one in a new conversation.instructedwhile listening adds trusted text from your code after the person's next answer.sensors=reads fixed measurements after watched tools succeed; a blocking sensor holds the closing until it reads clean.
Next: Context management, how a conversation and an agent measure and reduce what they send the model.