Browse documentation
Python API
View Markdown
On this page

gvn.shortcuts

The short path: one agent, some tools and a model, run to the end in one call. Start here, and move to the packages below when you need to pause, recover or compose.

The ideas behind it are explained in Run your first agent, Quickstart. This page is generated from the source, so it lists every public name with its signature and docstring. Python API has the other packages and an index of every name.

gvn.shortcuts

The short path: one agent, some tools, a model, run to the end in one call.

import asyncio
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import FunctionTool, run_agent

def look_up_order(order_id: str) -> dict[str, str]:
    return {"order_id": order_id, "status": "shipped"}

look_up = FunctionTool(
    name="look_up_order",
    description="Look up one order by its id.",
    arguments=Record({"order_id": Text()}),
    function=look_up_order,
)
run = asyncio.run(run_agent(instructions="...", prompt="...", model=model, tools=[look_up]))
print(run.outcome().payload()["text"])

This module is a stateless convenience over the explicit classes, not a second way of running things. run_agent builds exactly what you would wire by hand: a Toolbox, a Governor with ModelFulfiller, ToolFulfiller and PolicyFulfiller and request_approval external, a reference Agent, and a started event; it then delivers the event and answers approvals until the agent reaches a final state. Same machine, same journal records: a test checks that the short and the explicit path write identical journals. Each default can be replaced by passing the explicit piece:

journal   SqliteJournal(path=":memory:"): kept for this process only. Pass
          SqliteJournal(path="runs.db") (or any Journal) to keep runs.
output    Fanout(outputs=[]): signals go nowhere. Pass any Output to see them.
clock     SystemClock().
policy    clears every call. The agent offers the model only the tools given, and
          refuses a call to any other name before the policy is asked, so this means
          "every call to one of the tools you gave runs, without asking anyone".
          Pass any Decision over gvn.harness.agent.VERDICTS to tighten it;
          ``AskBeforeEveryCall()`` asks ``approve`` before every call. Because the
          default never asks, ``approve`` without ``policy`` is refused (ValueError)
          before anything runs: it could never be called.
memory    none: a ``remember`` request is refused as unfulfillable (the Governor
          raises Unfulfillable). Pass memory= (and memory_scope=) for a
          ``MemoryFulfiller``, wired for both ``remember`` and ``recall``.
sensors   none. Pass sensors= (gvn.harness.sensors.Sensor) and sensor_tools= (the
          measuring tools) for a ``SensorFulfiller`` over its own toolbox.

Nothing inside gvn imports this module (an import contract holds it to the outside).

Constants: VERDICTS, WAITING, DEFAULT_MEMORY_SCOPE.

FunctionTool

from gvn.shortcuts import FunctionTool
FunctionTool(
    name: str,
    description: str,
    arguments: Record,
    function: Callable[..., object],
    independent: bool = False,
    retry: Retry | None = None,
    namespace: str | None = None,
) -> None

A Tool whose work is a plain function, called with the arguments as keywords.

name, description and arguments (a gvn.kernel.schema.Record) are what a Tool subclass returns from the methods of the same names. function is any callable, sync or async: it is called as function(**arguments) with arguments already checked against arguments, and returns plain JSON (awaited first if it returns an awaitable); whatever it returns goes to the runtime unchanged, exactly as a Tool.run result would. A sync function runs on the event loop, so one that blocks for long holds every other call up; make it async. independent is what Tool.independent() returns: True only for a pure read. retry is what Tool.retry() returns: None (one attempt) or a gvn.harness.ports.Retry, given only when calling function again after a retryable ToolFailure is safe. namespace: None (the module that defines function, its __module__) or a dotted identifier ("billing.orders"): the tool's identity is namespace + "." + name. One class backs every FunctionTool, so the namespace comes from the function, not from this class.

