Browse documentation
Guides
View Markdown
On this page

Using a vendor model

This guide connects a harness to a real model service in place of the scripted fakes most examples on this site run on. At the end you have one complete script that runs an agent on a vendor's model and prints its answer and its usage, and you know where to look up everything else a model call carries.

gvn ships three adapters, the objects that turn gvn's model call into one vendor's API call: AnthropicModel (in gvn.adapters.anthropic), OpenAIModel (in gvn.adapters.openai) and ChatCompletionsModel (in gvn.adapters.chat_completions). The first two speak their vendor's own API. The third speaks the Chat Completions format (POST <base URL>/chat/completions), which most model services accept at their own base URL, so one adapter reaches many services; DeepSeek is the first one used with it.

  • You will be able to:
    • install an adapter and build it over your own SDK client;
    • choose the model id and hand the adapter to a harness;
    • run one complete script on a real model;
    • watch an adapter answer and fail, offline;
    • turn prompt caching and effort on or off;
    • look up the rest in the reference sections: a model per role, usage, thinking, structured answers, images and documents, failures, retries and throttles, other services, embeddings.
  • Read first: the quickstart or The short path, which run an agent on a scripted model with run_agent. The tutorials 5. A policy and approval and 12. A real model and ready-made tools wire the same by hand.
  • Time: about 30 minutes for the steps, plus an API key from your vendor to try it for real.

Where the model sits

This guide works on the model fulfiller in the quickstart's 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 model fulfiller is the one that answers an agent's requests to call the model. A port is an interface the framework talks to without knowing what is behind it. A model in gvn is anything that implements the Model port: one method, generate(exchange, progress), that takes the conversation so far (an Exchange) and returns the model's answer (a Reply). An adapter is a Model that translates that call into one vendor's API:

flowchart LR
    agent["<b>Agent</b>"]
    governor["<b>Governor</b>"]
    fulfiller["<b>ModelFulfiller</b>"]
    adapter["<b>Adapter</b><br/>AnthropicModel · OpenAIModel<br/>ChatCompletionsModel (a Model)"]
    client["<b>SDK client</b><br/>yours: key, URL, timeouts"]
    vendor(["Vendor service"])
    agent -- "request: invoke_model" --> governor
    governor --> fulfiller
    fulfiller -- "Exchange" --> adapter
    adapter --> client
    client --> vendor
    vendor -- "streamed reply" --> client
    client --> adapter
    adapter -- "Reply, or ModelFailure" --> fulfiller
    fulfiller -- "event: model_replied<br/>or model_failed" --> governor
    governor --> agent

Only the adapter knows the vendor; only the SDK client (the vendor's own Python library object, which you create) holds your credentials. Every adapter implements Model, so swapping a fake for an adapter, or one adapter for another, changes one line of your program. An adapter of your own is one module that implements Model.generate(exchange, progress); check it with gvn.testing.contracts.ModelContract, as described in Testing your harness.

The page goes one level down at a time. Steps 1 to 4 connect a real model and end with a complete script. Steps 5 and 6 watch an adapter answer and fail, offline. Step 7 covers the settings worth knowing early: caching, effort and a service's own request fields. The walkthrough ends there; the rest of the page is reference, with a table of what each section answers.

Step 1: install the extra

Each adapter needs an SDK. Use the anthropic extra for AnthropicModel, or openai for OpenAIModel and ChatCompletionsModel. ChatCompletionsModel uses the OpenAI SDK whichever service it reaches. The inner layers of gvn are kept independent of vendor SDKs by an import contract.

Step 2: build the client yourself

An adapter does not create its SDK client. You create it and hand it in, with the model id:

# not runnable: it needs a real API key and a model id.
import os

import anthropic

from gvn.adapters.anthropic import AnthropicModel

client = anthropic.AsyncAnthropic()  # reads its key from the environment
model = AnthropicModel(client=client, model=os.environ["MODEL_ID"], max_tokens=4096)

The OpenAI adapter is built the same way:

# not runnable: it needs a real API key and a model id.
import os

import openai

from gvn.adapters.openai import OpenAIModel

client = openai.AsyncOpenAI()  # reads its key from the environment
model = OpenAIModel(client=client, model=os.environ["MODEL_ID"])

ChatCompletionsModel is built over an openai.AsyncOpenAI that you point at the service with its base URL and key. It also takes a vendor, the name of that service, which the next paragraphs explain. This one reaches DeepSeek:

# not runnable: it needs a real API key and the network.
import os

import openai

from gvn.adapters.chat_completions import ChatCompletionsModel

client = openai.AsyncOpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
model = ChatCompletionsModel(client, "deepseek-flash", vendor="deepseek")

Any other service with a Chat Completions endpoint is reached the same way: change the base_url of the client, the model id, and the vendor. vendor names the service behind the client ("deepseek", "mistral", ...). The adapter cannot tell from a client which service it reaches, and what a service returns as its own, its reasoning, must go back only to that service, so you say which it is. vendor labels the sealed records the adapter keeps (Reasoning on Chat Completions) and is never sent on the wire. The adapter is stateless: every request carries the whole conversation, and gvn's journal is the only record of a run.

Why inject the client? It keeps every piece of configuration where it belongs: the API key, the base URL, timeouts, the SDK's own retry policy, proxies and the HTTP transport are all set on the client, by you, with the vendor's documented options. The adapter can inspect known client credentials to redact them from error details. Use an asynchronous client (AsyncAnthropic, AsyncOpenAI, or a compatible async client); passing a synchronous client is a TypeError.

Step 3: choose the model id

model is a required argument, and an empty string is a ValueError. Model ids change: new ones appear, old ones are retired, and the right one depends on cost, latency and what your harness asks of it. Read it from configuration rather than writing it into code, as the examples above do with an environment variable. Then changing models is a deployment change, and the id in use is visible where the rest of your configuration is.

AnthropicModel also takes max_tokens (default 4096): the most tokens one reply may use, thinking included. OpenAIModel takes max_tokens=None, which leaves the limit to the service; give an int to set it (it is sent as max_output_tokens, and the model's hidden reasoning counts towards it, so leave room for it). ChatCompletionsModel takes max_tokens=None too, sent as max_tokens when given. All take effort, and AnthropicModel takes cache; ChatCompletionsModel also takes extra, the service's own request fields (extra request fields); step 7 explains them.

All three also take context_window=None: the model's context window in tokens (the most one call can hold), which the adapter returns from Model.context_window(). Give it from the same configuration as the model id. The ModelFulfiller adds it to every model_replied event, which is how an actor's context budget learns it; with None, a budget written as a share of the window has nothing to apply to (see Context management).

Step 4: use it where the fake was

The model goes wherever a fake went before: usually into the ModelFulfiller that serves an agent's invoke_model requests, beside the toolbox the agent may use:

# not runnable: continues the example above.
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import ModelFulfiller

fulfiller = ModelFulfiller(model=model, toolbox=Toolbox())

For an agent with tools, build the toolbox with those same tool objects. The agent, policy, journal and Governor use the same wiring with either a fake or an adapter. With run_agent, the adapter is the model= argument and the fulfiller is built for you, as the script below does.

A complete script on a real model

Steps 1 to 4 in one file: an SDK client, the adapter over it, an agent with one tool, one prompt, and the outcome and usage printed. Save it as live_agent.py:

# not runnable: it needs a real API key, a model id and the network.
import asyncio
import os

import anthropic

from gvn.adapters.anthropic import AnthropicModel
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import AgentRun, FunctionTool, run_agent

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


def look_up_order(order_id: str) -> dict[str, object]:
    return {"order_id": order_id, **ORDERS.get(order_id, {"status": "unknown"})}


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,
)


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


def main() -> None:
    run = asyncio.run(ask_live())
    payload = run.outcome().payload()
    print(run.state())
    print(payload.get("text", payload.get("reason")))
    print([attempt["name"] for attempt in payload.get("attempts", [])])
    print(run.usage())


if __name__ == "__main__":
    main()

It needs an environment with the anthropic extra of gvn and two environment variables:

Variable Value
ANTHROPIC_API_KEY your key; the SDK client reads it when it is created
MODEL_ID a model id available to your account

Run python live_agent.py. A successful run prints four lines: the final state (State('completed')), the model's answer in its own words, the short names of the tools it called (usually look_up_order; the model chooses whether to call it), and the usage of the run's model calls as a dict of input_tokens, output_tokens, cache_read_tokens, cache_write_tokens and calls. When the model call fails, a wrong model id or key for example, the first line is State('failed') and the second is the failure's reason.

For OpenAI, build openai.AsyncOpenAI() and OpenAIModel(client=client, model=...) in the same two lines (it reads OPENAI_API_KEY); for a Chat Completions service, the client and ChatCompletionsModel of step 2. Nothing else in the script changes.

Step 5: see a reply, offline

You can watch an adapter work without a network or a key. The SDK clients accept an HTTP transport of your choosing; httpx2.MockTransport hands every request to a Python function instead of a socket. It is the HTTP library the vendor SDKs in gvn's development environment are built on.

First, a helper that builds a real AsyncOpenAI whose every request goes to a function:

import asyncio
import json
import typing
from collections.abc import Callable

import httpx2
import openai

from gvn.adapters.openai import OpenAIModel
from gvn.harness.messages import Message
from gvn.harness.ports import Exchange, ModelFailure, Quiet


def offline_client(answer: Callable[[httpx2.Request], httpx2.Response]) -> openai.AsyncOpenAI:
    """A real AsyncOpenAI whose every request is answered by ``answer(request)``."""
    return openai.AsyncOpenAI(
        api_key="not-a-real-key",
        base_url="https://model.invalid/v1",
        http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(answer)),
        max_retries=0,
    )


