# Quickstart

**In about ten minutes** you will see how gvn fits together, build a small state machine
that gvn checks for you, and run an agent that calls a function you wrote. Every term in
bold is explained where it first appears. You need gvn
[installed](install.md). Nothing here needs an API key or the network until the last step.

## The big picture

An AI model on its own only turns text into text. An **agent** is a program that puts a
model in a loop: it asks the model what to do next, does it, and reports back, until the job
is done. The code that runs that loop, calls the model, does the work and keeps the records
is called a **harness**. gvn is a harness.

A **state machine** is a way of writing down control flow as a list of **states** (the
situations the program can be in), **inputs** (the things that can happen), and a rule for
each: "in this state, when this happens, go to that state".

gvn's one central idea joins the two:

> **Control flow is a state machine that is checked before it runs.** Every non-final state
> needs a route or fallback for each declared input. gvn names any missing cases.

Everything else is arranged around that machine. This is the whole of gvn in one picture:

```mermaid
flowchart LR
    you(["You, or your application"])
    person(["A person who approves"])
    subgraph run ["One run"]
        direction TB
        governor["<b>Governor</b><br/>drives the run"]
        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><br/>every event, in order")]
    you -- "event: started" --> governor
    governor -- "request" --> fulfillers
    fulfillers -- "event" --> governor
    governor -- "records" --> journal
    governor -- "asks" --> person
    person -- "event: approved or denied" --> governor
```

Read it as a loop:

1. Something happens: you start a run, a model replies, a tool returns. Each of these is an
   **event**.
2. The **governor** hands the event to the **actor** for a pure state transition, then appends
   the event to the **journal** before starting any resulting work.
3. The actor is a **state machine**. The event is its input: it moves to its next state.
4. The new state says what work is needed next. That is a **request**: "call the model",
   "run this tool", "ask a person".
5. The governor gives the request to the **fulfiller** for that kind of work. There is one
   for calling the model, one for running **tools** (functions of yours that the model may
   ask for), and one for the **policy** (your rule for whether a tool call may run, or must
   first be approved by a person). The result comes back as the next event.
6. The Governor returns a finished result at a **final state**, or a waiting result when
   the actor remains unfinished and no work can run now.

```mermaid
sequenceDiagram
    participant App as Application
    participant G as Governor
    participant A as Actor
    participant J as Journal
    participant F as Model, policy, or tool
    App->>G: Deliver an event
    G->>A: handle(event)
    A-->>G: State transition and pending requests
    G->>J: Append the event
    loop While internal work is pending
        G->>F: Fulfill a request
        F-->>G: Return an event
        G->>A: handle(event)
        G->>J: Append the event
    end
    G-->>App: Finished or waiting result
```

The actor can decide before the append because it performs no I/O. The Governor starts
the effects only after the append succeeds.

The words in that loop are the core concepts:

| Concept | What it is | You meet it in |
|---|---|---|
| **State machine** | States, inputs, and what each input does in each state. Checked for completeness before it runs. | step 1 |
| **Actor** | A state machine with a job: an agent, a workflow, a conversation. It only decides; it never does the work itself. | step 3 |
| **Event** and **request** | An event is something that happened, fed to the machine as an input. A request is work the machine asks for. | steps 2 and 3 |
| **Governor** and **fulfillers** | The governor drives the loop. A fulfiller does one kind of work: call a model, run a tool, ask the policy. | step 3 |
| **Journal** | The ordered record of every event. A run can be rebuilt from it after a crash. | step 3 |

The machine never calls a model or a tool. It only moves between states and asks. That
separation is what makes a run checkable, replayable and safe to resume.

The rest of this page goes one level down at a time: first a machine on its own, then the
same machine taking inputs, then a real agent running the whole loop.

## Step 1: build a machine, and let gvn find the gaps

Start with the smallest version of an assistant. It waits for a question, thinks, may use a
tool, and answers:

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> thinking: asked
    thinking --> acting: tool_wanted
    acting --> thinking: tool_returned
    thinking --> answered: answer_ready
    answered --> [*]
```

A **blueprint** is how you describe a machine to gvn. This one declares the four states, the
four inputs, and the four arrows in the diagram. Each state also names an **output**: the
work that state asks for.

Save this as `quickstart_machine.py` and run `python quickstart_machine.py`:

```python
from gvn.kernel.blueprint import MooreBlueprint

draft = (
    MooreBlueprint(name="assistant")
    .inputs("asked", "tool_wanted", "tool_returned", "answer_ready")
    .outputs("wait", "call_model", "run_tool", "reply")
    .state(name="idle", output="wait")
    .state(name="thinking", output="call_model")
    .state(name="acting", output="run_tool")
    .state(name="answered", output="reply", final=True)
    .initial(name="idle")
    .on(source="idle", input="asked", target="thinking")
    .on(source="thinking", input="tool_wanted", target="acting")
    .on(source="acting", input="tool_returned", target="thinking")
    .on(source="thinking", input="answer_ready", target="answered")
)

for finding in draft.examine():
    print(finding.code(), finding.subject())
