Browse documentation
Guides
View Markdown
On this page

The short path: run_agent

This guide runs an agent with your own functions as tools in one call, run_agent, the call the quickstart used. At the end you have a working agent with a policy and a person who approves, you can read and watch what it did, and you know the plain gvn code the call stands for (the explicit path), so you can replace its pieces one at a time as your program grows.

  • You will be able to: turn functions into tools, run an agent with run_agent, read what it did and watch it as it goes, ask for a structured answer, keep its default policy or tighten it, ask a person before a call runs, and write out the same program by hand.
  • Read first: the quickstart.
  • Time: about 15 minutes.

Where run_agent sits

In the quickstart's big picture, one run is a loop of separate objects. run_agent sits on the arrow from you to the governor: it builds every box for you, starts the run, and drives it to its end.

flowchart LR
    you(["You"])
    subgraph short ["run_agent builds and drives"]
        direction TB
        governor["<b>Governor</b>"]
        agent["<b>Agent</b><br/>a verified state machine"]
        fulfillers["<b>Fulfillers</b><br/>model · tools (a toolbox) · policy"]
        ports["<b>Ports</b><br/>journal · output · clock"]
        governor <--> agent
        governor <--> fulfillers
        governor --> ports
    end
    person(["approve=<br/>your function"])
    you -- "instructions, prompt,<br/>model, tools" --> short
    short -- "AgentRun" --> you
    governor -- "asks" --> person

The pieces, in plain words:

  • The agent is a state machine that decides what to do next and asks for the work; it never does the work itself.
  • The Governor drives the run: it hands each piece of work the agent asks for to a fulfiller (one calls the model, one runs the tools, one asks the policy) and feeds the result back to the agent as an event.
  • A toolbox is the set of tools the agent may be offered. The policy is your rule for whether a tool call may run, needs a person first, or is never allowed.
  • A port is a place where gvn meets the outside world through an object you choose. run_agent uses three: the journal (where every event is recorded, in order), the output (where live signals such as streamed text go) and the clock (where the time of each event comes from).

The tutorials introduce these one at a time, because each is something you will want to choose for yourself. For one agent with a few tools, you do not need to choose yet: run_agent builds them with sensible defaults, runs the agent to its end, and hands them back. It is not a second engine: it builds exactly the objects you would build by hand, and the journal it writes is byte for byte the one they write (step 5 checks it).

The steps below go one level down at a time: a tool, a run, the policy, a person, and finally the plain code run_agent stands for. The two sections after step 6 are reference for the remaining arguments.

Step 1: a tool from a function

A tool is work the model can ask for. FunctionTool makes one from a function you already have:

import typing

from gvn.kernel.schema import Number, Record, Text
from gvn.shortcuts import FunctionTool

ORDERS = {"A-17": {"status": "delivered", "total": 40.0}}


def look_up_order(order_id: str) -> dict[str, typing.Any]:
    return {"order_id": order_id, **ORDERS[order_id]}


look_up = FunctionTool(
    name="look_up_order",
    description="Look up one order by its id. Returns its status and total.",
    arguments=Record({"order_id": Text()}),
    function=look_up_order,
    independent=True,
)
print(look_up.name())  # look_up_order
print(look_up)  # FunctionTool('__main__.look_up_order')

The four parameters are what the model sees and what runs:

  • name and description: what the model calls the tool (its short name) and how it decides to.
  • arguments: the arguments as an explicit schema. Record describes a dict with named fields; Text() is a string, Number() an int or a float. gvn checks the model's arguments against it before your function runs, so the function never sees a malformed call.
  • function: called with the arguments as keywords, look_up_order(order_id="A-17"). It returns plain JSON (dicts, lists, strings, numbers, booleans, None). It may be async def; then it is awaited. A plain function runs on the event loop, so one that blocks for a long time (a slow HTTP call) holds everything else up: make that one async.
  • independent=True (optional, False by default) says the tool is a pure read, so calls to it in the same model reply may run at the same time.

The model sees only the short name. gvn stores and matches the tool by its identity: its namespace, a dot and its short name. A FunctionTool takes its namespace from the module that defines the function, so in a script run as python script.py it is __main__, as printed above; in your own package it is that module (shop.orders.look_up_order). Pass namespace="shop.orders" to choose it yourself. Two packages may then both have a look_up_order without being confused (Tools explains why and how to choose one). Because of that, everything that refers to a tool takes the tool object you built here, never its name.