question = Exchange(instructions="Be brief.", messages=[Message.user("Hi")])

An Exchange is what the adapter is asked: the instructions and the messages so far. A Progress is where an adapter sends the text fragments of a reply while it streams in (the Governor supplies one that forwards them to your outputs); Quiet is a Progress that discards them.

The service streams its reply as server-sent events: a standard HTTP format in which the response body is a sequence of small event: and data: records. OpenAIModel speaks OpenAI's Responses API, where each event has a type. This function answers with two text fragments (response.output_text.delta), the finished message (response.output_item.done) and the end of the reply with its token usage (response.completed):

def event(data: dict[str, typing.Any]) -> str:
    return f"event: {data['type']}\ndata: {json.dumps(data)}\n\n"


def hello(request: httpx2.Request) -> httpx2.Response:
    message = {
        "type": "message",
        "id": "msg_1",
        "role": "assistant",
        "status": "completed",
        "content": [{"type": "output_text", "text": "Hello.", "annotations": []}],
    }
    usage = {"input_tokens": 12, "output_tokens": 3, "input_tokens_details": {"cached_tokens": 0}}
    events = [
        {"type": "response.output_text.delta", "output_index": 0, "delta": "Hel"},
        {"type": "response.output_text.delta", "output_index": 0, "delta": "lo."},
        {"type": "response.output_item.done", "output_index": 0, "item": message},
        {"type": "response.completed", "response": {"status": "completed", "usage": usage}},
    ]
    body = "".join(event(each) for each in events)
    return httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body.encode()
    )


hello_model = OpenAIModel(client=offline_client(hello), model="test-model")
reply = asyncio.run(hello_model.generate(exchange=question, progress=Quiet()))
print(reply.message().text(), reply.input_tokens(), reply.output_tokens())  # Hello. 12 3

The adapter assembled the fragments into one Reply, as it will with a real service. A real stream has more events (the reply's creation, content parts, a sequence number on each); the adapter reads the ones above and ignores the rest.

And the Anthropic adapter, over a real AsyncAnthropic, with the events of the Messages streaming protocol:

import anthropic

from gvn.adapters.anthropic import AnthropicModel

EVENTS = [
    {
        "type": "message_start",
        "message": {
            "id": "msg_1",
            "type": "message",
            "role": "assistant",
            "model": "test-model",
            "content": [],
            "stop_reason": None,
            "stop_sequence": None,
            "usage": {"input_tokens": 12, "output_tokens": 0},
        },
    },
    {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
    {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hel"}},
    {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "lo."}},
    {"type": "content_block_stop", "index": 0},
    {
        "type": "message_delta",
        "delta": {"stop_reason": "end_turn", "stop_sequence": None},
        "usage": {"output_tokens": 3},
    },
    {"type": "message_stop"},
]


def streamed(request: httpx2.Request) -> httpx2.Response:
    body = "".join(f"event: {each['type']}\ndata: {json.dumps(each)}\n\n" for each in EVENTS)
    return httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body.encode()
    )


client = anthropic.AsyncAnthropic(
    api_key="not-a-real-key",
    http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(streamed)),
    max_retries=0,
)
claude = AnthropicModel(client=client, model="test-model")
reply = asyncio.run(claude.generate(exchange=question, progress=Quiet()))
print(reply.message().text(), reply.input_tokens(), reply.output_tokens())  # Hello. 12 3

And ChatCompletionsModel, over the same kind of AsyncOpenAI. It speaks the Chat Completions format, where the stream is a sequence of data: records (chunks) that each carry a delta of the reply, ending with data: [DONE]. This function records the request it receives and answers with some reasoning (reasoning_content), the text and the token usage:

from gvn.adapters.chat_completions import ChatCompletionsModel

seen = []


def chunk(
    delta: dict[str, typing.Any],
    finish: str | None = None,
    usage: dict[str, typing.Any] | None = None,
) -> str:
    body = {"id": "c1", "object": "chat.completion.chunk", "model": "test-model",
            "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
    if usage:
        body["usage"] = usage
    return f"data: {json.dumps(body)}\n\n"


def chat(request: httpx2.Request) -> httpx2.Response:
    seen.append(json.loads(request.content))
    usage = {"prompt_tokens": 12, "completion_tokens": 9,
             "prompt_tokens_details": {"cached_tokens": 4}}
    body = "".join([
        chunk({"role": "assistant", "reasoning_content": "The user greets me."}),
        chunk({"content": "Hel"}),
        chunk({"content": "lo."}, finish="stop"),
        chunk({}, usage=usage),
        "data: [DONE]\n\n",
    ])
    return httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body.encode()
    )


deepseek = ChatCompletionsModel(
    offline_client(chat),
    "test-model",
    vendor="deepseek",
    extra={"thinking": {"type": "enabled"}},
)
reply = asyncio.run(deepseek.generate(exchange=question, progress=Quiet()))
print(reply.message().text(), reply.usage())
# Hello. {'input_tokens': 12, 'output_tokens': 9, 'cache_read_tokens': 4, 'cache_write_tokens': 0}
print(reply.message().sealed())
# ({'vendor': 'deepseek', 'model': 'test-model', 'block': {'reasoning_content': 'The user greets me.'}},)
print(seen[0]["thinking"], seen[0]["messages"][0])  # {'type': 'enabled'} {'role': 'system', 'content': 'Be brief.'}

The request went to /chat/completions with the extra field as given. The reasoning came back as one sealed record labelled with the vendor, and the cached input tokens as cache_read_tokens.

The reply also carries the tokens the service reported. For a test suite, prefer the fakes in gvn.testing. A mock transport is for testing an adapter, or for checking what your harness sends on the wire.

Each adapter also says which service it calls: Model.provider(), a lower-case name as the OpenTelemetry GenAI conventions spell it. ChatCompletionsModel answers with the vendor it was given, since one adapter reaches many services:

print(hello_model.provider(), claude.provider(), deepseek.provider())  # openai anthropic deepseek

