Your own harness¶
At the end you have: a plan for your own harness, as ten answered questions, and a file to start it from.
Before this: 12. A real model and ready-made tools. This page adds no new part of gvn; it turns the parts you have used into decisions about your job.
Time: about 15 minutes.
The big picture, asked about your job¶
The tutorials opened this picture one box at a time, for a help desk. Your job fills the same boxes:
flowchart LR
you(["You, or your application"])
person(["A person who approves"])
subgraph run ["One run"]
direction TB
governor["<b>Governor</b>"]
actor["<b>Actor</b><br/>a verified state machine"]
governor -- "event" --> actor
actor -- "request" --> governor
end
fulfillers["<b>Fulfillers</b><br/>model · tools · policy"]
journal[("<b>Journal</b>")]
output["<b>Output</b>"]
you -- "event: started" --> governor
governor -- "request" --> fulfillers
fulfillers -- "event" --> governor
governor -- "records" --> journal
governor -- "reports" --> output
governor -- "asks" --> person
person -- "answer" --> governor
Each box asks one thing of your job:
- You, or your application: what starts a run, and what does the start carry?
- Actor: what are the steps of the job, and in which states can it end?
- Fulfillers: which model thinks, which tools act, and which policy judges each call?
- A person: which calls wait for a yes, and whose yes counts?
- Journal: where is the run kept, so that it is still there after the process is gone?
- Output: what do you want to see while the run is going?
- Governor: nothing. It is the same for every job.
The design checklist¶
Answer these in order before you write code. Each answer is one decision in your file.
| Question about your job | Your answer decides | Taught in |
|---|---|---|
| What is the job, and when is it finished? | The final states of your actor and what its outcome carries. An Agent ends completed, failed or overflowed. |
1. A first machine, 3. An agent |
| One agent, or several steps? | Agent alone when the job is one question with one set of instructions and tools. A Workflow when parts need different instructions or tools, when code must fix their order, when each ending needs its own route, or when parts run at once or under a deadline. |
8. A workflow, Workflows, Designing a large harness |
| Which tools, and which have effects? | Your Tool classes. For each tool with an effect outside the run, how invocation.key() makes a repeated call harmless. |
4. Adding a tool, 6. Crash and resume, Tools |
| Which calls need a person, and who may answer? | Your policy: cleared, needs_approval or forbidden for each call. entitlement= and by= when only some people may answer. |
5. Approval by a person, Who answered, recipe Stop a tool call until a person approves |
| Must a run outlive its process? | The journal: MemoryJournal within one process, SqliteJournal for a file that processes share, PostgresJournal for a database that machines share. |
6. Crash and resume, Running gvn as a service |
| How is a run named, and started only once? | The run's name, derived from the job's own id. Recover first; start only when the journal does not know the name. | 6. Crash and resume |
| What shape is the final answer? | Plain text, or checked fields: answer= with a Record on the agent. |
Structured answers |
| What do you watch while it runs? | The output: your own Output class, LoggingOutput, TracingOutput, or several at once. |
7. Streaming, Logs, traces and streams |
| How do you test it offline? | Which fakes stand in for the model, the tools and the journal. | 11. Testing your harness, recipe Test an agent offline |
| Which model? | The adapter and the model id, read from the environment as MODEL_ID. It comes last because it changes one object. |
12. A real model, Using a vendor model |
A worked example: an intake harness¶
Here is the checklist applied to another job. Messages arrive in a shared inbox. For each one, an agent finds the customer, drafts a reply and sends it. A person must agree before anything is sent, and may answer hours later, after the process has restarted.
| Question | The answer for intake |
|---|---|
| The job, and when it is finished | One message in, one reply sent. The run ends completed with the agent's last text. |
| One agent or several steps | One agent: one set of instructions, two tools, and the order is the model's to choose. |
| Tools, and which have effects | find_customer only reads. send_reply has an effect, so it writes its key to the outbox and a repeated call sends nothing. |
| Calls that need a person | Every send_reply. Everything else is cleared. |
| Outliving the process | Yes: SqliteJournal, in a file. |
| Naming the run | intake- plus the message's id. Recover first, start only if unknown. |
| The answer's shape | Plain text. |
| What to watch | One line when the run waits and when it finishes. |
| Testing offline | A FunctionModel plays the model, so the whole file runs with no key. |
| The model | Left for last: one object in build_governor. |
And the file those answers give. handle is what one process does for one message; the
last lines call it three times, as three processes would: the message arrives, the process
restarts with nothing new, then a person approves.
import asyncio
import pathlib
import typing
from tempfile import TemporaryDirectory
from gvn.adapters.clock import SystemClock
from gvn.adapters.sqlite import SqliteJournal
from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import FINISHED, WAITING, Exchange, Output, Reply, Signal
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.runtime.recovery import Recovery, UnknownRun
from gvn.testing.fakes import FunctionModel
class FindCustomer(Tool):
"""Reads only: the policy clears it."""
def name(self) -> str:
return "find_customer"
def namespace(self) -> str:
return "intake"
def description(self) -> str:
return "Find a customer record by email."
def arguments(self) -> Record:
return Record({"email": Text()})
async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
return {"email": arguments["email"], "plan": "pro"}
class SendReply(Tool):
"""Has an effect outside the run: a person approves it, and a repeat sends nothing."""
def __init__(self, outbox: pathlib.Path) -> None:
self._outbox = outbox
def name(self) -> str:
return "send_reply"
def namespace(self) -> str:
return "intake"
def description(self) -> str:
return "Send the drafted reply to the customer."
def arguments(self) -> Record:
return Record({"email": Text(), "body": Text()})
async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
sent = self._outbox.read_text().splitlines() if self._outbox.exists() else []
if not any(line.startswith(invocation.key() + " ") for line in sent):
with self._outbox.open("a") as outbox:
outbox.write(f"{invocation.key()} {arguments['email']}: {arguments['body']}\n")
return {"sent": True}
class IntakePolicy(Decision):
def __init__(self, send_reply: Tool) -> None:
self._send_reply = send_reply
def outcomes(self) -> Alphabet:
return VERDICTS
def judge(self, consultation: object) -> Symbol:
if consultation.calls_to(self._send_reply):
return VERDICTS.named("needs_approval")
return VERDICTS.named("cleared")
def scripted_model(exchange: Exchange) -> Reply:
"""Stands in for the vendor model: its reply depends only on the conversation so far."""
results = [message for message in exchange.messages() if message.role() == TOOL]
if not results:
find = ToolCall(call_id="c1", name="find_customer", arguments={"email": "ana@example.com"})
return Reply(message=Message.assistant(calls=[find]))
if len(results) == 1:
plan = results[0].results()[0].content()["plan"]
body = f"Hello Ana, here is how billing works on the {plan} plan."
send = ToolCall(
call_id="c2", name="send_reply", arguments={"email": "ana@example.com", "body": body}
)
return Reply(message=Message.assistant(calls=[send]))
return Reply(message=Message.assistant(text="Reply sent to ana@example.com."))
class Progress(Output):
"""What you watch while it runs: one line when the run waits or finishes."""
def emit(self, signal: Signal) -> None:
if signal.kind() in (WAITING, FINISHED):
print(f" [{signal.actor()}] {signal.kind()} in {signal.data()['state']}")
def build_governor(journal: SqliteJournal, outbox: pathlib.Path) -> tuple[Governor, list[Tool]]:
find_customer, send_reply = FindCustomer(), SendReply(outbox=outbox)
toolbox = Toolbox([find_customer, send_reply])
governor = Governor(
fulfillers={
"invoke_model": ModelFulfiller(
model=FunctionModel(respond=scripted_model), toolbox=toolbox
),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=IntakePolicy(send_reply=send_reply)),
},
external=["request_approval"],
journal=journal,
output=Progress(),
clock=SystemClock(),
)
return governor, [find_customer, send_reply]
async def handle(folder: pathlib.Path, message_id: str, text: str, answer: str | None) -> None:
"""One process: find the run of this message or start it, then pass on a person's answer."""
run_name = f"intake-{message_id}"
journal = SqliteJournal(path=folder / "intake.db")
governor, tools = build_governor(journal=journal, outbox=folder / "outbox.txt")
try:
agent = await Recovery(journal=journal).recover(run_id=run_name, actor_class=Agent)
result = await governor.resume(actor=agent)
except UnknownRun:
agent = Agent(name=run_name, instructions="Draft a reply and send it.", tools=tools)
started = Event(name="started", payload={"prompt": text})
result = await governor.deliver(actor=agent, event=started)
if result.pending() and answer is not None:
request = result.pending()[0]
result = await governor.answer(actor=agent, request=request, event=Event(name=answer))
await journal.close()
if result.pending():
call = result.pending()[0].payload()["calls"][0]
print(f"{run_name} waits for a person: {call['name']} to {call['arguments']['email']}")
else:
print(f"{run_name} {result.outcome().state().name()}: {result.outcome().payload()['text']}")
with TemporaryDirectory() as directory:
folder = pathlib.Path(directory)
question = "ana@example.com asks how billing works."
asyncio.run(handle(folder, "msg-81", question, answer=None)) # the message arrives
asyncio.run(handle(folder, "msg-81", question, answer=None)) # the process restarted
asyncio.run(handle(folder, "msg-81", question, answer="approved")) # a person approves
print((folder / "outbox.txt").read_text().count("\n"), "reply in the outbox")
It prints:
[intake-msg-81] waiting in awaiting_approval
intake-msg-81 waits for a person: send_reply to ana@example.com
[intake-msg-81] waiting in awaiting_approval
intake-msg-81 waits for a person: send_reply to ana@example.com
[intake-msg-81] waiting in awaiting_approval
[intake-msg-81] finished in completed
intake-msg-81 completed: Reply sent to ana@example.com.
1 reply in the outbox
The first call started the run, which parked on the approval. The second, a restart, found the run in the file and left it waiting. The third recovered the same run, passed on the person's answer, and the reply was sent once.
Three things in the file are worth copying:
- Each process builds its own tools and Governor, in
build_governor. The journal stores a tool's name, never its code. - The tools fix their namespace with
namespace(), so their identity isintake.send_replywhichever file builds them. handlenever asks whether the run exists. It recovers, and theUnknownRunbranch is the only place a run is started.
To take this file live, swap the model in build_governor and use a real folder, as
tutorial 12 did. The journal and the
clock are already the real ones.
Start from a file¶
The recipes are single files that run offline as they are. Start from the one closest to your job and change it:
| Your job looks like | Start from | File |
|---|---|---|
| One agent, a tool that needs a person's yes, and the answer comes from another process or after a restart | Keep an agent's pending approval across a restart | resume_approval.py |
| One agent, and you want its tests first: nothing runs before approval, proven with no API key | Test an agent offline | check_agent_offline.py |
| Two or more steps in a fixed order, with an approval inside one of them | A two-stage workflow | claims_workflow.py |
| Only the approval itself, with who answered on record | Stop a tool call until a person approves | approve_tool.py |
The intake file above covers the same ground as the first row, with the Governor wired by hand and the run named after its message. If your job is close to intake, copy it instead.
Packaging it¶
Every tutorial wired a Governor by hand. That wiring belongs to the job, so gvn has an
object for it. A
Harness (in gvn.runtime.harnesses) is one packaged job: it names itself, says what a run
is started with, builds the starting actor, and holds the toolbox and the policy. A
Launcher (in gvn.runtime.launching) takes a harness, a model, a journal, an output and a
clock, builds the Governor from them, and then lets you drive runs by name: start,
approve, deny, reply, wake, resume and recover.
Harnesses shows one in code, and
Running gvn as a service runs a Launcher in several
processes over one journal.
Recap¶
- Your harness fills the same boxes as the help desk. The checklist is one question per decision, in the order to make them.
- Start from the recipe closest to your job, or from the intake file on this page.
HarnessandLauncherare the packaged form of the wiring you did by hand.
Next¶
- Choose your path points you to the pages for what you want to do next.
- The Guides each solve one task on top of what you now know.
- Evals measure whether a change to your harness made it better.
- The Workbench shows your harness and its runs in a browser.