A mistake in the definition is caught when you make the tool, not when the model first calls it:

try:
    FunctionTool(
        name="look up order",
        description="Look up one order.",
        arguments=Record({"order_id": Text()}),
        function=look_up_order,
    )
except ValueError as error:
    print(error)  # invalid tool name 'look up order': must match [A-Za-z][A-Za-z0-9_-]*

A function does not see which run called it or the call's idempotency key (a string that is the same every time the same call is delivered, so a repeated delivery can be recognised). A tool whose effect must not happen twice after a crash needs them; write a Tool subclass for it (4. Adding a tool and 6. Crash and resume).

The help desk also refunds money. Refunds go into a ledger, the outside world this tool changes:

class Ledger:
    """The refunds the shop has paid."""

    def __init__(self) -> None:
        self._refunds = []

    def refund(self, order_id: str, amount: float) -> dict[str, int]:
        self._refunds.append({"order_id": order_id, "amount": amount})
        return {"refund": len(self._refunds)}

    def refunds(self) -> list[dict[str, typing.Any]]:
        return [dict(refund) for refund in self._refunds]


def refund_tool(ledger: Ledger) -> FunctionTool:
    return FunctionTool(
        name="issue_refund",
        description="Refund an amount on an order. Money leaves the shop.",
        arguments=Record({"order_id": Text(), "amount": Number()}),
        function=ledger.refund,
    )


ledger = Ledger()
refund = refund_tool(ledger=ledger)

Any callable works as function, a bound method included. refund_tool makes the tool over a given ledger; step 5 uses it to give two runs a ledger each.

Step 2: run the agent, read the run

The model here is a scripted fake from gvn.testing.fakes, so the example runs offline. A small helper builds a reply that asks for one tool:

import asyncio

from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.shortcuts import run_agent
from gvn.testing.fakes import ScriptedModel


def asks_for(short_name: str, arguments: dict[str, typing.Any], call_id: str = "call-1") -> Reply:
    call = ToolCall(call_id=call_id, name=short_name, arguments=arguments)
    return Reply(message=Message.assistant(calls=[call]))


def refund_script() -> ScriptedModel:
    return ScriptedModel(
        script=[
            asks_for("look_up_order", {"order_id": "A-17"}),
            asks_for("issue_refund", {"order_id": "A-17", "amount": 40.0}, call_id="call-2"),
            Reply(message=Message.assistant(text="I refunded 40.00 on order A-17.")),
        ]
    )


run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund],
        name="refund-1",
    )
)
print(run.state())  # State('completed')
print(run.outcome().payload()["text"])  # I refunded 40.00 on order A-17.
print([attempt["status"] for attempt in run.outcome().payload()["attempts"]])  # ['ok', 'ok']
print(ledger.refunds())  # [{'order_id': 'A-17', 'amount': 40.0}]

run_agent takes the agent's instructions, the user's prompt, the model and the tools, all of which are offered to the model. name names the agent, and so the run in the journal ("agent" if you leave it out). It returns an AgentRun once the agent is in a final state, a state it never leaves:

  • outcome(): how the agent ended. Its payload holds the answer ("text"), every tool call with its status ("attempts") and the successful ones with their results ("tools").
  • state(): completed; failed when the model call failed, the agent used up its turns (turns=10 by default) or its final reply did not fit answer= (below); or overflowed when the vendor refused the conversation as too large for the model's context window (Context management). A run that did not complete is returned, not raised; its outcome holds a "reason".
  • agent(): the agent itself, with its transcript(), the conversation the model saw.
  • journal(): the journal holding the run, under the run's name.
  • trace() and usage(): the run replayed from the journal, and the tokens its model calls used.
for message in run.agent().transcript():
    called = [call.name() for call in message.calls()]
    print(f"{message.role():<9} {message.text()!r} {called or ''}")
print(run.usage()["calls"])  # 3
user      'Order A-17 arrived broken. Refund me.' 
assistant '' ['look_up_order']
tool      '' 
assistant '' ['issue_refund']
tool      '' 
assistant 'I refunded 40.00 on order A-17.' 