The ModelFulfiller journals the provider with every model answer, as "provider" on model_replied and model_failed (beside "model", the model's name), so a run's record says which service each call went to. A reply that names its own provider (Reply.provider()) is journaled with that one, else the model's. The fakes have no provider of their own, so their answers carry one only when the reply names it. A FallbackModel has none either, since no one service answers for the list: its reply names the provider of the member that answered, and a failure from it names none rather than a service that may not be the one that failed. Logs, traces and streams shows where it is read from there.

Step 6: see a failure, offline

An adapter never lets a vendor exception escape. Every failure becomes a ModelFailure (in gvn.harness.ports) with a reason() a person can act on and a retryable() flag. This function answers the way the service does when it is rate limiting:

def rate_limited(request: httpx2.Request) -> httpx2.Response:
    error = {"message": "slow down", "type": "requests", "param": None, "code": None}
    return httpx2.Response(429, json={"error": error})


busy_model = OpenAIModel(client=offline_client(rate_limited), model="test-model")
try:
    asyncio.run(busy_model.generate(exchange=question, progress=Quiet()))
except ModelFailure as failure:
    print(failure.reason(), failure.retryable())
# rate limited by the model service (429); retry later: slow down True

The reason starts with what happened and ends with the service's own message ("slow down"), which is often the only clue to what went wrong. When a call fails says which failures are retryable and who retries.

Step 7: caching and effort

An agent sends its whole prompt on every model call: the tool descriptions, the instructions and the conversation so far. The tool descriptions can make up most of the input tokens, and they are the same on every call.

Prompt caching is the vendor's answer: the service keeps a prefix of a prompt it has seen, and a later call that starts with exactly the same bytes reads that prefix from the cache, at a fraction of the price. AnthropicModel turns it on by default (cache=True). It marks three places as cache breakpoints, from the most stable part of the prompt to the least:

  1. the last tool (tools are sent first, so this caches all of them);
  2. the system prompt (tools and instructions together);
  3. the conversation, through the API's automatic caching, which moves forward as the conversation grows, so each call reads the previous call's prefix.

For a prefix to match, the bytes must be identical, so the adapter sends tools in name order and every object's keys sorted, on every call and after a journal round trip. A prefix shorter than the model's minimum cacheable length is not cached. cache=False sends no cache markers at all.

Effort asks the model to spend more or less work on its replies. effort=None, the default, sends nothing and leaves the model's own default. Otherwise it is one of the adapter's EFFORTS, sent to Anthropic as output_config: {"effort": ...}. The API rejects a level the model does not support, and that call fails. The adapter does not configure thinking: models that think by default do so.

To see what the adapter sends, keep a list of the request bodies in the answering function. This builds a model with a low effort and caching on, and asks it something with one tool. A ToolSpec is what the model is told about a tool: its name, description and argument schema, without the code that runs it:

from gvn.adapters.anthropic import EFFORTS
from gvn.harness.tools import ToolSpec
from gvn.kernel.schema import Record, Text

print(EFFORTS)  # ('low', 'medium', 'high', 'xhigh', 'max')

sent = []


def answer_and_record(request: httpx2.Request) -> httpx2.Response:
    sent.append(json.loads(request.content))
    return streamed(request)


def recording_client() -> anthropic.AsyncAnthropic:
    return anthropic.AsyncAnthropic(
        api_key="not-a-real-key",
        http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(answer_and_record)),
        max_retries=0,
    )


frugal = AnthropicModel(
    client=recording_client(), model="test-model", max_tokens=4096, effort="low", cache=True
)
read_file = ToolSpec(
    name="read_file", description="Read a file.", arguments=Record(fields={"path": Text()})
)
with_tool = Exchange(instructions="Be brief.", messages=[Message.user("Hi")], tools=[read_file])
asyncio.run(frugal.generate(exchange=with_tool, progress=Quiet()))

body = sent[-1]
print(body["tools"][-1]["cache_control"])  # {'type': 'ephemeral'}
print(body["system"])
# [{'type': 'text', 'text': 'Be brief.', 'cache_control': {'type': 'ephemeral'}}]
print(body["cache_control"], body["output_config"])
# {'type': 'ephemeral'} {'effort': 'low'}

The three cache_control markers are the three breakpoints, and output_config carries the effort. Both settings belong to the adapter, so every actor whose calls go through one AnthropicModel (every actor under one Governor, usually) shares them.

Effort and caching on OpenAI

OpenAIModel(client=..., model=..., max_tokens=None, effort=None) takes an effort too. It accepts every level the Responses API documents, its own EFFORTS: 'none', 'minimal', 'low', 'medium', 'high', 'xhigh' and 'max', sent as reasoning: {"effort": ...}. Which of them a given model accepts is the service's decision, not the adapter's: a level the model does not support fails at the first call, not retryable, and the reason quotes the service's answer, which names the levels the model does support. Function tools work together with any accepted effort level.

OpenAIModel has no cache setting, because caching is automatic on this vendor: the service caches long enough prompt prefixes on its own, and the adapter sends nothing to turn it on or off. What the adapter does is keep the prefix stable: tools in name order and every object's keys sorted, so the same conversation is the same bytes on every call and after a journal round trip. The usage figures then say what the cache did; What a call cost explains them.

Effort and extra fields on Chat Completions

ChatCompletionsModel(client, model, vendor, max_tokens=None, effort=None, context_window=None, extra=None) takes an effort too: None sends nothing, and otherwise one of its EFFORTS ('none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'), sent as reasoning_effort. Which levels a model accepts is the service's decision: a level it does not support is rejected at the first call, and the failure's reason quotes the service's message. It has no cache setting; the usage figures (What a call cost) say what the service's cache did.

extra= is for what a service adds to the format. It is a mapping of further top-level request fields, plain JSON, sent as given with every request, for example extra={"thinking": {"type": "disabled"}}. gvn does not interpret them. A name the adapter sets itself (model, messages, tools, tool_choice, stream, stream_options, response_format, max_tokens, reasoning_effort, n) is a ValueError when you build the adapter, naming it.

Reference: the rest of this page

The walkthrough ends here: you have a model connected. The remaining sections are reference; each stands on its own, so go to the one that answers your question.

Section What it answers
A model per role How do I use a small model for summaries or picks and a large one for the work?
What a call cost: usage What do the four usage figures mean, and where do I read them?
Thinking between tool rounds How is a model's thinking or reasoning carried from one call to the next?
Structured answers on each vendor Which request field carries an answer schema on each vendor?
Images and documents How do I send an image or a PDF, from a prompt or from a tool?
Citations Where are the sources a reply cites?
Server tools How do I turn on a tool the vendor runs, such as web search?
The vendor's own context reduction How do I let the vendor clear or compact a long conversation?
What is translated Which gvn term becomes which field of the vendor's API?
When a call fails Which failures are retryable, who retries, and how do I add retries, a fallback model or a throttle?
Cancellation What happens to a model call the Governor no longer wants?
Other services How do I reach another service that speaks Chat Completions or the Responses API?
Embeddings for a memory How do I give a memory an embedder, so it recalls by meaning?
Failures you will meet What does this error at the first call mean?

A model per role

One ModelFulfiller serves every model call of a run, and so far it has had one model. A harness often wants more than one: a large model for the work, a small and cheap one to summarise a long conversation (Context management) or to pick a route (Model-backed choices). gvn does this with roles.

flowchart LR
    agent["<b>Agent</b><br/>model_role=None"]
    step["<b>Summarise</b> step<br/>model_role='summariser'"]
    fulfiller["<b>ModelFulfiller</b><br/>model=large<br/>roles={'summariser': small}"]
    large["large model"]
    small["small model"]
    agent -- "invoke_model" --> fulfiller
    step -- "invoke_model<br/>model_role: summariser" --> fulfiller
    fulfiller -- "no role" --> large
    fulfiller -- "summariser" --> small

A role is a name that an actor uses and that your wiring maps to a model. It is not a vendor's model id: the actor says what the call is for ("summariser", "triage"), and the place where you build the runtime says which model does that job, so changing models stays a deployment change. A role name starts with a letter and has letters, digits, _ and -.

  • Who names a role. Agent(..., model_role=None), Conversation(..., model_role=None) and Choice(..., model_role=None) name one for all their calls; Summarise(keep, brief="", model_role=None) names one for its summaries (with none, a summary uses the actor's role). A role that is not None travels in the invoke_model payload as "model_role", so the journal shows which role every call asked for.
  • Who maps it. ModelFulfiller(model, toolbox, retry=None, roles=None) takes roles, a mapping of role name to Model. A request that names a role is served by that role's model; a request that names none by model, exactly as before. A Retry retries on the model that serves the request.
  • Each actor learns its own model's window. The model_replied event carries the "context_window" of the model that answered, so an actor on a small model measures against the small model's window. A summary's reply is never a measurement, so a smaller summariser does not change what the actor knows of its own conversation.

Here a large model does the work and a small one summarises. The budget summarises once the transcript holds more than two messages:

import asyncio

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.context_window import ContextBudget, Summarise
from gvn.harness.events import Event
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput, StubTool


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

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


def large_works(exchange: Exchange) -> Reply:
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="A-17 shipped on 3 May."), input_tokens=900, output_tokens=40)
    call = ToolCall("c1", "look_up_order", {"order_id": "A-17"})
    return Reply(message=Message.assistant(text="", calls=[call]), input_tokens=800, output_tokens=30)