```

The diagram looks finished. gvn's **verifier** disagrees, and lists every gap:

```text
incomplete acting/answer_ready
incomplete acting/asked
incomplete acting/tool_wanted
incomplete idle/answer_ready
incomplete idle/tool_returned
incomplete idle/tool_wanted
incomplete thinking/asked
incomplete thinking/tool_returned
```

Each line is a question the diagram never answered. Take `acting/asked`: the assistant is
running a tool and the user's question arrives a second time, because a button was clicked
twice. What happens? In a hand-written loop, that case is whatever the code happens to do. In
gvn it must be decided, by you, before anything runs.

A machine where every state answers every input is called **complete**. This is the key
property of gvn: the unhandled case is found now, not in production.

Here the right answer for all eight gaps is "ignore it and stay where you are".
`otherwise_stay()` says that once, explicitly. When an unexpected input should count as a
fault instead, [you can send it to a failure state](concepts/machines.md#choosing-what-happens-otherwise).
Add these lines:

```python
assistant = draft.otherwise_stay().build()
print(assistant)
```

```text
Definition('assistant', moore, fc368a074f32)
```

`build()` runs the verifier again. It finds nothing this time and returns a **definition**:
the checked, unchangeable form of your machine. The printed line has three parts: its name;
`moore`, the style of machine, meaning each *state* names the work that is due (the only
style this page uses); and a **fingerprint**, a short code computed from everything in the
machine, so two definitions with the same fingerprint are the same machine. Had anything been missing, `build()` would have raised an error listing every finding.

!!! note "Completeness is one of several checks"
    The verifier also refuses a state no path can reach, an input nothing uses, and a state
    from which the machine can never finish. The [first tutorial](tutorials/first-machine.md)
    shows each one.

## Step 2: feed the machine its inputs

A definition is a description. A **machine** is one running copy of it, holding a current
state. `feed` gives it one input and returns the **step** it took. Add these lines:

```python
from gvn.kernel.machine import Machine
from gvn.kernel.symbols import Symbol

machine = Machine(definition=assistant)
for name in ["asked", "tool_wanted", "asked", "tool_returned", "answer_ready"]:
    print(machine.feed(Symbol(name)))
print(machine.state(), machine.finished())
```

```text
Step(idle --asked--> thinking / call_model, declared)
Step(thinking --tool_wanted--> acting / run_tool, declared)
Step(acting --asked--> acting / run_tool, undeclared)
Step(acting --tool_returned--> thinking / call_model, declared)
Step(thinking --answer_ready--> answered / reply, declared)
State('answered') True
```

Read one line: `idle --asked--> thinking / call_model` means "in `idle`, the input `asked`
moved the machine to `thinking`, whose output is `call_model`".

Two things to notice:

- **The outputs are the work.** `call_model`, `run_tool`, `reply`: the machine did none of
  them. It only said which one is due. In the big picture, these are the requests the
  governor hands to fulfillers.
- **The third line is the double click.** `asked` arrived while `acting`. The machine stayed
  put, and the step says `undeclared`, so gvn knows not to start the same work twice.

You fed the inputs by hand here. In a real run, the governor feeds them, and they come from
a model, from tools and from people.

## Step 3: run a real agent through the whole loop

gvn ships a ready-made actor called the **agent**. It is the grown-up version of your
`assistant` machine: it asks a model what to do, checks each tool call with a policy, runs
the tools, and loops until the model answers.

Below, the tool is a function that looks up an order. The model asks to
look up an order, your function returns its status, and the model turns that into an answer.
`run_agent` builds the agent, the governor, the fulfillers and a journal, and drives the run
to its end.

So that this runs with no API key, the model is a **scripted fake**: it asks for the tool
once, then answers.

Save this as `quickstart_agent.py` and run `python quickstart_agent.py`:

```python
import asyncio

from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import FunctionTool, run_agent
from gvn.testing.fakes import ScriptedModel


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


# The tool: your function, with a name, a description and its arguments for the model.
look_up = FunctionTool(
    name="look_up_order",
    description="Look up one order by its id. Returns its status.",
    arguments=Record({"order_id": Text()}),
    function=look_up_order,
)

# A fake model: it asks for the tool once, then answers.
asks_for_a17 = ToolCall(call_id="call-1", name="look_up_order", arguments={"order_id": "A-17"})
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(calls=[asks_for_a17])),
        Reply(message=Message.assistant(text="Your order A-17 shipped yesterday.")),
    ]
)