The function does not see the Invocation (its idempotency key, the run's context). A tool whose effect must not repeat after a crash needs them: write a Tool subclass instead.

TypeError/ValueError at construction for a bad name, an empty description, arguments that are not a Record, a function that is not callable, an independent that is not a bool, a retry that is neither None nor a Retry, or a namespace that is not a dotted identifier (or a function whose __module__ is not one, with no namespace).

FunctionTool.name

name() -> str

The short name the model sees and calls. Matches [A-Za-z][A-Za-z0-9_-]*. Unique among the tools one actor is offered; a Toolbox may hold same-named tools of different identities.

FunctionTool.namespace

namespace() -> str

Where the tool comes from, a dotted identifier: the module that defines the tool's class (type(self).__module__) unless a tool overrides it. A tool class that backs many tools (one per configuration) takes a namespace at construction, so tools of one class configured apart have different identities.

FunctionTool.description

description() -> str

What the tool does, written for the model.

FunctionTool.arguments

arguments() -> Record

A gvn.kernel.schema.Record describing the arguments dict.

FunctionTool.independent

independent() -> bool

True when a call to this tool neither depends on nor affects any other call in the same reply (a pure read). Independent calls next to each other may run at the same time; everything else runs in the order the model asked.

False unless a tool overrides it. Must return a bool (the Toolbox checks).

FunctionTool.retry

retry() -> Retry | None

How a call of this tool is tried again when it fails retryably: None (one attempt) or a gvn.harness.ports.Retry (how many attempts in all, how long to wait between them). Constant for the tool's life.

The retry belongs to the tool because only the tool knows whether repeating a call is safe. Every attempt carries the same Invocation, so the same idempotency key: a tool should declare a Retry only when a repeat under that key is harmless (a pure read, or a service that honours the key). A search may deserve five attempts and a payment none. Only a ToolFailure with retryable=True is ever retried.

None unless a tool overrides it. The ToolFulfiller checks what it returns: anything other than None or a Retry is a TypeError naming the tool (a broken tool definition, not a failed call).

FunctionTool.run

async def run(arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any

Do the work. arguments already satisfies arguments(). Returns plain JSON, or a ToolOutput when the model should also see images or documents (a screenshot): its content is the result's JSON and its attachments go to the model after it.

invocation is the Invocation: which run asked (invocation.origin()), with what trusted data (invocation.context()), under which idempotency key (invocation.key()). A tool that must stay within the run's data (only this alert's hosts, only this customer) checks invocation.context() and raises rather than act outside it.

invocation.key() is a non-empty str that identifies this call: it is the same every time the same call of the same run is (re)issued, and different for every other call. Work is delivered at least once, so after a crash the same call may run again with the same key. A tool with side effects should use the key to make repeats harmless, for example by passing it to the service it calls as that service's idempotency key, or by remembering the keys it has completed (in storage that outlives the process) and not repeating them.

What the key does not cover. An Agent that is interrupted after a tool acted, and then resumed, asks its model again: the next call is a new call with a new key, even when it asks for the same thing. (An Errand's batch is fixed, so its keys stay the same across interrupt and resume.) An effect that must happen at most once whatever happens to the run (a payment, a deployment, a signature) should therefore be keyed by what it is, built from the trusted invocation.context() (for example "promote:<service>:<version>"), not by invocation.key() alone.

Failure. A tool that understands why a call failed raises ToolFailure: retryable=True when the service could not be reached or asked to wait (an outage, a timeout, a rate limit; pass its retry_after when it gave one), retryable=False (the default) when it answered and refused (not found, not permitted, invalid for the service, a business rule). The runtime turns it into a failed ToolResult of kind tool_rejected or tool_unavailable, and may run a retryable call again under the same invocation.key() (when the tool declares a retry()), which a tool already tolerates. Any other exception is reported as tool_raised: a defect in the tool, never retried. See TOOL_ERRORS.

AskBeforeEveryCall

from gvn.shortcuts import AskBeforeEveryCall
AskBeforeEveryCall()

A policy under which every tool call needs a person's approval first: the verdict for every call is needs_approval.

run = await run_agent(..., policy=AskBeforeEveryCall(), approve=ask_me)

The policy decides when to ask, approve supplies the answer, and the agent's machine records both: the needs_approval verdict and the approved or denied answer are events in the journal. Takes no arguments; every instance is equal to every other and hashes alike. Usable with a PolicyFulfiller on the explicit path as well.

AskBeforeEveryCall.outcomes

outcomes() -> Alphabet

The Alphabet of every answer this decision can give. Must not vary over time.

AskBeforeEveryCall.judge

judge(consultation: object) -> Symbol

Inspect subject and return one Symbol from outcomes().

Unanswered

from gvn.shortcuts import Unanswered
Unanswered(
    message: str,
    agent: Agent,
    governor: Governor,
    journal: Journal,
    pending: Iterable[Request],
) -> None

The run waits on a request that nobody given to run_agent can answer.

Raised when the policy asks for approval and no approve was given. Nothing is lost: the run stands in the journal, waiting, and the pieces are here to answer it the explicit way, await error.governor().answer(actor=error.agent(), request=error.pending()[0], event=Event(name="approved")).

Unanswered.agent

agent() -> Agent

The Agent, in the state it waits in.

Unanswered.governor

governor() -> Governor

The Governor that drove it; answer through it.

Unanswered.journal

journal() -> Journal

The Journal holding the run so far.

Unanswered.pending

pending() -> tuple[Request, ...]

The requests the run waits on (a tuple of Request).

AgentRun

from gvn.shortcuts import AgentRun
AgentRun(agent: Agent, journal: Journal, trace: Trace) -> None

A run of run_agent that reached a final state. Immutable.

outcome() is the Agent's Outcome; state() its final State (completed, failed or overflowed: a model failure, exhausted turns, an invalid structured answer or an exhausted context budget end the run, they do not raise); answer() the validated structured answer (the outcome's "answer"; None when the run was given no answer or did not complete); agent() the Agent (its transcript()); journal() the Journal the run is in, under the agent's name; trace() the run replayed from that journal (gvn.runtime.replay.Trace); usage() the tokens its model calls used, trace().usage().

AgentRun.outcome

outcome() -> Outcome

AgentRun.state

state() -> State

AgentRun.answer

answer() -> typing.Any

AgentRun.agent

agent() -> Agent

AgentRun.journal

journal() -> Journal

AgentRun.trace

trace() -> Trace

AgentRun.usage

usage() -> dict[str, int]

run_agent

from gvn.shortcuts import run_agent
async def run_agent(
    instructions: str,
    prompt: str,
    model: Model,
    tools: Toolbox | Iterable[Tool] = (),
    policy: Decision | None = None,
    approve: Callable[[Request], object] | None = None,
    name: str = 'agent',
    turns: int = 10,
    answer: Record | None = None,
    journal: Journal | None = None,
    output: Output | None = None,
    clock: Clock | None = None,
    context_budget: ContextBudget | None = None,
    model_role: str | None = None,
    model_roles: Mapping[str, Model] | None = None,
    memory: Memory | None = None,
    memory_scope: MemoryScope | None = None,
    recall: bool = False,
    recall_limit: int = 5,
    sensors: Iterable[Sensor] = (),
    sensor_tools: Toolbox | Iterable[Tool] = (),
) -> AgentRun

Run one reference Agent to a final state and return an AgentRun.

instructions and prompt (str): the agent's instructions and the user's message. model: a Model (a fake from gvn.testing, or a vendor adapter). tools: Tools (FunctionTool or your own subclasses) or a Toolbox, never names (a str is a TypeError); the agent is offered all of them, and two with one short name are a ValueError. policy: None (clear every call; see the module docstring) or a Decision over VERDICTS. approve: None, or a callable (sync or async) asked approve(request) with each request_approval Request; it returns True (approve), False (deny) or the Event to answer with (approved with {"denied": [...]}, denied with {"reason": ...}). name: the agent's name, which is the run's id in the journal. turns: model turns allowed. answer: None, or a kernel Record the final answer must fit (the Agent's answer); the validated data is AgentRun.answer(). context_budget: None (nothing is reduced) or a gvn.harness.context_window.ContextBudget, the Agent's own context_budget; a summary call it makes is a model call like any other, in the journal and in AgentRun.usage(). model_role: None, or the role the Agent names in its model calls (the Agent's own model_role). model_roles: None, or a mapping of role name to Model for the ModelFulfiller (its roles): a call naming a role is served by that role's model, every other call by model. memory: None, or a gvn.harness.ports.Memory; given, a gvn.runtime.memory.MemoryFulfiller serves the agent's remember requests (made when context_budget was built with remember_dropped=True) under memory_scope: a MemoryScope, DEFAULT_MEMORY_SCOPE (MemoryScope("run_agent")) when None. memory_scope without memory is a ValueError. The model's own tools for memory are not added: pass RecallTool / RememberTool in tools like any tool, each with its scope (the same one, to share what the agent itself remembers). recall: a bool, the Agent's own recall: True asks the memory for at most recall_limit entries matching prompt before the model is first called, and shows the model what it finds as one user message under the fixed header gvn.harness.context_window.RECALLED (untrusted notes, never instructions); it needs memory (ValueError without it). The same MemoryFulfiller serves remember and recall. sensors: the Agent's own sensors (gvn.harness.sensors.Sensor, each watching tools in tools). sensor_tools: the measuring Tools (or a Toolbox) they read, served by a SensorFulfiller over a toolbox of their own: never offered to the model, never asked of the policy, so give only read-only measurements. Given sensors, a sensor tool they read that sensor_tools lacks is refused before the run (Unfulfillable); sensor_tools without sensors is a ValueError. journal, output, clock: the ports, defaulted as the module docstring says.

Raises Unanswered when the run waits on a request and no approve was given; ValueError when approve is given and policy is not (the default policy clears every call, so approve would never be asked; the message names AskBeforeEveryCall), raised with the other argument checks, before the journal is read or anything runs; ValueError when journal already holds a run called name (a run's id is used once), and equally when another caller begins a run of that name at the same moment: exactly one of them runs, and each other gets this ValueError having called no model or tool and written nothing to the journal; TypeError/ValueError for bad arguments (from the classes it builds); whatever approve or the Governor raises.