def small_summarises(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text="The person asked where order A-17 is."), input_tokens=200, output_tokens=15)


large = FunctionModel(respond=large_works, context_window=200_000)
small = FunctionModel(respond=small_summarises, context_window=16_000)
look_up = StubTool(name="look_up_order", arguments=Record({"order_id": Text()}), result={"shipped": "3 May"})
role_tools = Toolbox([look_up])
role_journal = MemoryJournal()
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=large, toolbox=role_tools, roles={"summariser": small}),
        "invoke_tools": ToolFulfiller(toolbox=role_tools),
        "consult_policy": PolicyFulfiller(decision=ClearAll()),
    },
    journal=role_journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
support = Agent(
    name="support",
    instructions="Answer questions about orders.",
    tools=[look_up],
    context_budget=ContextBudget(reduce_over=2, steps=[Summarise(keep=1, model_role="summariser")]),
)
result = asyncio.run(governor.deliver(actor=support, event=Event("started", {"prompt": "Where is A-17?"})))
print(result.outcome().payload()["reductions"])
print(len(large.exchanges()), len(small.exchanges()))


async def windows() -> None:
    for record in await role_journal.read("support"):
        event = record["event"]
        if event["name"] == "model_replied":
            print(repr(event["payload"]["message"]["text"]), event["payload"]["context_window"])


asyncio.run(windows())
{'trimmed': 0, 'summarised': 1, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}
2 1
'' 200000
'The person asked where order A-17 is.' 16000
'A-17 shipped on 3 May.' 200000

The large model was asked twice, for the work; the small one once, for the summary. Each reply carries the window of the model that wrote it, and the agent measured only the two replies from its own model.

A role the mapping lacks is refused before the run starts. Every actor answers model_roles(): the roles it, and anything it will ever build beneath it, may ask for. An Agent or Conversation answers its own role and its Summarise steps' roles, a Choice its own, and a workflow the roles its plan declares (below). Each time the Governor is asked to drive an actor (deliver, answer, resume, wake), it first asks every fulfiller what that actor needs and it lacks (Fulfiller.unmet(actor)); the ModelFulfiller names the roles it has no model for, and the tools its toolbox does not hold (Tools). Any answer stops the call with Unfulfillable before the actor handles anything: nothing is journaled and the actor is unchanged, so you fix the wiring and deliver again.

from gvn.runtime.governor import Unfulfillable

triage = Agent(name="triage", instructions="Sort the ticket.", model_role="triage")
unwired_journal = MemoryJournal()
unwired = Governor(
    fulfillers={"invoke_model": ModelFulfiller(model=large, toolbox=role_tools)},
    journal=unwired_journal,
    output=RecordingOutput(),
    clock=ManualClock(),
)
try:
    asyncio.run(unwired.deliver(actor=triage, event=Event("started", {"prompt": "Printer on fire."})))
except Unfulfillable as error:
    print(error)
print(triage.state(), asyncio.run(unwired_journal.length("triage")))
actor 'triage' cannot be driven: the 'invoke_model' fulfiller lacks what it needs: model roles ['triage'] have no model in this ModelFulfiller (roles: [])
State('idle') 0

A workflow declares the roles of its children. A workflow builds its children while it runs, so it cannot know their roles in advance unless its plan says so: Plan(definition, stages, ..., model_roles=["summariser"]), and the workflow answers model_roles() with them (its children's tools are declared the same way, with tools=). When a stage builds a child whose roles the plan does not declare, that is a ValueError naming the workflow, the stage, the child and the roles, the same every time, so any test that reaches the stage finds it. A workflow hosting another workflow declares the inner one's roles too (Workflows in depth).

The ModelFulfiller still checks each request's role when it serves it, as a defence for an actor whose model_roles() leaves out a role it asks for: that is a ValueError naming the request and the role, raised out of the Governor's call with nothing journaled for the request.

run_agent takes the same two settings as model_role= (the agent's) and model_roles= (the mapping).

What each model cost. Every answer journals "model", the name of the model that made the call: the model id the vendor reported in its reply, else Model.name() (the adapters answer the id they were configured with). Trace.usage_by_model() splits a run's usage by it (What the runs cost), so a large and a small model, priced differently, are priced separately.

A packaged harness from gvn-domains lists the roles its actors name in Harness.model_roles(), and its Launcher(..., model_roles=...) takes the mapping. The launcher checks the mapping when it is built, so a missing role is refused before any run is even started (What the launcher wires; the feature builds name "summariser").

What a call cost: usage

Every Reply carries the tokens the call reported, as four figures. reply.usage() gives them as plain JSON, the form gvn journals:

Key Meaning
input_tokens every input token the call processed, read from the cache or not
output_tokens the tokens generated, thinking included
cache_read_tokens the part of input_tokens read from the prompt cache (billed at the cache-read price)
cache_write_tokens the part of input_tokens written to the cache (billed at the cache-write price)

So input_tokens is the whole prompt, not only the uncached part: the uncached input is input_tokens - cache_read_tokens - cache_write_tokens. Anthropic reports the three parts separately (its input_tokens is only the uncached part), and the adapter adds them up. A figure the service does not report is 0.

On OpenAI the figures come straight from the Responses API's usage:

  • input_tokens is the service's input_tokens, which already includes cached tokens;
  • cache_read_tokens is input_tokens_details.cached_tokens, the part read from the cache;
  • cache_write_tokens is input_tokens_details.cache_write_tokens. OpenAI documents a separate cache-write price only for its newest models; it is 0 when the service reports none;
  • output_tokens is the service's output_tokens, which includes the model's hidden reasoning tokens.

On Chat Completions the figures come from the stream's usage record:

  • input_tokens is prompt_tokens, every input token;
  • cache_read_tokens is prompt_tokens_details.cached_tokens or, when the service sends prompt_cache_hit_tokens instead, that figure; 0 when it sends neither, and never more than the input;
  • cache_write_tokens is always 0;
  • output_tokens is completion_tokens, reasoning tokens included.

The usage is read from the last stream chunk that carries one. A stream with none gives zeros.

Here the service reports a first call that wrote 1,200 tokens to the cache:

CACHED_EVENTS = [dict(each) for each in EVENTS]
CACHED_EVENTS[0] = {
    "type": "message_start",
    "message": {
        **EVENTS[0]["message"],
        "usage": {
            "input_tokens": 50,
            "cache_creation_input_tokens": 1200,
            "cache_read_input_tokens": 0,
            "output_tokens": 0,
        },
    },
}


def cache_writing(request: httpx2.Request) -> httpx2.Response:
    body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in CACHED_EVENTS)
    return httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body.encode()
    )


cold = AnthropicModel(
    client=anthropic.AsyncAnthropic(
        api_key="not-a-real-key",
        http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(cache_writing)),
        max_retries=0,
    ),
    model="test-model",
)
reply = asyncio.run(cold.generate(exchange=question, progress=Quiet()))
print(reply.usage())  # {'input_tokens': 1250, 'output_tokens': 3, 'cache_read_tokens': 0, 'cache_write_tokens': 1200}

input_tokens is 1,250: the 50 uncached tokens plus the 1,200 written to the cache. The Governor records these figures on every model_replied event and on its event signal, and Trace.usage() totals them for a run (see What the runs cost).

Thinking between tool rounds

Models that think write their reasoning as thinking blocks before they answer, signed by the vendor (redacted_thinking when the reasoning is encrypted). When the reply asks for tools, the next call continues the same turn of thought, and Anthropic asks for those blocks back unmodified, with the assistant turn they belong to. Without them the model loses its earlier reasoning across tool rounds.