run = asyncio.run(
    run_agent(
        instructions="Answer customers briefly. Look orders up before answering.",
        prompt="Where is my order A-17?",
        model=model,
        tools=[look_up],
    )
)
print(run.outcome().payload()["text"])
```

It prints:

```text
Your order A-17 shipped yesterday.
```

`run_agent` ran the agent to its end: the model asked for `look_up_order`, your function ran,
its result went back to the model, and the model answered. `run.outcome()` is how the run
ended: the final state the agent reached and a payload of result data, whose `"text"` is the
answer.

What each piece in that code is:

| Piece | Meaning in this example |
|---|---|
| `FunctionTool` | Turns your function into a tool. `name` and `description` are what the model reads; `arguments` is the accepted input shape, checked by gvn before your function runs: `Record({...})` describes a dict with named fields, and `Text()` a string. |
| `ScriptedModel` | The fake model. `ToolCall`, `Message` and `Reply` are the shapes a real model's answers arrive in. |
| `instructions` | The agent's standing directions. |
| `prompt` | This run's question. |
| `tools` | The tools this agent may be offered, as tool objects. Passing one makes it available; it does not force the model to use it. |

### See the machine at work

Add these lines at the end and run it again:

```python
print(run.outcome().payload()["tools"])
# [{'name': 'look_up_order', 'identity': '__main__.look_up_order', 'arguments': {'order_id': 'A-17'}, 'content': {'order_id': 'A-17', 'status': 'shipped yesterday'}}]
records = asyncio.run(run.journal().read("agent"))
print([record["event"]["name"] for record in records])
# ['started', 'model_replied', 'cleared', 'tools_returned', 'model_replied']
```

The first line shows what the agent *did*: the tool it called and what came back. The call
carries the tool's two names: `name`, the short name the model sees, and `identity`, the
name gvn stores and matches on: the module that defines the tool's function, a dot and the
short name. Here that module is `__main__`, because the function is defined in the script
you run; in your own package it would be that module, such as `shop.orders.look_up_order`
([Tools](concepts/tools.md) explains why a tool has both).

The second shows the **journal**: every event of the run, in order (`"agent"` is the name
`run_agent` gives the agent, which also names its run in the journal). Read it against the
picture at the top of this page. Each name is an input that was fed to the agent's machine,
exactly as you fed `asked` and `tool_wanted` to yours in step 2:

| Event in the journal | Who produced it | What the machine did next |
|---|---|---|
| `started` | you, through `run_agent` | asked for the model |
| `model_replied` | the model fulfiller | asked the policy about the tool call |
| `cleared` | the policy fulfiller | asked for the tool to run |
| `tools_returned` | the tool fulfiller | asked for the model again |
| `model_replied` | the model fulfiller | finished: no more tool calls |

The agent's machine is bigger than yours, but it is the same kind of object, checked by the
same verifier. Add this to see it:

```python
from gvn.harness.agent import Agent

agent_machine = Agent.definition()
print(agent_machine)
print(len(agent_machine.states()), "states,", len(agent_machine.inputs()), "inputs")
print(sorted(state.name() for state in agent_machine.finals()))
```

```text
Definition('agent', moore, 932dda45130a)
18 states, 33 inputs
['completed', 'failed', 'overflowed']
```

The default definition has 18 states and 33 inputs. It resolves each pair through a declared
transition, a fallback, or the rule that final states stay final. The journal records the
events that drive the actor. With a durable journal, gvn can rebuild a run in another
process after a crash.

## Step 4: switch to a real model

Use an environment with the `anthropic` extra of `gvn`. Set `ANTHROPIC_API_KEY` and set
`MODEL_ID` to a model available to your account. Keep the imports, tool function and
`look_up = FunctionTool(...)` from step 3. Replace everything after that with this block:

```python
# not runnable: it needs an API key and the network.
import os

import anthropic

from gvn.adapters.anthropic import AnthropicModel
from gvn.shortcuts import AgentRun


async def ask_live() -> AgentRun:
    async with anthropic.AsyncAnthropic() as client:
        return await run_agent(
            instructions="Answer customers briefly. Look orders up before answering.",
            prompt="Where is my order A-17?",
            model=AnthropicModel(client=client, model=os.environ["MODEL_ID"]),
            tools=[look_up],
        )


run = asyncio.run(ask_live())
payload = run.outcome().payload()
print(payload.get("text", payload.get("reason")))
```

Run `python quickstart_agent.py` again. The provider's model chooses whether to call
`look_up_order`, so the outcome may differ. The SDK reads the credential when your code
creates its client. For OpenAI, use `OpenAIModel`. For a compatible Chat Completions endpoint,
use `ChatCompletionsModel`. See
[Using a vendor model](guides/vendors.md).

## What `run_agent` chose for you

`run_agent` is a shortcut over the pieces in the big picture. It made three choices you
will want to revisit:

- **Policy:** clears tool calls without asking anyone. The tools still validate their inputs.
- **Journal:** it lives in memory and is gone when the process ends.
- **Output:** nothing is shown while the run goes.

Each is one argument away: a policy that asks a person before a refund (`policy=`, with
`approve=` to supply the answer; `AskBeforeEveryCall()` asks before every call), a journal in a
file. [The short path](guides/shortcuts.md) shows them, and the plain gvn code `run_agent`
stands for.

## Where next

- [Choose your path](paths.md): an ordered route for building your own harness, trying gvn
  in an afternoon, evaluating it, or briefing a coding agent.
- [The short path](guides/shortcuts.md): everything `run_agent` can do, how to ask a person
  before a call runs, and how to grow out of it one piece at a time.
- The [tutorials](tutorials/index.md) take each box of the big picture in turn, one idea at
  a time: the state machine, the governor, policies and approval, crash and resume,
  workflows. Each takes 10 to 20 minutes.
- The [concepts](concepts/index.md) explain the model behind the code, in the same order.
