12. A real model and ready-made tools¶
At the end you can: run the help desk on a vendor's model with a journal in a file, the real clock, log lines for every step and a person approving refunds, and name the real part that replaces each fake the tutorials used.
What you will learn: how to use gvn's ready-made tools next to your own, how to write
the help desk's policy in a few lines with Rules, how to replace the scripted model with
a vendor's model, and which real adapter stands behind each port. A last section, for
when you want it, says what a real model call costs.
Before this: 11. Testing your harness.
Time: about 15 minutes, plus whatever it takes to get an API key.
Where this sits in the big picture¶
In the quickstart's big picture, the model and the tools are reached only through the fulfillers, at the edge of the run. That is why going live changes so little: the actor, the Governor, the journal and your tests stay as they are, and only the objects at the edge are swapped.
flowchart LR
governor["<b>Governor</b>"]
model["model fulfiller"]
tools["tool fulfiller"]
policy["policy fulfiller"]
fake["ScriptedModel"] -.->|"replaced by"| real["AnthropicModel / OpenAIModel"]
yours["your tools"] -.->|"joined by"| ready["gvn-tools: files, shell, git, ..."]
hand["RefundPolicy"] -.->|"rewritten as"| rules["Rules"]
governor --> model --> real
governor --> tools --> ready
governor --> policy --> rules
The page swaps them in that order of safety: the tools and the policy first, still offline, then the model, then the journal, the clock and the output, which were fakes too.
Where you are¶
Every run in the tutorials used a fake model, so it ran offline and gave the same answer each time. That is how you test (tutorial 11). To serve customers, the model must be real, and the agent will want more tools than the two you wrote. Both changes touch only the edges of the program: the model is a port, and tools live in the toolbox.
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 of tutorial 4 and the refund tool of tutorial 5, each built once as an object. Then add each block of the page below it, in order. Steps 4 and 5 and one block of "Going further" call a vendor: add those blocks when you have an API key.
The look-up and refund tools from tutorials 4 and 5
import asyncio
import typing
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Model, Reply
from gvn.harness.tools import Invocation, Tool, Toolbox
from gvn.kernel.schema import Number, Record, Text
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel
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 IssueRefund(Tool):
"""Refunds into a list, in memory: enough for this page."""
def __init__(self, refunds: list[dict[str, typing.Any]]) -> None:
self._refunds = refunds
def name(self) -> str:
return "issue_refund"
def description(self) -> str:
return "Refund an amount on an order. Money leaves the shop."
def arguments(self) -> Record:
return Record({"order_id": Text(), "amount": Number()})
async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
self._refunds.append(dict(arguments))
return {"refund": len(self._refunds)}
order_book = OrderBook(orders={"A-17": {"status": "delivered", "total": 40.0}})
look_up_order = LookUpOrder(order_book=order_book)
issue_refund = IssueRefund(refunds=[])
Step 1: ready-made tools¶
gvn-tools (import name gvn_tools) is a sibling package of tools for files, a shell, git,
the web, Jira and GitHub. Each tool is constructed with its confinement, and refuses
anything outside it, whatever the policy says. The file tools are confined to a
Workspace: one directory.
The help desk keeps its written policies in a folder. Give the agent the file tools over it:
import pathlib
from tempfile import TemporaryDirectory
from gvn_tools import files
from gvn_tools.workspace import Workspace
policy_workspace = TemporaryDirectory(prefix="gvn-helpdesk-")
policies = pathlib.Path(policy_workspace.name)
(policies / "returns.md").write_text("Damaged orders are refunded in full within 30 days.\n")
file_tools = files.tools(workspace=Workspace(root=policies.resolve()))
print([tool.name() for tool in file_tools])
# ['read_file', 'list_files', 'search_files', 'write_file', 'edit_file']
print(file_tools.read_file.identity()) # gvn_tools.files.read_file
toolbox = Toolbox([*file_tools, look_up_order, issue_refund])
files.tools returns the family as a named tuple: you pick one tool by attribute
(file_tools.read_file) and pass the whole tuple where several are expected. Each tool's
identity starts with the
module that defines it, gvn_tools.files, so it can never be confused with a read_file of
your own. The toolbox holds the shop's tools beside them.
A path that leaves the workspace (../secrets.txt) is refused by the tool itself, and the
model receives a failed result. Tools describes the safety model of every
family; Files the file tools.
Step 2: the policy in a few lines¶
Each tool family comes with the policy it recommends, as a Rules object: a ready-made
Decision over the same three verdicts as your hand-written policies. You can also build your
own: clear, approve and forbid take tool objects and match calls by identity, and
when= adds a condition. A call no rule matches is forbidden by default.
from gvn_tools.rules import Rules
def small_refund(call: ToolCall, context: dict[str, typing.Any]) -> bool:
amount = call.arguments().get("amount")
return isinstance(amount, (int, float)) and amount <= 100.0
helpdesk_rules = (
Rules()
.clear(file_tools.read_file, file_tools.list_files, look_up_order)
.approve(issue_refund, when=small_refund)
)
That is the RefundPolicy of tutorial 5 in three lines: reading and looking up are cleared,
a refund up to 100.00 needs a person, and everything else (a larger refund, an unreadable
amount, writing a file) is forbidden, because no rule matches it. As in tutorial 5, the
condition treats the arguments as untrusted.
files.rules(file_tools) would clear all five file tools, writing included. The help desk only needs
to read, so it names what it needs; and the agent below is only offered the reading tools,
which is a second line of defence: a call to a tool not offered to the agent is refused
before the policy is even asked.
Step 3: run it, still offline¶
build_governor(model=...) is the only place the model appears. Run it once with a scripted
model to see the new tools work:
def build_governor(model: Model) -> Governor:
return Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=helpdesk_rules),
},
external=["request_approval"],
journal=MemoryJournal(),
output=RecordingOutput(),
clock=ManualClock(),
)
read_policy = ToolCall(call_id="call-1", name="read_file", arguments={"path": "returns.md"})
scripted = ScriptedModel(
script=[
Reply(message=Message.assistant(calls=[read_policy])),
Reply(message=Message.assistant(text="Damaged orders are refunded in full.")),
]
)
def new_helpdesk() -> Agent:
return Agent(
name="helpdesk",
instructions="Answer from the shop's written policies. Read them before answering.",
tools=[file_tools.read_file, file_tools.list_files, look_up_order],
)
question = Event(name="started", payload={"prompt": "What if my order arrives damaged?"})
result = asyncio.run(build_governor(model=scripted).deliver(actor=new_helpdesk(), event=question))
print(result.outcome().payload()["tools"][0]["content"]["text"])
# Damaged orders are refunded in full within 30 days.
Step 4: swap in a real model¶
gvn has three model adapters: AnthropicModel (in gvn.adapters.anthropic), OpenAIModel
(in gvn.adapters.openai) and ChatCompletionsModel (in gvn.adapters.chat_completions,
for any service with a Chat Completions endpoint, DeepSeek for one). Each needs an SDK, from
the anthropic or openai extra. The openai extra
provides the SDK for both OpenAIModel and ChatCompletionsModel.
Set two environment variables before you run the next block: ANTHROPIC_API_KEY, which
the SDK reads, and MODEL_ID, the id of a model available to your account, which the
block reads (the same name the quickstart uses). The SDK owns the
connection and the credential. Then start a fresh actor:
# not runnable: it needs an API key and the network.
import os
import anthropic
from gvn.adapters.anthropic import AnthropicModel
async def ask_live() -> Result:
async with anthropic.AsyncAnthropic() as client:
model = AnthropicModel(client=client, model=os.environ["MODEL_ID"], max_tokens=4096)
return await build_governor(model=model).deliver(actor=new_helpdesk(), event=question)
result = asyncio.run(ask_live())
payload = result.outcome().payload()
print(payload.get("text", payload.get("reason")))
The fresh actor uses the same tools and the same policy. The block prints the model's answer when the run completes, or the reason when the run fails.
Using a vendor model covers all three adapters: what they translate, how failures are reported, and which ones are worth retrying.
Step 5: from fake to real, every port¶
Step 4 made the model real and left three fakes in build_governor: a journal in memory,
a clock that never moves and an output that only records. Each
port has a real adapter, all in gvn.adapters. The fakes are all in
gvn.testing.fakes.
| Port | The fake the tutorials used | The real adapter | Import it from | Install extra |
|---|---|---|---|---|
| Model | ScriptedModel, FunctionModel |
AnthropicModel, OpenAIModel or ChatCompletionsModel |
gvn.adapters.anthropic, gvn.adapters.openai, gvn.adapters.chat_completions |
anthropic for the first, openai for the other two |
| Journal | MemoryJournal |
SqliteJournal, or PostgresJournal |
gvn.adapters.sqlite, gvn.adapters.postgres |
none for SQLite, postgres for PostgreSQL |
| Clock | ManualClock |
SystemClock |
gvn.adapters.clock |
none |
| Output | RecordingOutput |
LoggingOutput, or TracingOutput |
gvn.adapters.logs, gvn.adapters.otel |
none for logging, otel for tracing |
Optional extras says how to install one. You met
SqliteJournal in tutorial 6 and LoggingOutput by name in
tutorial 7. SystemClock() takes no arguments: now() is the system's
time in seconds since the epoch, and sleep really waits.
Here are all four together, with the approval of tutorial 5 and the run named after its ticket and recovered first, as in tutorial 6:
# not runnable: it needs an API key and the network.
import logging
from gvn.adapters.clock import SystemClock
from gvn.adapters.logs import LoggingOutput
from gvn.adapters.sqlite import SqliteJournal
from gvn.runtime.governor import WAITING
from gvn.runtime.recovery import Recovery, UnknownRun
helpdesk_log = logging.getLogger("helpdesk")
helpdesk_log.addHandler(logging.StreamHandler())
helpdesk_log.setLevel(logging.INFO)
def live_governor(model: Model, journal: SqliteJournal) -> Governor:
return Governor(
fulfillers={
"invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
"invoke_tools": ToolFulfiller(toolbox=toolbox),
"consult_policy": PolicyFulfiller(decision=helpdesk_rules),
},
external=["request_approval"],
journal=journal,
output=LoggingOutput(logger=helpdesk_log),
clock=SystemClock(),
)
def new_refund_desk(run_name: str) -> Agent:
return Agent(
name=run_name,
instructions=(
"Read the shop's written policies and look the order up. "
"Refund the order if the policies allow it."
),
tools=[file_tools.read_file, file_tools.list_files, look_up_order, issue_refund],
)
async def serve(ticket_id: str, complaint: str) -> None:
run_name = f"helpdesk-ticket-{ticket_id}"
journal = SqliteJournal(path="helpdesk.db")
async with anthropic.AsyncAnthropic() as client:
model = AnthropicModel(client=client, model=os.environ["MODEL_ID"], max_tokens=4096)
governor = live_governor(model=model, journal=journal)
try:
agent = await Recovery(journal=journal).recover(run_id=run_name, actor_class=Agent)
result = await governor.resume(actor=agent)
except UnknownRun:
agent = new_refund_desk(run_name)
started = Event(name="started", payload={"prompt": complaint})
result = await governor.deliver(actor=agent, event=started)
while result.status() == WAITING:
request = result.pending()[0]
for call in request.payload()["calls"]:
print("wants", call["name"], call["arguments"])
answer = "approved" if input("approve? [y/n] ") == "y" else "denied"
result = await governor.answer(actor=agent, request=request, event=Event(name=answer))
await journal.close()
payload = result.outcome().payload()
print(payload.get("text", payload.get("reason")))
complaint = "Order A-17 arrived damaged three days ago. Please refund it."
asyncio.run(serve(ticket_id="4711", complaint=complaint))
Only live_governor differs from the build_governor of step 3, and only in its last
three arguments. The tools, the rules and the agent class are the ones you tested offline.
One run printed the lines below. The first sixteen lines, left out here, logged the model listing and reading the policy file and looking the order up. A model chooses its own words and its own order of calls, so yours will differ:
helpdesk-ticket-4711 event needs_approval -> awaiting_approval (to helpdesk-ticket-4711)
helpdesk-ticket-4711 waiting in awaiting_approval for request_approval
wants issue_refund {'order_id': 'A-17', 'amount': 40.0}
approve? [y/n] y
helpdesk-ticket-4711 event approved -> acting (to helpdesk-ticket-4711)
helpdesk-ticket-4711 request invoke_tools helpdesk-ticket-4711/21
helpdesk-ticket-4711 event tools_returned -> thinking (to helpdesk-ticket-4711)
helpdesk-ticket-4711 request invoke_model helpdesk-ticket-4711/25
helpdesk-ticket-4711 event model_replied -> completed (to helpdesk-ticket-4711)
helpdesk-ticket-4711 finished in completed
I refunded order A-17 in full: $40.00. Our policy refunds damaged orders in full within 30 days, and this one arrived three days ago.
Apart from the wants line, the prompt and the final answer, every line comes from
LoggingOutput: one per event, request, wait and finish. Run the file a second time and
this block prints two lines only, the finish and the answer, with no call to the vendor: the run named helpdesk-ticket-4711 is in helpdesk.db, so it is recovered,
found finished, and its answer printed again. Stop the program at the approve? prompt
instead, start it again, and it asks the same question: the wait is in the file, not in
the process.
Change it and run again¶
Predict the answer first, then run the code and open the block. Both checks run offline,
on the build_governor of step 3.
1. Ask for a refund the rules do not cover. A scripted model asks to refund 250.00.
small_refund is false for it, so no rule matches. Is a person asked? What does the
outcome's list of attempts say?
def refund_desk() -> Agent:
return Agent(
name="refund-desk",
instructions="Refund damaged orders.",
tools=[look_up_order, issue_refund],
)
def try_refund(amount: float) -> Result:
refund = ToolCall(
call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": amount}
)
model = ScriptedModel(
script=[
Reply(message=Message.assistant(calls=[refund])),
Reply(message=Message.assistant(text="Done.")),
]
)
return asyncio.run(build_governor(model=model).deliver(actor=refund_desk(), event=question))
large = try_refund(250.0)
attempt = large.outcome().payload()["attempts"][0]
print(large.status(), attempt["status"], "-", attempt["detail"])
small = try_refund(40.0)
print(small.status(), [request.kind().name() for request in small.pending()])
What happens
Nobody was asked about 250.00: a call no rule matches is forbidden, the tool did not
run, and the model was told so and answered. The 40.00 refund matches the approve
rule, so that run waits for a person.
2. Ask for a tool the agent was not offered. The help desk agent of step 3 was offered
the two reading tools. A scripted model asks it to write returns.md. What is the
attempt's status, and what is in the file afterwards?
write = ToolCall(
call_id="call-1", name="write_file", arguments={"path": "returns.md", "content": "No refunds."}
)
writing_model = ScriptedModel(
script=[
Reply(message=Message.assistant(calls=[write])),
Reply(message=Message.assistant(text="Done.")),
]
)
result = asyncio.run(build_governor(model=writing_model).deliver(actor=new_helpdesk(), event=question))
attempt = result.outcome().payload()["attempts"][0]
print(attempt["status"], "-", attempt["detail"])
print((policies / "returns.md").read_text())
What happens
unoffered - tool 'write_file' was not offered to this agent
Damaged orders are refunded in full within 30 days.
The status is unoffered, not forbidden: the call was refused before the policy was
asked, because write_file is in the toolbox and not among the agent's tools. The file
is unchanged.
Recap¶
- The model is a port: swapping
ScriptedModelforAnthropicModelorOpenAIModelchanges one object. gvn_toolsprovides confined, ready-made tools; each refuses what is outside its confinement, whatever the policy says.Rules().clear(...).approve(..., when=...)writes a policy in a few lines, over tool objects; anything not ruled is forbidden.- A
gvn-toolsfamily is a named tuple: pick a tool by attribute, pass the whole tuple where several are expected. - Offer an agent only the tools it needs.
- Every port has a real adapter in
gvn.adapters: a vendor model,SqliteJournalorPostgresJournal,SystemClock,LoggingOutputorTracingOutput. Swapping them in changes the Governor's arguments and nothing else.
Next: 13. Your own harness turns the help desk into a checklist for your own job, with a file to start from.
Going further: what a real call costs¶
The tutorial's main line ends with the recap above. This section is a second topic, for when your harness runs on a real model and you want to know what you pay for.
A real model is paid per token (the unit, a few characters long, that models count text
in), and an agent sends its whole prompt (tool descriptions,
instructions, the conversation so far) on every call. Two settings on AnthropicModel change
what you pay:
cache=True(the default) turns on prompt caching: the service keeps the prompt's prefix, and the next call that starts with the same bytes reads it from the cache at a fraction of the price.cache=Falseturns it off.effortasks the model to spend more or less work on a reply:None(the default) leaves the model's own default, otherwise one of"low","medium","high","xhigh"or"max". A model that does not accept a level fails the call.
# not runnable: it needs an API key and the network.
thrifty_model = AnthropicModel(
client=anthropic.AsyncAnthropic(),
model=os.environ["MODEL_ID"],
max_tokens=4096,
effort="low",
cache=True,
)
Every reply reports its tokens, and the Governor journals them with the model_replied
event. They come as four figures. Here is a reply with round figures close to the warm
fix-and-commit run on the Live runs page:
warm_reply = Reply(
message=Message.assistant(text="Fixed and committed."),
input_tokens=11470,
output_tokens=455,
cache_read_tokens=11330,
)
print(warm_reply.usage())
# {'input_tokens': 11470, 'output_tokens': 455, 'cache_read_tokens': 11330, 'cache_write_tokens': 0}
input_tokens counts every input token, read from the cache or not; cache_read_tokens and
cache_write_tokens are parts of it. So pricing a call takes four prices. With the Claude Haiku 5.5
list prices the live test uses (in dollars per million tokens):
def dollars(
usage: dict[str, int],
input_price: float,
cache_read_price: float,
cache_write_price: float,
output_price: float,
) -> float:
uncached = usage["input_tokens"] - usage["cache_read_tokens"] - usage["cache_write_tokens"]
per_million = (
uncached * input_price
+ usage["cache_read_tokens"] * cache_read_price
+ usage["cache_write_tokens"] * cache_write_price
+ usage["output_tokens"] * output_price
)
return round(per_million / 1_000_000, 5)
haiku_prices = {
"input_price": 0.10,
"cache_read_price": 0.01,
"cache_write_price": 0.125,
"output_price": 0.50,
}
print(dollars(usage=warm_reply.usage(), **haiku_prices)) # 0.00035
uncached = {**warm_reply.usage(), "cache_read_tokens": 0}
print(dollars(usage=uncached, **haiku_prices)) # 0.00137
Reading most of the prompt from the cache cut the cost to about a quarter. (The live run's
own figures, measured rather than rounded, are on the Live runs
page.) For a whole run,
Trace.usage() adds up every reply in the journal (a
trace is a recorded run read back event by event) (see
What the runs cost), and
Using a vendor model explains where the
cache markers go and how a model's thinking is carried between tool rounds.
In short: AnthropicModel caches the prompt by default and takes an effort. Usage has
four figures, and input_tokens counts every input token, cached or not.
Where to go from here¶
13. Your own harness is the last tutorial and the bridge to your own job. Beside it:
- A coding agent on your own repository puts the files, shell and git tools to work: an agent that edits a repository and runs its tests with a person's approval.
- The Concepts explain the model behind everything you used, in the same order, with the details the tutorials skipped.
- The Domains hold complete harnesses (customer service, research, software and more) to read or build on.
- Logs, traces and streams and Replay and evaluation are for running a harness in production and improving it safely.