gvn keeps them as sealed content (opaque data that only the adapter of the vendor that wrote it may read): a slot on the assistant Message (sealed()) holding records {"vendor", "model", "block"}, in the order the vendor sent them. gvn never reads inside them; only the adapter of that vendor does. Here the service thinks, then calls a tool:

THINKING_EVENTS = [
    EVENTS[0],
    {
        "type": "content_block_start",
        "index": 0,
        "content_block": {"type": "thinking", "thinking": "", "signature": ""},
    },
    {
        "type": "content_block_delta",
        "index": 0,
        "delta": {"type": "thinking_delta", "thinking": "Read the file first."},
    },
    {
        "type": "content_block_delta",
        "index": 0,
        "delta": {"type": "signature_delta", "signature": "c2lnbmVk"},
    },
    {"type": "content_block_stop", "index": 0},
    {
        "type": "content_block_start",
        "index": 1,
        "content_block": {"type": "tool_use", "id": "toolu_1", "name": "read_file", "input": {}},
    },
    {
        "type": "content_block_delta",
        "index": 1,
        "delta": {"type": "input_json_delta", "partial_json": '{"path": "calc.py"}'},
    },
    {"type": "content_block_stop", "index": 1},
    {
        "type": "message_delta",
        "delta": {"stop_reason": "tool_use", "stop_sequence": None},
        "usage": {"output_tokens": 40},
    },
    {"type": "message_stop"},
]


def thinks_then_calls(request: httpx2.Request) -> httpx2.Response:
    sent.append(json.loads(request.content))
    body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in THINKING_EVENTS)
    return httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body.encode()
    )


thinker = AnthropicModel(
    client=anthropic.AsyncAnthropic(
        api_key="not-a-real-key",
        http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(thinks_then_calls)),
        max_retries=0,
    ),
    model="test-model",
)
fix_it = Exchange(
    instructions="Fix the bug.", messages=[Message.user("Fix calc.py")], tools=[read_file]
)
asking = asyncio.run(thinker.generate(exchange=fix_it, progress=Quiet())).message()
print(asking)
# Message(role='assistant', calls=[ToolCall(call_id='toolu_1', name='read_file', arguments={'path': 'calc.py'})], sealed=<1 records>)
print([(record["vendor"], record["block"]["type"]) for record in asking.sealed()])
# [('anthropic', 'thinking')]

The reply's repr shows only how many sealed records it holds, never their content. Now send the tool's result back, the way the agent's next model call does, and look at the assistant turn in the request:

from gvn.harness.messages import ToolResult

next_round = Exchange(
    instructions="Fix the bug.",
    messages=[
        Message.user("Fix calc.py"),
        asking,
        Message.tool(results=[ToolResult(call_id="toolu_1", content="def average(numbers): ...")]),
    ],
    tools=[read_file],
)
asyncio.run(thinker.generate(exchange=next_round, progress=Quiet()))
assistant_turn = sent[-1]["messages"][1]["content"]
print([block["type"] for block in assistant_turn])  # ['thinking', 'tool_use']
print(assistant_turn[0]["signature"])  # c2lnbmVk

The thinking block went back first, byte for byte, before the tool call, as it came.

What to know about sealed content:

  • It never goes anywhere else. It is part of the message's value (equality, the Dto or plain-data form, the journal, the transcript), but nothing routes on it, and it never reaches a tool, a policy, an approver, a summariser or an outcome.
  • Same vendor only. The Anthropic adapter sends back every record whose vendor is "anthropic", whatever model wrote it; the API drops, unbilled, the blocks the current model cannot read. Another vendor's records are never sent, so a harness can change vendor in the middle of a journal. The OpenAI adapter does the same with its own records, below.
  • Original order. A turn whose blocks came as thinking, then at most one text block, then tool calls (what Claude Haiku 5.5 sends) is sent back in that order. Any other order (thinking between tool calls, several text blocks) is recorded on the first record as "layout" and replayed block for block.
  • It costs. Sealed content is journaled, about 5.5 bytes per thinking token, and it is billed as input on the next call.
  • Reducing history strips it. The vendor binds thinking to everything before it, so it is only valid while that history is unchanged. When an actor's context budget reduces its conversation (clearing old tool results, keeping recent messages, or replacing old ones with a summary), every message the reduction returns loses its sealed content; the text and tool calls stay, and the vendor's cache of the conversation restarts. The vendor's own reduction, below, avoids both.

Reasoning on OpenAI

OpenAI's reasoning models think before they answer too, and the Responses API returns that work as reasoning items whose content is encrypted (encrypted_content): you cannot read it, but the service can. OpenAI asks for the reasoning items of a reply that called tools to be sent back with the tool results, so the model can continue its reasoning.

The adapter is stateless: it sends every request with store: false and the whole conversation as input, and never refers to anything the service kept (no previous_response_id). gvn's journal stays the only record of a run, so a run replays from it and can change vendor. The encrypted content is what makes that possible: the reasoning travels in the request itself.

So OpenAIModel keeps each reasoning item as a sealed record, exactly as it arrived, with "vendor": "openai", and sends every OpenAI record back with its assistant turn, in its original place, keys sorted. The rules above apply unchanged: other vendors' records are never sent, nothing outside the adapter reads them, and cutting history strips them. Two points are specific to OpenAI:

  • Order and phase. A reply whose items came as reasoning, then at most one message, then tool calls needs nothing more. Any other order, or a message labelled with a phase ("commentary" or "final_answer", which OpenAI asks to be sent back), is recorded on the first record as "layout". A reply without reasoning has no record to hold it, so its phase is not kept.
  • Reasoning the service cannot decrypt is rejected, not dropped. OpenAI omits reasoning that a different model family cannot use, but reasoning whose encrypted content it cannot verify fails the call (HTTP 400, "could not be verified"). A journal written against one OpenAI organisation or compatible service, replayed against another, may therefore be rejected.

Reasoning on Chat Completions

Services that show a model's reasoning send it beside the text as reasoning_content. ChatCompletionsModel joins the fragments and, when the result is not empty, keeps it as one sealed record, {"vendor": <vendor>, "model": <the model id>, "block": {"reasoning_content": <the text>}}. It is the vendor you gave that labels the record. When the assistant message is sent again, with the tool results, a record of this adapter's vendor (whatever its model) goes back as that message's reasoning_content. Services that reason across tool rounds require this; services that do not simply read it as the field it is. Another vendor's records are never sent, so a conversation begun on another vendor continues here without its reasoning, and the reasoning one service returned never reaches another. The reasoning text is not reported to progress: only the answer's text is.

Structured answers on each vendor

An Exchange may carry an answer schema (Exchange.answer(), a kernel Record), which an agent built with answer= puts there; Structured answers shows the whole path. Each adapter asks its vendor to constrain the reply's text to that schema:

Anthropic OpenAI (Responses API) Chat Completions
request field output_config: {"format": {"type": "json_schema", "schema": ...}}, beside effort text: {"format": {"type": "json_schema", "name": "answer", "schema": ..., "strict": true}} response_format: {"type": "json_schema", "json_schema": {"name": "answer", "schema": ..., "strict": true}}
where the answer arrives the reply's text the reply's text (output_text) the reply's text
refusal stop_reason: "refusal": a ModelFailure a refusal content part: a ModelFailure a refusal in the reply: a ModelFailure
cut off by the token limit stop_reason: "max_tokens": a ModelFailure an incomplete reply: a ModelFailure finish_reason: "length": a ModelFailure

The adapter sends the schema exactly as gvn renders it, or refuses it before calling (a ModelFailure that is not retryable, and a ValueError from the adapter's answer_format if you check up front). It never loosens a schema, and the refusal names what the vendor cannot express. Every adapter supports schemas made from simple enums, records, lists, nullable fields, numbers, booleans and text within that adapter's limits. Run answer_format(schema) from the chosen adapter to check before calling the model. Anthropic limits the total optional and nullable fields and rejects bounded integers. ChatCompletionsModel refuses a schema under the same rules as OpenAIModel: an optional field, MapOf, Json(), more than 10 levels of nested objects, more than 1,000 enum values or more than 5,000 properties. Anthropic does not guarantee the letter case of an enum value it returns, and gvn's check is exact, so use lower-case identifiers as enum values. A call that asks Anthropic both to cite documents and to constrain the answer is failed by the adapter before it is sent.

ChatCompletionsModel asks for a structured answer in one way, the strict json_schema response_format above, and in no other: it never asks for JSON some other way in its place. Whether the service takes it is the service's decision. A service that does not takes the request as an error, and the call fails, not retryable, with the service's message as the reason; the adapter makes no second attempt.

Images and documents

A user Message may carry attachments after its text: images (PNG, JPEG, GIF, WebP) and PDF documents, each an Attachment from gvn.harness.messages. Give each either its bytes with a media type, or an https:// URL the vendor fetches itself:

from gvn.harness.messages import Attachment

chart = Attachment.image(data=b"\x89PNG\r\n\x1a\n" + bytes(32), media_type="image/png")
contract = Attachment.document(url="https://example.com/contract.pdf", title="Contract")
look = Message.user(text="What does the chart show?", attachments=[chart, contract])
print([attachment.kind() for attachment in look.attachments()])  # ['image', 'document']

gvn checks what it can without a network: one of data or URL, a supported media type, bytes that start the way that type's files start, at most 5 MB of data (ATTACHMENT_LIMIT), and an https:// URL of at most 2,048 characters. The image bytes above only exercise the header check. Pass a complete image when calling a real model. An Agent or a Choice takes attachments with its prompt, in the started event's "attachments" (their plain Dto forms: plain-data copies gvn can journal and rebuild).

Anthropic OpenAI Chat Completions
image by data an image block, base64 source input_image, image_url a data: URL, detail: "auto" an image_url part, url a data: URL
image by URL an image block, url source input_image, image_url the URL an image_url part, url the URL
PDF by data a document block, base64 source, with its title input_file, file_data a data: URL, filename the title a file part, file_data a data: URL, filename the title (or document.pdf)
PDF by URL a document block, url source input_file, file_url refused before any call (not retryable): the format has no URL form of a file

On Chat Completions the message's text is the first part, then one part per attachment; a message without attachments is plain text. A service that does not take a part answers with an error, which is a failure that is not retryable.

Where the bytes are kept. Attachment data is journaled inline, as base64, so the journal stays the one record of a run. Measured with the in-memory journal: a 100 KB image in an agent's prompt adds about 134 KB to the journal (the started record) and about 134 KB to the latest snapshot of the agent; the first snapshot, taken before the prompt, does not grow. Every model call of the run sends the image again, since the whole conversation is sent each time. Larger files belong at a URL.

Images and documents from tools

A tool can show the model media too: a screenshot tool, a tool that renders a chart, an MCP server (a separate program that offers tools over a standard protocol) that answers with a picture. Such a tool's run returns a ToolOutput instead of plain JSON. Its content is the JSON result, read by the model as before; its attachments are Attachment values, the same checked images and PDFs a user message carries, which the model sees right after the JSON. Adding a tool writes one step by step. Here is the value itself:

from gvn.harness.tools import ToolOutput

screenshot = Attachment.image(data=b"\x89PNG\r\n\x1a\n" + bytes(32), media_type="image/png")
returned = ToolOutput(content={"page": "checkout"}, attachments=[screenshot])
print(returned.content(), [attachment.kind() for attachment in returned.attachments()])
# {'page': 'checkout'} ['image']

The runtime turns it into a ToolResult whose attachments() are those images. One result holds at most 20 attachments (RESULT_ATTACHMENTS) and at most 5 MB of data together (RESULT_ATTACHMENT_LIMIT), and its documents cannot ask to be cited (citations are for a person's documents). Each adapter puts them in its vendor's tool-result shape:

Anthropic OpenAI (Responses API)
a result with attachments the tool_result block's content becomes a list: a text block with the JSON, then one image or document block per attachment the function_call_output item's output becomes a list: an input_text part with the JSON, then one input_image or input_file part per attachment
a result without content is the JSON text, as before output is the JSON text, as before
documented by "Handle tool calls": a tool result's content blocks "can use the text, image, document, or search_result types" the API reference: output is "a string or an array of content outputs (text, image, file)"

ChatCompletionsModel sends a result with attachments the same way: content becomes a list, a text part with the JSON, then one image_url or file part per attachment, built as for a user message above.

Anthropic and OpenAI accept every media type an Attachment allows in a tool result, so nothing is dropped or replaced by a description. A model that cannot read images answers the call with an error (HTTP 400), which becomes a ModelFailure that is not retryable, as any invalid request does.

Attachments are for the model: the policy, a person approving a call and anything that routes see the JSON content, and an outcome's attempts carry the JSON content only. When a conversation's context budget summarises old messages, the summariser is shown each attachment's description (kind, media type and size, or its URL) instead of its bytes, for tool results and user messages alike, so a summary round never resends them.

What it costs in the journal. Measured with the in-memory journal: a tool returning a 100 KB image adds 133,411 bytes to the tools_returned record that brings it (base64, about 1.33 bytes per byte), and the same to every snapshot of the agent taken after it; earlier snapshots and other records do not grow. As for a prompt's images, every later model call of the run sends the image again.

Citations

When a vendor ties part of a reply to a source, the adapter keeps it on the assistant Message as a citation record: {"vendor", "start", "end", "source"}, meaning text[start:end] rests on source (the vendor's own description of the passage, page or web page, as it sent it). An agent's outcome carries the final reply's citations under "citations" when there are any. They are data for people and for code that shows sources: nothing routes on them, and they are not sent back to the model.

  • Anthropic cites documents when asked: Attachment.document(..., cited=True) sends citations: {"enabled": true}, and the reply's text blocks come back with char_location, page_location or content_block_location citations (and web_search_result_location with web search). The span of a citation is its text block.
  • OpenAI cites through its hosted tools (url_citation annotations from web search, file_citation from file search); it does not cite document inputs, so cited has no effect there.

Server tools

Both vendors can run some tools themselves, inside the model call: web search, web fetch, code execution, file search. gvn does not govern them. Your policy, approvals, tool budget and invoke_tools never see their calls, and their cost is billed inside the model call. So they are off by default, and you turn one on explicitly, by passing its definition to the adapter as given in the vendor's documentation:

# not runnable: it needs a real API key.
model = AnthropicModel(
    client=anthropic.AsyncAnthropic(),
    model=os.environ["MODEL_ID"],
    server_tools=[{"type": "web_search_20260209", "name": "web_search", "max_uses": 3}],
)

And on OpenAI:

# not runnable: it needs a real API key.
model = OpenAIModel(
    client=openai.AsyncOpenAI(), model=os.environ["MODEL_ID"], server_tools=[{"type": "web_search"}]
)

What gvn does with them: their blocks in a reply (Anthropic's server_tool_use and *_tool_result, OpenAI's web_search_call, file_search_call, code_interpreter_call and image_generation_call items) are kept as sealed content, in their original place, and sent back unmodified to the same vendor, so a conversation that used them can continue. Anthropic may pause a long server-tool turn (pause_turn); the adapter does not resume it, and the call fails.

The vendor's own context reduction

An agent or a conversation keeps its conversation within its model's context window with a context budget: gvn measures the conversation and reduces it on its own side. Both vendors can also reduce a conversation on theirs (clearing old tool results, or compacting older turns into a summary), which keeps the model's carried thinking and the vendor's cache valid. gvn does not wrap that in a reduction step. It is an adapter setting, off by default, passed through as the vendor defines it, as server tools are:

# not runnable: it needs a real API key.
model = AnthropicModel(
    client=anthropic.AsyncAnthropic(),
    model=os.environ["MODEL_ID"],
    context_window=int(os.environ["MODEL_CONTEXT_WINDOW"]),
    context_edits=[{"type": "compact_20260112"}],
)

And on OpenAI:

# not runnable: it needs a real API key.
model = OpenAIModel(
    client=openai.AsyncOpenAI(),
    model=os.environ["MODEL_ID"],
    context_management=[{"type": "compaction", "compact_threshold": 200000}],
)
  • Anthropic: context_edits are sent as given, in order, as context_management.edits. Their type must be one the adapter knows (gvn.adapters.anthropic.CONTEXT_EDITS); the adapter adds the beta flag each one needs, and building it with edits needs a client that offers the beta endpoint.
  • OpenAI: context_management entries are sent as given.

What gvn does with it: the adapter keeps what the vendor returns to be sent back (Anthropic's compaction block, OpenAI's compaction item) as sealed content, in its place, and sends it back unmodified, so later calls continue from the vendor's summary. The next reply's usage shows a smaller conversation, and the actor's own budget measures that as usual. What gvn leaves on the vendor's side: it passes the setting through, and the vendor's reduction is not recorded as a reduction (the outcome's "reductions" does not count it) and is not replayed offline. gvn's own transcript is unchanged: it keeps, journals and sends every message. On Anthropic, the tokens the compaction pass itself used are billed but not in the recorded usage. An Anthropic turn paused after compacting fails, as a paused server-tool turn does.

What is translated

Each adapter translates between gvn's vocabulary and the vendor's, in both directions. The first table is Anthropic and OpenAI; Chat Completions follows it.

gvn Anthropic OpenAI (Responses API)
Exchange.instructions() the system prompt (omitted when empty) instructions (omitted when empty)
a user Message a user turn a user message item
an assistant Message an assistant turn: its sealed Anthropic blocks, a text block and one tool-use block per ToolCall, in the original order its sealed OpenAI reasoning items, an assistant message item with its text and one function_call item per ToolCall, in the original order
a tool Message a user turn with one tool-result block per ToolResult, flagged as an error when it failed; its attachments after the JSON in the block one function_call_output item per ToolResult; a failed result's content is wrapped as {"content": ..., "error": true}, because the protocol has no error flag; its attachments after the JSON in output
each ToolSpec a tool with its JSON Schema a function tool with its JSON Schema and strict: false, so the schema is used as written
Exchange.answer() output_config.format text.format, strict
a user Message's attachments image and document blocks after the text input_image and input_file parts after the text
an instruction Message (trusted text from harness code, see Conversations) a system message inside messages, in its place a message item with role developer, in its place

ChatCompletionsModel translates to the Chat Completions format, where the whole conversation is the messages of every request:

gvn Chat Completions
Exchange.instructions() a leading system message (omitted when empty)
a user Message a user message; its attachments make content a list of parts
an instruction Message a system message with its text, in its place
an assistant Message an assistant message: its text as content (none when it has no text), one tool_calls entry per ToolCall (arguments as JSON text, keys sorted), and its reasoning_content when it holds a sealed record of this adapter's vendor
a tool Message one tool message per ToolResult, with its tool_call_id; a failed result's content is wrapped as {"content": ..., "error": true}, because the format has no error flag
each ToolSpec a function tool with its JSON Schema, in name order with every object's keys sorted; tools is omitted when there are none, and tool_choice is never sent, so the model decides
Exchange.answer() response_format, strict json_schema

The adapter reads only the first choice of a reply.

The reply is streamed. Each text fragment goes to the Progress the Governor supplies, so it reaches your outputs as a delta signal while the model is still writing. When the stream ends, the adapter returns a Reply with the full text, the tool calls (ids and names as the service gave them, arguments parsed from JSON), any sealed thinking blocks, and token usage.

A reply's citations become citation records on the Message, and enabled server tools' blocks become sealed content (see the sections above, which name the adapters they apply to).

Two details: Anthropic's prompt-cache tokens (written and read) are added to the input token count, as usage explains. OpenAI reports usage on the event that ends the reply; a compatible service that does not report it gives zero. On Chat Completions the usage arrives on the last chunk of the stream.

When a call fails

The two tables below name Anthropic and OpenAI; ChatCompletionsModel follows the same lines, as the next paragraph says. As step 6 showed, every failure becomes a ModelFailure with a reason() and a retryable() flag. Which failures are retryable:

Retryable Anthropic OpenAI
yes rate limiting, overload, server errors (5xx), timeouts, connection errors, a transient conflict, a stream that ended before the reply was complete rate limiting, server errors (5xx), timeouts (including 408), connection errors, a conflict (409), a stream cut off before the model finished, a reply the service failed with a server error
no bad requests, authentication, permission, not found (check the model id), a request that is too large, a reached spend limit, billing errors bad requests (including an effort level the model does not support, and reasoning the service cannot verify), authentication, permission, not found (check the model id and base URL), an exhausted quota, an unprocessable request

On Chat Completions, rate limiting (429), server errors (5xx), timeouts and connection errors are retryable; every other status error (bad request, authentication, permission, not found, unprocessable) is not. An error object that arrives inside the stream is a failure: retryable unless its code or type says the request was at fault.

Some replies arrive without an HTTP error and are still unusable. They are failures that are not retryable, because acting on them would be wrong and sending the same request again would not cure them:

  • a reply cut off by the token limit (Anthropic max_tokens, OpenAI an incomplete reply for max_output_tokens): a truncated tool call must not be run;
  • a refusal, or a reply stopped by a content filter;
  • tool arguments that are not a JSON object, or are not valid JSON at all;
  • a stop or finish reason the adapter does not recognise (on Chat Completions: length and content_filter are failures that are not retryable, and any other finish_reason than stop, tool_calls or function_call is a retryable failure naming it, as is a stream that ends without one).

A conversation too large for the window fails with exceeded_context() true, and is not retryable: Anthropic's model_context_window_exceeded stop reason and its "prompt is too long" 400, and the context_length_exceeded error code of OpenAI and of Chat Completions, wherever in the response it arrives. Nothing else sets it; a reply cut off by the token limit is the token limit. The model_failed event carries "exceeded_context": true, and an agent or a conversation routes on it: it reduces its conversation if its context budget allows, or ends overflowed (see Context management).

A failure carries two more facts when the vendor gave them: retry_after(), the seconds the service asked to wait (its retry-after-ms or retry-after header, read as a number of seconds; an HTTP date is not read), and usage(), the tokens a refused or cut-off reply spent. Both reach the journal with the model_failed event.

The adapters can include a one-line excerpt of the service's error message, up to 160 characters. They redact the client API key. Anthropic also redacts the client's auth token, and the two OpenAI SDK adapters redact strings shaped like sk- keys. Error details can still contain other request values, such as the model id or a tool-call id. Treat them as service output when choosing what to log.

Who retries

By default gvn's ModelFulfiller does not retry. It turns any ModelFailure into a model_failed event with the reason, and the reference agent moves to failed (unless the failure says the conversation exceeded the context window, above). The retryable() flag is information for whoever decides about retries:

  • The SDK client. Both SDKs retry rate limits, server errors and connection errors themselves, with backoff, according to the max_retries and timeout you set on the client.
  • The ModelFulfiller, when you ask it to, with a Retry (see the next section).
  • A Model of your own that wraps an adapter. Use the injected Clock (the port gvn reads the time from) for any waiting, so tests can advance a ManualClock (a fake clock you move by hand) instead of sleeping.

Pick one place. Retries in both the client and the fulfiller multiply: two client retries inside each of three fulfiller attempts is nine calls.

Retries and fallback models

Retry (from gvn.harness.ports) makes the ModelFulfiller try a failed call again when the failure is retryable. It sleeps only on the Clock you give it, and spreads its delays with a jitter source you can fix in tests:

from gvn.runtime.fulfillers import ModelFulfiller
from gvn.harness.ports import Retry
from gvn.testing.fakes import ManualClock

retry = Retry(attempts=3, clock=ManualClock(), first_delay=1.0, longest_delay=30.0, jitter=lambda: 0.0)
print(retry.delay(attempt=1), retry.delay(attempt=2), retry.delay(attempt=3))  # 0.5 1.0 None
print(retry.delay(attempt=1, retry_after=7.0))  # 7.0
print(retry.delay(attempt=1, retry_after=60.0))  # None

attempts counts every call, so attempts=3 is two retries. Each delay doubles from first_delay up to longest_delay, scaled into its upper half by jitter() (a float in [0, 1); random.random by default). A retry-after from the vendor wins when it is longer, and one longer than longest_delay is not waited for: the failure is reported with its retry_after for a scheduler to act on. A failure that is not retryable is never retried.

Hand it over as ModelFulfiller(model=..., toolbox=..., retry=retry). What the journal shows: the event that finally answers the request (model_replied, or the last model_failed) carries "retries", one entry per attempt given up on, with its reason, the seconds waited, and the vendor's retry_after and reported usage when known. The actor handles one final answer. Earlier attempts can still incur charges, run vendor-hosted tools, or send streamed text that the application has already displayed. A crash before the answer is recorded loses the retry history. Recovery starts a new sequence of attempts.

FallbackModel(models=[...]) is a Model that asks each model in turn and moves on when one fails retryably; a failure that is not retryable is raised at once, since another model would be asked the same thing. Each vendor's sealed content stays with that vendor, so a conversation can move from one to the other. Wrap it in a ModelFulfiller with a Retry to retry the whole list. Successful fallback reports the answering model's usage. If all members fail retryably, the combined failure carries the last member's usage when known. Earlier members' usage does not appear as separate journal entries, just as SDK retries are handled inside the client. See Spending and rate limits for the tally's scope.

Holding calls to the account's limits

A Retry deals with one call that failed. To limit how many calls the adapters start at once or per minute in one process, wrap each adapter in a ThrottledModel (in gvn.runtime.throttles) over one shared throttle. A limit across processes needs a throttle over shared storage. A throttled model is a Model, so it goes wherever the adapter went, and a ModelFailure with a retry_after makes everyone who shares the throttle wait, not only the caller that was told:

# not runnable: continues step 4; limit, calls and clock are yours.
from gvn.runtime.throttles import ConcurrencyThrottle, RateThrottle, ThrottledModel, Throttles

account = Throttles([ConcurrencyThrottle(limit), RateThrottle(calls, 60.0, clock)])
fulfiller = ModelFulfiller(model=ThrottledModel(model, account), toolbox=Toolbox(tools=[...]))

Spending and rate limits covers the throttles, sharing one across models, and writing one that holds across processes.

Cancellation

When the Governor no longer wants a model call (the run was interrupted, or a workflow's join, the rule that ends a stage once enough of its children have finished, dropped the agent that asked), it cancels the task. The adapter lets asyncio.CancelledError propagate and closes the stream, so the HTTP connection is released and no partial reply is used. Nothing is journaled for a cancelled call; if the run is resumed, the call is made again.

Other services

A service that implements the Chat Completions format is reached with ChatCompletionsModel, as step 2 showed for DeepSeek: the client's base_url, the model id and the vendor change, and nothing else. Run your harness's scenarios against the service you choose.

Services of the Responses API

OpenAIModel speaks OpenAI's Responses API (POST /responses), which OpenAI names as the way to use function tools together with a reasoning effort. Another service that implements the same API can be used by pointing the OpenAI client at it with base_url and passing the id that service uses for its model:

# not runnable: it needs a running service.
import os

import openai

from gvn.adapters.openai import OpenAIModel

client = openai.AsyncOpenAI(base_url=os.environ["MODEL_BASE_URL"], api_key=os.environ["MODEL_KEY"])
model = OpenAIModel(client=client, model=os.environ["MODEL_ID"])

What the service must support:

  • The Responses API. A service that speaks Chat Completions is reached with ChatCompletionsModel instead.
  • A stateless request. The adapter sends store: false and the whole conversation each time, and asks for encrypted reasoning (include: ["reasoning.encrypted_content"]).
  • Empty or whitespace-only tool arguments mean "no arguments" ({}), and usage is optional.

Run your harness's scenarios against the service you choose.

Embeddings for a memory

A memory can recall by meaning as well as by words when it is given an embedder, an object that turns texts into vectors (Recall by meaning). OpenAIEmbedder (in gvn.adapters.openai, the openai extra) is the embedder over the embeddings endpoint (POST <base URL>/embeddings), a format many embedding services accept at their own base URL. It is built over an openai.AsyncOpenAI you create, as the model adapters are, and handed to a memory; nothing else in gvn sees it, and it is not a Model:

# not runnable: it needs a real API key and an embedding model id.
import os

import openai

from gvn.adapters.openai import OpenAIEmbedder
from gvn.adapters.sqlite import SqliteMemory

client = openai.AsyncOpenAI()  # reads its key from the environment
embedder = OpenAIEmbedder(client, os.environ["EMBEDDING_MODEL_ID"])
memory = SqliteMemory("memory.db", embedder=embedder)

OpenAIEmbedder(client, model, dimensions=None, name=None, batch=256). The model id has no default. dimensions, when given, is sent with each request; batch is the most texts sent in one request, and more go as several requests, one after the other. Every vector comes back in the order of the texts. The embedder never retries: the client's own retry settings apply, and a request that still fails is one EmbedderFailure, whose reason never holds the API key or the texts sent, and which the memory raises as a MemoryFailure.

A memory keeps every vector under the embedder's name() and compares only vectors of one name. The default name is "openai:<model>", with ":<dimensions>" added when dimensions is given. When the client points at another service with base_url, pass name= too: the same model id on two services need not make the same vectors, and the name is what keeps them apart.

Failures you will meet

  • A synchronous client (anthropic.Anthropic() instead of AsyncAnthropic()) is a TypeError when you build the adapter.
  • A wrong model id fails at the first call, not when you build the adapter: a ModelFailure, not retryable, whose reason says to check the model id.
  • A reply cut off by the token limit is a failure, not a short answer. Raise max_tokens if your harness's replies are long.
  • Retries happen in the SDK client, with the max_retries and timeout you set on it, unless you give the ModelFulfiller a Retry; without one, an agent whose model call failed ends in failed.
  • An answer schema the vendor cannot express fails at the first call, before anything is sent, naming what it cannot express.
  • An effort level the model does not accept fails at the first call: the API rejects it, and the adapter does not check which levels a model supports. The reason quotes the service, which names the levels it does support.
  • A structured answer the service does not take fails at the first call, not retryable: ChatCompletionsModel sends the strict json_schema response_format and nothing else, and the reason quotes the service's message.
  • A PDF given by URL on Chat Completions fails before any call, not retryable: give its bytes.
  • An OpenAI reply that reasons a lot can hit max_tokens before it writes anything: reasoning counts towards the limit. Raise it, or lower the effort.

Recap

  • Install the extra, build the vendor's async client yourself, and hand it to AnthropicModel(client=..., model=...), OpenAIModel(client=..., model=...) or, for a service with a Chat Completions endpoint, ChatCompletionsModel(client, model, vendor=...) over an openai.AsyncOpenAI with that service's base_url.
  • Read the model id from configuration: there is no default.
  • The adapter goes where a fake went, usually into ModelFulfiller(model=..., toolbox=...); nothing else in the harness changes. roles={name: model} serves the actors and steps that name a model_role with another model.
  • Every failure is a ModelFailure with a reason, a retryable flag, and the vendor's retry_after and tokens spent when known; the SDK client retries, or a Retry on the ModelFulfiller does. FallbackModel moves to another model on retryable failures. ThrottledModel applies a shared throttle to calls made through it.
  • Each adapter says its service (Model.provider()), and it is journaled with every model answer.
  • An answer schema is sent through each vendor's own structured output, exactly or not at all (on Chat Completions, as a strict json_schema and nothing else: the service takes it or rejects the call); images and PDFs ride on user messages; citations are kept; server tools are off unless you pass them.
  • AnthropicModel caches the prompt by default (cache=True) and takes an effort; OpenAIModel and ChatCompletionsModel take an effort too (the latter sends it as reasoning_effort), and caching is automatic on OpenAI. Usage has four figures, and input_tokens counts every input token, cached or not.
  • Anthropic's thinking, OpenAI's encrypted reasoning and a Chat Completions service's reasoning_content are carried between tool rounds as sealed content, sent back only to the same vendor, never to a tool, a policy or a person.
  • context_window= gives the model's window to the actors' context budgets; a conversation the vendor refuses as too large fails with exceeded_context; the vendor's own context reduction is an adapter setting (context_edits=, context_management=) that gvn passes through and does not record as a reduction.
  • OpenAIEmbedder(client, model) turns texts into vectors over an embeddings endpoint, for a memory that recalls by meaning; it is handed to the memory, and a client pointed at another service gets its own name=.

Next

Choose by what you need now: