# Structured answers

This guide gives an agent a declared shape for its final answer. At the end you have an agent
whose answer your code reads as checked data (a category, a text, a list) instead of prose,
and you know what happens when a reply does not fit.

- **You will be able to:** describe an answer as a schema, ask an agent for it, read the
  checked data from its outcome, see what happens when a reply does not fit, do the same
  with `run_agent`, and see how an adapter turns the schema into its vendor's request.
- **Read first:** the [quickstart](../quickstart.md). The steps wire an agent by hand, as
  [3. An agent with a scripted model](../tutorials/first-agent.md) does; each piece is
  named where it appears. On the short path, go to
  [the short path section](#on-the-short-path) after step 1.
- **Time:** about 15 minutes.

## Why

Code that uses an agent's answer usually needs data, not prose: a category, a number, a
list. The old way is to ask the model nicely for JSON and parse the text, asking again when
it does not parse. That works most of the time, and the times it does not are hidden in a
retry loop.

Anthropic and OpenAI accept a JSON Schema with the request to constrain the reply's text.
The Chat Completions adapter can also request a strict schema from services that accept
that format. gvn checks the final reply against the schema in all cases. An answer that
fails validation follows the agent's declared `answer_invalid` route to `failed`.

## How the parts fit

This guide works on the **actor** box of the quickstart's
[big picture](../quickstart.md#the-big-picture). There the **Governor** drives a run: it
hands each piece of work the agent asks for (a **request**) to a **fulfiller**, the object
that does that kind of work, and feeds the result back to the agent as an **event**. The
shape travels with the work the agent asks for, and the check happens back in the agent:

```mermaid
flowchart LR
    agent["<b>Agent</b><br/>answer = a schema"]
    governor["<b>Governor</b>"]
    fulfiller["<b>Model fulfiller</b>"]
    adapter["<b>Adapter</b><br/>AnthropicModel · OpenAIModel"]
    vendor(["Vendor service<br/>constrains the reply"])
    agent -- "request: invoke_model<br/>(with the schema)" --> governor
    governor --> fulfiller
    fulfiller --> adapter
    adapter -- "the vendor's own<br/>structured-output field" --> vendor
    vendor -- "reply: JSON text" --> adapter
    adapter --> fulfiller
    fulfiller -- "event: model_replied" --> governor
    governor --> agent
    agent -- "fits" --> completed(["completed, with the data"])
    agent -- "does not fit" --> failed(["failed, with a reason"])
```

1. You describe the answer as a **schema**: an object that says what a value must look like
   and checks it at runtime.
2. The agent sends the schema with every request to call the model. An **adapter** is the
   piece that turns gvn's model request into one vendor's API call; it puts the schema in
   the vendor's own structured-output field.
3. The vendor constrains the reply. The agent checks the final reply against the same schema
   and ends `completed` with the data, or `failed` with a reason.

The steps below follow that order: the schema, the agent, a run, a reply that does not fit,
tools, and the real vendors. A last section does the same with `run_agent`.

## Step 1: describe the answer

An answer is described with a schema from `gvn.kernel.schema` (the **kernel** is gvn's core
package: machines and the schemas they check). It is the same module that describes a tool's
arguments: a `Record` is a dict with named fields, each of which is another schema. Here a
triage answer has a kind from a fixed list, a one-line summary, a component that may be
unknown, and a list of labels:

```python
from gvn.kernel.schema import ListOf, Nullable, OneOf, Record, Text

triage_answer = Record(
    fields={
        "kind": OneOf("bug", "feature", "question"),
        "summary": Text(),
        "component": Nullable(Text()),
        "labels": ListOf(Text()),
    }
)
crash = {"kind": "bug", "summary": "Crash on save", "component": "editor", "labels": ["crash", "save"]}
slow = {"kind": "complaint", "summary": "Too slow", "component": None, "labels": []}
print(triage_answer.admits(crash))  # True
print(triage_answer.admits(slow))  # False
```

`OneOf` is a fixed set of strings (an enum), `Nullable` admits `None` as well, and
`ListOf(item)` is a list whose items all fit `item`; the item may itself be a `Record`, for
a list of objects. The second value fails because `"complaint"` is not one of the kinds. The
[schema table](../concepts/durable-objects.md#deeper-schemas) lists every field type. The
schema is a value you build explicitly: gvn never reads type hints to decide a shape.

## Step 2: give it to an agent

`Agent` takes the schema as `answer`:

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

triager = Agent(
    name="triager",
    instructions="Classify the report. Answer with the requested fields only.",
    answer=triage_answer,
)
extra = set(Agent.answering_definition().inputs().names()) - set(Agent.definition().inputs().names())
print(extra)  # {'answer_invalid'}
```

An agent is a [state machine](../reference/glossary.md#state-machine): its states, and the
inputs that move it between them, are declared up front. An agent with an answer runs on a
second machine, `Agent.answering_definition()`. It is the
[reference agent's machine](../concepts/reference-agent.md) with one more input,
`answer_invalid`, which the printed set shows. When the model replies without tool calls,
the agent's `classify_reply` [decision](../reference/glossary.md#decision) (an object that
looks at data and picks one of a fixed set of outcomes) checks the text against the schema
and answers `answered` (on to `completed`) or `answer_invalid` (on to `failed`). An agent
without an answer runs on `Agent.definition()`, unchanged.

## Step 3: run it

A scripted model stands in for the vendor: `ScriptedModel` is a fake that replies from a
script, so the example runs offline. `answer_reply` builds a `Reply` (one model answer) whose
text is the data written as compact JSON, which is what a vendor's structured output returns.
The Governor gets one fulfiller, a `ModelFulfiller` for the agent's `invoke_model` requests,
and in-memory test stand-ins for the journal (where every event is recorded), the output
(where live signals go) and the clock:

```python
import asyncio

from gvn.harness.events import Event
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import ModelFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel, answer_reply

model = ScriptedModel(script=[answer_reply(data=crash)])
governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
report = Event(name="started", payload={"prompt": "The editor crashes when I save a file."})
result = asyncio.run(governor.deliver(actor=triager, event=report))
print(result.outcome().state())  # State('completed')
print(result.outcome().payload()["answer"])
# {'kind': 'bug', 'summary': 'Crash on save', 'component': 'editor', 'labels': ['crash', 'save']}
print(result.outcome().payload()["answer"]["labels"])  # ['crash', 'save']
print(model.exchanges()[0].answer() == triage_answer)  # True
```

Notice three things:

- The checked data is in the outcome under `"answer"`, the list of labels as a plain list.
  `"text"` still holds the raw text.
- The model received the schema: `model.exchanges()` lists every call the fake model
  received, and `Exchange.answer()` is the schema that call carried, the same `Record`. It travelled in
  the `invoke_model` request as its JSON Schema and was rebuilt by the `ModelFulfiller`, so
  only the kernel's own schema classes can be used in an answer (a schema class of your own
  is refused when you build the agent).
- The fake model constrains nothing, so you can script a reply that does not fit, which is the
  next step.

## Step 4: a reply that does not fit

```python
from gvn.harness.messages import Message
from gvn.harness.ports import Reply

model = ScriptedModel(script=[Reply(message=Message.assistant(text='{"kind": "complaint"}'))])
governor = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=model, toolbox=Toolbox())},
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
second_triager = Agent(name="second-triager", instructions="Classify the report.", answer=triage_answer)
result = asyncio.run(governor.deliver(actor=second_triager, event=report))
print(result.outcome().state())  # State('failed')
print(result.outcome().payload()["reason"])
print(len(model.exchanges()))  # 1
```

```text
State('failed')
the final reply is not a valid answer: the reply does not match the answer schema: $.kind: 'complaint' is not one of ['bug', 'feature', 'question']; $.summary: missing required field; $.component: missing required field; $.labels: missing required field
1
```

The run took the `answer_invalid` route to `failed`, with a reason that names every
problem, and the model was asked exactly once. With a real vendor the service constrains
the reply; if a reply still does not fit, you find out here, in a journaled, declared state,
rather than when your code reads a field that is not there. Whether to try again is a decision for
the code that hosts the agent, for example a workflow stage that routes `failed` back to
itself a bounded number of times.

## Step 5: tools first, the answer last

An agent with an answer can still use tools. A reply that calls tools is not an answer and
is not checked; the agent runs the tools as usual (policy, approval, results) and asks the
model again, with the same schema, until a reply without tool calls arrives. Only that final
reply is checked against the answer schema. The adapter sends that schema for reply text.
Tool calls have their own argument schemas.

## Step 6: on a real vendor

Anthropic uses `output_config.format`, OpenAI Responses uses `text.format` with
`strict: true`, and Chat Completions uses a strict `json_schema` in `response_format`.
Use each adapter's `answer_format` to see the request field without a network call:

```python
from gvn.adapters.anthropic import answer_format as anthropic_format
from gvn.adapters.openai import answer_format as openai_format

print(anthropic_format(triage_answer)["type"])  # json_schema
print(openai_format(triage_answer)["strict"])  # True
```

The adapters send the schema exactly as gvn renders it, or refuse it. They never loosen a
schema to make it fit, because then the guarantee would be about a different shape than the
one your code checks. The refusal happens before any call: `answer_format` raises
`ValueError`, and a model call with that schema fails with a `ModelFailure` (the error a
model adapter reports for a failed call) that is not retryable and carries the same reason.
Two examples of a schema an adapter refuses:

```python
from gvn.kernel.schema import Integer

scored = Record(fields={"score": Integer(minimum=1, maximum=5)})
try:
    anthropic_format(scored)
except ValueError as error:
    print(error)
print(openai_format(scored)["schema"]["properties"]["score"])

with_optional = Record(fields={"note": Text()}, optional=["note"])
try:
    openai_format(with_optional)
except ValueError as error:
    print(error)
```

```text
Anthropic's structured outputs cannot express Integer bounds (minimum/maximum) (at $.score)
{'maximum': 5, 'minimum': 1, 'type': 'integer'}
OpenAI's strict Structured Outputs cannot express an optional field (strict mode requires every field: make it required, or required and Nullable) (at $.note)
```

[Using a vendor model](vendors.md#structured-answers-on-each-vendor) has the request field
of each vendor. Enums, records, lists, `Nullable`, numbers, booleans and text are what the
adapters send. To share one schema across providers, call each adapter's
`answer_format(schema)` on it first.

## On the short path: `run_agent(answer=...)` {#on-the-short-path}

[`run_agent`](shortcuts.md#a-structured-answer) builds the Governor, the fulfiller and the
agent of steps 2 and 3 for you. It takes the same schema as `answer=`, and the `AgentRun` it
returns holds the checked data as `run.answer()`:

```python
import asyncio

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

run = asyncio.run(
    run_agent(
        instructions="Classify the report. Answer with the requested fields only.",
        prompt="The editor crashes when I save a file.",
        model=ScriptedModel(script=[answer_reply(data=crash)]),
        answer=triage_answer,
        name="triage-short",
    )
)
print(run.state())
print(run.answer())
print(run.answer()["labels"])

unfit = asyncio.run(
    run_agent(
        instructions="Classify the report.",
        prompt="The editor crashes when I save a file.",
        model=ScriptedModel(script=[Reply(message=Message.assistant(text='{"kind": "complaint"}'))]),
        answer=triage_answer,
        name="triage-short-unfit",
    )
)
print(unfit.state(), unfit.answer())
```

```text
State('completed')
{'kind': 'bug', 'summary': 'Crash on save', 'component': 'editor', 'labels': ['crash', 'save']}
['crash', 'save']
State('failed') None
```

`run.answer()` is the outcome's `"answer"`. A final reply that does not fit ends the run
`failed`, as in step 4: the run is returned, `answer()` is None and
`unfit.outcome().payload()["reason"]` names every problem. Tools, a policy and `approve=`
work beside `answer=` as [The short path](shortcuts.md) shows them.

## How it meets the rest of the framework

- **Streaming.** The reply's text is the JSON, so the `delta` signals of a structured
  answer (the pieces of text sent to the output as the model writes them; see
  [Streaming and observability](../concepts/streaming-and-observability.md)) are fragments
  of JSON. They are progress, not data: read the answer from the outcome.
- **Thinking.** A model's thinking, which the adapters carry between tool rounds
  ([Using a vendor model](vendors.md#thinking-between-tool-rounds)), is not constrained by
  the vendors.
- **Refusals and the token limit.** The adapters report a refusal or reply cut off by the
  output token limit as `ModelFailure`. The agent ends `failed` through `model_failed`, so
  the truncated JSON stays out of the answer validator. The failure includes usage when
  the vendor reports it.
- **Citations.** Anthropic refuses to cite documents and constrain the answer in the same
  call; the adapter fails such a call before sending it.
- **Conversations and errands** do not take an answer. An
  [`Errand`](../concepts/errands.md) (a batch of tool calls made by code) has no model. A
  [`Conversation`](../concepts/conversations.md) (an actor that talks with a person) ends through its `close` tool, whose arguments are already declared data,
  and its other replies are written for a person.

## Recap

- Describe the answer with a kernel `Record` (its fields may be `ListOf`, `OneOf`,
  `Nullable` and the other schemas) and pass it as `Agent(..., answer=...)` or
  `run_agent(..., answer=...)`.
- The vendor constrains the reply; gvn checks it again; the data is in the outcome under
  `"answer"`, and in `AgentRun.answer()` on the short path.
- A reply that does not fit takes the declared `answer_invalid` route to `failed`, once,
  with a reason.
- Adapters send the schema exactly or refuse it before calling, naming what their vendor
  cannot express.
- `answer_reply` scripts a structured answer for tests.

## Next

Choose by what you need now:

- **A model that picks a route.** [Model-backed choices](model-backed-choices.md) uses the
  same mechanism to let a model pick one of a workflow's declared routes.
- **The answer from a real model.** [Using a vendor model](vendors.md) builds the adapter;
  [its structured-answers section](vendors.md#structured-answers-on-each-vendor) has each
  vendor's request field.
- **Whether the answers are right.** [Replay and evaluation](replay-and-evaluation.md)
  reads finished runs back and grades them against checks.