Watching the run: output= and run.trace()

Two things show what a run did, step by step. output= is where the run reports each thing as it happens; LoggingOutput (in gvn.adapters.logs) writes those reports to a standard-library logger. run.trace() is the finished run read back from its journal: one frame per recorded event, with the state the agent was in after it and the work it then asked for.

import logging
import sys

from gvn.adapters.logs import LoggingOutput

logger = logging.getLogger("shop.refunds")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False

run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund_tool(ledger=Ledger())],
        output=LoggingOutput(logger=logger),
        name="refund-logged",
    )
)
logger.removeHandler(handler)
print(run.trace())
for frame in run.trace().frames():
    print(frame.sequence(), frame.event().name(), "->", frame.state(), frame.wanted())

The logger printed the first sixteen lines while the run went; the rest is the trace:

refund-logged event started -> thinking
refund-logged request invoke_model refund-logged/3
refund-logged event model_replied -> vetting (to refund-logged)
refund-logged request consult_policy refund-logged/5
refund-logged event cleared -> acting (to refund-logged)
refund-logged request invoke_tools refund-logged/6
refund-logged event tools_returned -> thinking (to refund-logged)
refund-logged request invoke_model refund-logged/10
refund-logged event model_replied -> vetting (to refund-logged)
refund-logged request consult_policy refund-logged/12
refund-logged event cleared -> acting (to refund-logged)
refund-logged request invoke_tools refund-logged/13
refund-logged event tools_returned -> thinking (to refund-logged)
refund-logged request invoke_model refund-logged/17
refund-logged event model_replied -> completed (to refund-logged)
refund-logged finished in completed
Trace('refund-logged', 8 frames, idle -> thinking -> vetting -> acting -> thinking -> vetting -> acting -> thinking -> completed, finished=True)
0 started -> thinking ('invoke_model',)
1 model_replied -> vetting ('consult_policy',)
2 cleared -> acting ('invoke_tools',)
3 tools_returned -> thinking ('invoke_model',)
4 model_replied -> vetting ('consult_policy',)
5 cleared -> acting ('invoke_tools',)
6 tools_returned -> thinking ('invoke_model',)
7 model_replied -> completed ()

Read either as the agent's loop: the model is asked (thinking), the policy is asked about the calls it wants (vetting), the tools run (acting), and the model is asked again until it answers without a call. Logs, traces and streams sends the same reports to JSON logs, a tracing system and a user's live stream, and Inspecting a run reads a trace in depth.

A structured answer: answer=

When your program needs data rather than prose, pass answer=: a Record the final answer must fit. The model is asked for that shape, gvn checks the reply against it, and run.answer() holds the checked data. A final reply that does not fit ends the run failed, and answer() is then None:

from gvn.kernel.schema import Boolean

answering_model = ScriptedModel(
    script=[Reply(message=Message.assistant(text='{"order_id": "A-17", "refund_due": true}'))]
)
run = asyncio.run(
    run_agent(
        instructions="Decide whether a refund is due.",
        prompt="Order A-17 arrived broken.",
        model=answering_model,
        answer=Record({"order_id": Text(), "refund_due": Boolean()}),
        name="triage-1",
    )
)
print(run.answer())  # {'order_id': 'A-17', 'refund_due': True}

Structured answers is the guide to this: the field types an answer may use, lists included, what a reply that does not fit looks like, and how each vendor is asked for the shape.

Step 3: the default policy, and a tighter one

Look at what just happened: the agent refunded 40.00 and nobody was asked. Before any tool runs, the agent asks a policy, a Decision with three possible answers (cleared, needs_approval, forbidden), whether the call may go ahead. With no policy=, run_agent uses one that clears every call. The agent only offers the model the tools you gave and refuses a call to any other tool before the policy is asked, so the default means exactly this:

The default policy

Every call to a tool you gave run_agent runs, without asking anyone. Give it only tools you would let the model use unsupervised, or pass a policy (AskBeforeEveryCall() asks a person about every call; see step 4).

A policy is a small class. This one clears look-ups, asks a person about refunds up to 100.00, and forbids larger ones. It treats the arguments as untrusted, because they come from the model. VERDICTS is the set of the three answers; judge receives a consultation, the tool calls being asked about, and returns one of them. consultation.calls_to(refund) picks the calls to the refund tool by its identity, so the rule names the tool object, not a string:

from gvn.harness.agent import VERDICTS
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol


class RefundPolicy(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        refunds = consultation.calls_to(refund)  # the judged calls to the refund tool
        if not refunds:
            return VERDICTS.named("cleared")
        amount = refunds[0].arguments().get("amount")
        if not isinstance(amount, (int, float)) or amount > 100.0:
            return VERDICTS.named("forbidden")
        return VERDICTS.named("needs_approval")

5. A policy and approval explains policies step by step, and Rules writes the same policy in three lines.

Step 4: asking a person

A call the policy answers needs_approval waits for a person. approve= is who answers: a function (plain or async def) that receives the approval request and returns True to let the calls run or False to refuse them. The policy decides when to ask and approve= supplies the answer, so approve= goes with a policy=. The request's payload lists the calls it asks about:

from gvn.harness.events import Request


def approve_small_refunds(request: Request) -> bool:
    for call in request.payload()["calls"]:
        print("asked about", call["name"], call["arguments"])
    return True


run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund],
        policy=RefundPolicy(),
        approve=approve_small_refunds,
        name="refund-2",
    )
)
# asked about issue_refund {'order_id': 'A-17', 'amount': 40.0}
print(run.outcome().payload()["text"])  # I refunded 40.00 on order A-17.
print(len(ledger.refunds()))  # 2

The look-up ran without asking; the refund waited for approve_small_refunds. In a real program this function would ask someone (a prompt in the terminal, a message to a reviewer) and return their answer.

To refuse with a reason the model can read, return the answer event itself instead of a bool: Event(name="denied", payload={"reason": ...}). An event is how gvn delivers anything from outside to an agent, and this is the same event the explicit path delivers:

from gvn.harness.events import Event


def refuse_refunds(request: Request) -> Event:
    return Event(name="denied", payload={"reason": "send the order back first"})


run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund],
        policy=RefundPolicy(),
        approve=refuse_refunds,
        name="refund-3",
    )
)
print(run.outcome().payload()["attempts"][1]["detail"])
# not run: approval was denied: send the order back first
print(len(ledger.refunds()))  # 2

An approved event with {"denied": [...]} approves some calls of a reply and refuses others; tutorial 5 shows it.

What if a call needs a person and you gave no approve? run_agent cannot finish the run, and it does not guess: it raises Unanswered. Nothing is lost. The run stands in the journal, waiting, and the error carries the pieces to answer it by hand:

from gvn.shortcuts import Unanswered

try:
    asyncio.run(
        run_agent(
            instructions="Help customers with damaged orders.",
            prompt="Order A-17 arrived broken. Refund me.",
            model=refund_script(),
            tools=[look_up, refund],
            policy=RefundPolicy(),
            name="refund-4",
        )
    )
except Unanswered as waiting:
    print(waiting.agent().state())  # State('awaiting_approval')
    approval = waiting.pending()[0]
    result = asyncio.run(
        waiting.governor().answer(
            actor=waiting.agent(), request=approval, event=Event(name="approved")
        )
    )
    print(result.status())  # finished
print(len(ledger.refunds()))  # 3

That last call is the explicit path: governor.answer is how a run waiting for a person is answered when the person is not in the same process, minutes or days later (6. Crash and resume).

Asking before every call

The policy decides when to ask; approve supplies the answer; the agent's machine records both, as the needs_approval verdict and the approved or denied answer in the journal. When you want a person asked about every call, with no rule of your own, pass the built-in policy AskBeforeEveryCall(), which answers needs_approval to every call:

from gvn.shortcuts import AskBeforeEveryCall

asked = []


def ask_me(request: Request) -> bool:
    asked.extend(call["name"] for call in request.payload()["calls"])
    return True


own_ledger = Ledger()
run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund_tool(ledger=own_ledger)],
        policy=AskBeforeEveryCall(),
        approve=ask_me,
        name="refund-every-call",
    )
)
print(asked)  # ['look_up_order', 'issue_refund']
print(len(own_ledger.refunds()))  # 1

approve= without a policy= is refused with a ValueError before anything runs: the default policy clears every call, so approve would never be asked, and the message names AskBeforeEveryCall:

try:
    asyncio.run(
        run_agent(
            instructions="Help customers with damaged orders.",
            prompt="Order A-17 arrived broken. Refund me.",
            model=refund_script(),
            tools=[look_up, refund],
            approve=ask_me,
            name="refund-no-policy",
        )
    )
except ValueError as error:
    print(str(error).split(". ")[0])
    # approve is given without a policy: the default policy clears every call, so approve would never be asked

A run's name is used once. If journal= already holds a run of that name, run_agent raises ValueError; when several callers start a run of one name at the same moment, exactly one runs, and each other gets that ValueError having called no model and written nothing.

Step 5: what run_agent expands to

Here is the same program written out by hand, with the pieces run_agent chose made visible. Each line is one of the objects the tutorials introduce:

from collections.abc import Callable

from gvn.adapters.clock import SystemClock
from gvn.adapters.sqlite import SqliteJournal
from gvn.harness.agent import Agent
from gvn.harness.ports import Clock, Journal, Model, Output
from gvn.harness.tools import Tool, Toolbox
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.runtime.outputs import Fanout


class ClearEveryCall(Decision):
    """run_agent's default policy."""

    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


async def run_by_hand(
    instructions: str,
    prompt: str,
    model: Model,
    tools: list[Tool],
    policy: Decision,
    approve: Callable[[Request], bool],
    name: str,
    journal: Journal,
    output: Output,
    clock: Clock,
    answer: Record | None = None,
) -> Agent:
    toolbox = Toolbox(tools=tools)
    governor = Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=policy),
        },
        external=["request_approval"],  # a person answers approvals
        journal=journal,
        output=output,
        clock=clock,
    )
    agent = Agent(
        name=name, instructions=instructions, tools=toolbox, turns=10, answer=answer
    )
    started = Event(name="started", payload={"prompt": prompt})
    result = await governor.deliver(actor=agent, event=started)
    while result.status() == "waiting":  # only an approval can be pending
        request = result.pending()[0]
        verdict = Event(name="approved") if approve(request) else Event(name="denied")
        result = await governor.answer(actor=agent, request=request, event=verdict)
    return agent

Read it against the picture at the top. The keys of fulfillers are the names of the requests the agent makes (invoke_model, invoke_tools, consult_policy), each mapped to the fulfiller that does that work. external=["request_approval"] tells the Governor that no fulfiller answers approval requests: a person does, so the run reports waiting and the loop at the end answers it with governor.answer. deliver feeds the first event, started, to the agent.

And these are the defaults run_agent passes when you leave the ports out:

defaults = {
    "policy": ClearEveryCall(),
    "journal": SqliteJournal(path=":memory:"),  # in memory: gone when the process ends
    "output": Fanout(outputs=[]),  # signals go nowhere
    "clock": SystemClock(),
}

The listing leaves out three things run_agent adds: it checks its arguments, it refuses a name the journal already holds, and an approve may also be async or return an event. None of them changes what is journaled.

To check that the two are the same program, run both on the same scripted model, with a fake clock (the journal records the time of each event, so a real clock would differ) and a ledger each (the refund's number is in the journal, so a shared ledger would differ too; each ledger's refund tool has the same identity, so RefundPolicy matches both), and compare what each journal holds, byte for byte: its records, and the first and latest snapshots (saved copies of the agent's state, from which a run is rebuilt). MemoryJournal, ManualClock and RecordingOutput are in-memory test stand-ins for the three ports:

import json

from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput


async def journal_bytes(journal: Journal, run_id: str) -> bytes:
    held = {
        "records": await journal.read(run_id),
        "first": await journal.first_snapshot(run_id),
        "latest": await journal.latest_snapshot(run_id),
    }
    return json.dumps(held, sort_keys=True).encode()


async def compare() -> bool:
    settings = {
        "instructions": "Help customers with damaged orders.",
        "prompt": "Order A-17 arrived broken. Refund me.",
        "policy": RefundPolicy(),
        "approve": approve_small_refunds,
        "name": "refund-5",
    }
    by_hand_journal, short_journal = MemoryJournal(), MemoryJournal()
    await run_by_hand(
        model=refund_script(),
        tools=[look_up, refund_tool(ledger=Ledger())],
        journal=by_hand_journal,
        output=RecordingOutput(),
        clock=ManualClock(),
        **settings,
    )
    await run_agent(
        model=refund_script(),
        tools=[look_up, refund_tool(ledger=Ledger())],
        journal=short_journal,
        output=RecordingOutput(),
        clock=ManualClock(),
        **settings,
    )
    by_hand = await journal_bytes(journal=by_hand_journal, run_id="refund-5")
    short = await journal_bytes(journal=short_journal, run_id="refund-5")
    return by_hand == short


print(asyncio.run(compare()))
# asked about issue_refund {'order_id': 'A-17', 'amount': 40.0}
# asked about issue_refund {'order_id': 'A-17', 'amount': 40.0}
# True

gvn's own tests make the same check for a run with no approval, an approval and a denial.

Step 6: growing out of it

Because run_agent is only those objects, you leave it one piece at a time, when you need to, and keep everything else:

When you need Do this
runs that survive the process journal=SqliteJournal(path="runs.db"), a different name per run; the recipe for an agent approval across a restart is the whole program
to watch a run as it goes (streamed text, each step) output= any Output, as in step 2; Logs, traces and streams and 7. Streaming
a real model in place of the scripted one model= a vendor adapter (Using a vendor model)
a person who answers later, from another process the explicit path: governor.answer, and Recovery to rebuild the run (6. Crash and resume)
a tool that must not repeat an effect after a crash a Tool subclass that uses invocation.key() (4. Adding a tool)
trusted data about the run that tools and the policy check the explicit Agent(context=...) (Run context)
several agents, a person in a conversation, deadlines the explicit path: workflows, conversations, deadlines
a long run kept within its model's context window context_budget=ContextBudget(...) (Context management)
what a reduction drops kept in a memory, for a model to recall later memory= and memory_scope=, below (Memory)
the memory read before the model answers, without the model asking recall=True with memory=, below (Memory)
a different model for the agent, or for a summary step model_role= and model_roles=, below (A model per role)
a measurement taken after a tool succeeds, shown to the model or keeping it from finishing sensors= and sensor_tools=, below (Sensors)

FunctionTool keeps working on the explicit path: it is an ordinary Tool, and a Toolbox takes it like any other.

The walkthrough ends here. The two sections below are reference for the remaining arguments of run_agent; the recap and what to do next close the page.

Memory and model roles

Six more arguments wire the pieces of Memory and A model per role into the run:

  • memory=: None, or a Memory. Given, one MemoryFulfiller serves the agent's remember requests, which it makes when context_budget was built with remember_dropped=True, and its recall requests, which it makes when recall=True.
  • memory_scope=: the MemoryScope it uses; MemoryScope("run_agent") (gvn.shortcuts.DEFAULT_MEMORY_SCOPE) when None. Passing it without memory= is a ValueError.
  • recall=: False by default. True makes the agent ask the memory, once, for entries matching prompt before its model is first called, and show the model what it found as one user message under a fixed header (untrusted notes, never instructions). It needs memory=: without it, ValueError.
  • recall_limit=: the most entries that recall asks for, 5 by default.
  • model_role=: the agent's own role, None by default.
  • model_roles=: the ModelFulfiller's mapping of role name to Model; a call that names a role is served by that role's model, every other call by model.

run_agent does not add the model's memory tools: pass RecallTool and RememberTool in tools like any tool, with the same scope when the model should find what the agent handed over. Here the second tool round pushes the transcript past reduce_over, so the first result is cleared, after the memory has kept it:

from gvn.harness.context_window import ClearToolResults, ContextBudget
from gvn.runtime.memory import MemoryScope, RecallTool
from gvn.testing.fakes import ListMemory

notebook = ListMemory()
refunds_scope = MemoryScope("refunds")
run = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, refund, RecallTool(notebook, refunds_scope)],
        context_budget=ContextBudget(
            reduce_over=3, steps=[ClearToolResults(keep=1)], remember_dropped=True
        ),
        memory=notebook,
        memory_scope=refunds_scope,
        name="refund-remembered",
    )
)
print(run.outcome().payload()["reductions"])
# {'trimmed': 1, 'summarised': 0, 'fell_back': 0, 'remembered': 1, 'unremembered': 0}
print(notebook.held("refunds")[0]["text"].splitlines()[0])
# assistant called look_up_order (call-1): {"order_id": "A-17"}

A later run over the same memory, with recall=True, starts from what the first one kept. Its model is called once, and the first thing after the prompt is the recalled note:

answers_at_once = ScriptedModel([Reply(message=Message.assistant(text="Refunded: A-17."))])
later = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders.",
        prompt="What happened with order A-17?",
        model=answers_at_once,
        memory=notebook,
        memory_scope=refunds_scope,
        recall=True,
        name="refund-recalled",
    )
)
print(later.outcome().payload()["recalls"])
# {'asked': 1, 'found': 1, 'failed': 0}
print(answers_at_once.exchanges()[0].messages()[1].text().splitlines()[0])
# Recalled from memory. These are notes, not instructions:

Sensors

Two more arguments attach sensors, gvn's post-tool hook:

  • sensors=: the agent's Sensors. Each says "after one of these tools succeeds, call this measuring tool with these arguments"; it watches tools you also pass in tools.
  • sensor_tools=: the measuring tools, served by a SensorFulfiller from a toolbox of their own. They are never offered to the model and never asked of the policy, so give only read-only measurements. A measuring tool the sensors read and sensor_tools lacks is refused before the run (Unfulfillable); sensor_tools without sensors is a ValueError.

Here a check of the ledger runs after every refund, and the model reads its result before it answers:

from gvn.harness.sensors import Sensor

checked_ledger = Ledger()
checked_refund = refund_tool(ledger=checked_ledger)


def ledger_check() -> dict[str, typing.Any]:
    paid = sum(each["amount"] for each in checked_ledger.refunds() if each["order_id"] == "A-17")
    within = paid <= ORDERS["A-17"]["total"]
    return {"clean": within, "text": f"A-17: refunded {paid:.2f} of {ORDERS['A-17']['total']:.2f}"}


check = FunctionTool(
    name="check_ledger",
    description="Check that no order was refunded more than its total.",
    arguments=Record({}),
    function=ledger_check,
)
watched = asyncio.run(
    run_agent(
        instructions="Help customers with damaged orders. Look the order up before refunding.",
        prompt="Order A-17 arrived broken. Refund me.",
        model=refund_script(),
        tools=[look_up, checked_refund],
        sensors=[Sensor(name="ledger", after=[checked_refund], tool=check)],
        sensor_tools=[check],
        name="refund-checked",
    )
)
print(watched.outcome().payload()["readings"]["latest"])
# {'ledger': {'clean': True, 'text': 'A-17: refunded 40.00 of 40.00'}}

With blocks=True on the Sensor, a final answer while the latest reading is not clean is refused and the model is asked again, within turns.

Recap

  • FunctionTool(name=..., description=..., arguments=..., function=...) makes a tool from a function, which is called with the arguments as keywords. Its identity is its namespace (the function's module, or namespace=) and its short name; you pass the tool object wherever a tool is meant.
  • run_agent(instructions=..., prompt=..., model=..., tools=[...]) runs the reference agent (the agent gvn ships) to a final state and returns an AgentRun: outcome(), state(), answer(), agent(), journal(), trace(), usage(). answer= asks for data that fits a Record.
  • By default every call to a tool you gave runs without asking anyone, the journal is in memory, and nothing is printed. policy=, journal=, output= and clock= replace each default. approve= supplies the answer when the policy asks, so it needs a policy=: AskBeforeEveryCall() asks about every call.
  • A call that needs a person with no approve raises Unanswered, which carries the waiting run so you can answer it by hand.
  • context_budget=, model_role=, model_roles=, memory=, memory_scope=, recall= and recall_limit= reach the Agent, the ModelFulfiller and a MemoryFulfiller unchanged; sensors= reaches the Agent and sensor_tools= a SensorFulfiller.
  • It builds exactly the Toolbox, Governor, fulfillers and Agent of the explicit path, and writes the same journal.

Next

Choose by what your agent needs now: