---
title: What is a Model? The provider contract
description: A weft.Model is one method, Stream, that turns a ModelRequest into a stream of model events ending in exactly one ModelFinish; the loop enforces that contract.
url: https://weftgo.dev/docs/concepts/models/
type: concept
sources:
  - weft/docs/adr/0013-adapter-contract.md
  - weft/AGENTS.md rule 7
  - weft/core/model.go:9-62 (Usage, StopReason, ModelInfo), 149-224 (ModelRequest, Model and its stream contract), 226-304 (ModelEvent and the five events)
  - weft/core/agent.go:246-305 (ModelMiddleware, WrapModel, InfoOf, Unwrap), 918-925 (Agent.Model)
  - weft/core/errors.go:56-69 (ErrModelContract, ErrUnsupported), 118-125 (ErrContextOverflow)
  - 'v0.20.2: weft/core/model.go:149-167 (ModelRequest godoc: fresh Messages, Tools and Content slices; Params'' values copied, a write through a knob''s pointer or into Stop reaches neither the agent''s or run option''s Params, the caller''s variables, nor a later step or attempt record; the bytes behind a part and ToolDef fields stay shared); weft/core/mw/retry.go:109-111, weft/core/mw/model.go:31-33 (each try or model tried gets its own copy of the slices and Params values); docs-site/examples/middleware/params_test.go TestCapTemperature'
  - weft/core/loop.go:531-544 (fresh slice copies per request), 598-680 (contract enforcement), 707-728 (empty assistant turns are not appended)
  - weft/anthropic/convert.go:128-134 (an assistant message with no sendable blocks skipped), 230-231 and 288-289 (empty text dropped), 270-285 (unsigned reasoning dropped)
  - weft/openai/convert.go:48-55 and 203-241 (reasoning dropped; nothing sendable skipped); weft/google/convert.go:34-39 (a model content with no parts skipped), 299-302 (unsigned reasoning dropped)
  - weft/core/report.go:87-134 (RawPair), 136-160 (Reporter), 162-215 (ReportFromContext, Attempt, Raw, WantsRaw)
  - weft/CHANGELOG.md:5361 (the Unwrap convention), 6472, 6493, 6577
  - weft/example_test.go ExampleAgent_Model
  - docs-site/examples/concepts/models.go, concepts_test.go TestDemos/models
---

# What is a Model? The provider contract

A [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) is the provider seam: one method, `Stream(ctx, req)`, that takes one step's [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) and yields that step's output as model events, ending in exactly one `ModelFinish`. The provider adapters implement it over the vendors' official Go SDKs; `wefttest.Script` implements it for tests; so can you. The loop checks every stream against the contract, so a broken model fails the run instead of corrupting the transcript.

A complete model, in `concepts/models.go`:

```go title="concepts/models.go"
// echoModel is a complete weft.Model: it streams one text delta that
// repeats the last message, then exactly one ModelFinish.
type echoModel struct{}

func (echoModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	return func(yield func(weft.ModelEvent, error) bool) {
		if err := ctx.Err(); err != nil {
			yield(nil, err) // a failure is one terminal (nil, err)
			return
		}
		last := req.Messages[len(req.Messages)-1].Text()
		if !yield(weft.ModelTextDelta{Text: "you said: " + last}, nil) {
			return
		}
		yield(weft.ModelFinish{Reason: weft.StopEndTurn, Usage: weft.Usage{InputTokens: 4, OutputTokens: 3}}, nil)
	}
}

// Info names the model on RunStart.Model and in the manifest (optional).
func (echoModel) Info() weft.ModelInfo { return weft.ModelInfo{Provider: "docs", Name: "echo-1"} }
```

[concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go)

`weft.New(echoModel{})` is a working agent; asked "hello", it answers `you said: hello`.

## How it works

Each step, the loop builds a request, passes it through the `WrapModel` middleware chain, and ranges over the stream the innermost model returns. Text deltas become `TextDelta` events and the assistant message's text; tool calls are collected for the step's tool batch; `ModelFinish` closes the step with its stop reason and usage. The adapter's job is translation in both directions: the request into the vendor's wire format, the vendor's stream into these events.

## The model contract

[`Model.Stream`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) returns an `iter.Seq2[ModelEvent, error]` that must:

1. Yield any number of `ModelTextDelta`, `ModelReasoningDelta` and `ModelToolCall` values, optionally interleaved with `ModelToolCallDelta` progress, then exactly one `ModelFinish`.
2. Report a failure as a single terminal `(nil, err)`, with nothing after it.
3. Honour `ctx`: when it is done, yield `(nil, ctx.Err())` if the stream has not finished.

The loop enforces it. A stream that ends without `ModelFinish`, yields an event after it, yields a tool call with an empty id or name, yields two tool calls with the same id in one step, or panics fails the run with an error wrapping [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract):

```go title="concepts/models.go"
noFinish := wefttest.Raw(weft.ModelTextDelta{Text: "hello"}) // a stream with no ModelFinish
agt := weft.New(wefttest.Script(noFinish))
_, err := agt.Generate(ctx, weft.Prompt("hi"))
fmt.Fprintln(w, "ErrModelContract:", errors.Is(err, weft.ErrModelContract))
fmt.Fprintln(w, err)
```

[concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go)

```text
ErrModelContract: true
weft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinish
```

An error yielded after `ModelFinish` fails the run as that stream error, `model stream: <err>`, not as `ErrModelContract`. `ErrModelContract` means an adapter bug, not an outage: a provider's own errors reach the caller unwrapped, as `model stream: <the provider's error>`. Two sentinels adapters wrap on purpose:

- [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported): the request uses something the model cannot carry, such as a `FilePart` of a media type the provider does not accept. It is a run error, so a caller can `errors.Is` on it and fall back to another model.
- [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow): the request exceeds the model's context window. See [run errors](https://weftgo.dev/docs/concepts/errors/#context-overflow).

The loop also protects adapters from each other and from themselves:

- **Each request gets fresh copies** of the `Messages` and `Tools` slices, of each message's `Content` slice, and of `Params`' values (the pointer knobs and `Stop`). A model or middleware may append, reassign a message or part, or write `*req.Params.Temperature`. Nothing reaches the transcript, the agent, the run option, the caller's variables or a later step. Only the bytes inside parts (a tool call's `Args`, a file's `Data`) and the `ToolDef` fields stay shared. Never modify them, and clone what you keep past the call.
- **Empty assistant turns never reach the transcript.** A step that streamed no text, no reasoning and no calls appends nothing, because providers reject empty content. All three adapters also skip an assistant message with nothing sendable (reasoning-only, say: openai drops all reasoning, anthropic and google drop unsigned reasoning) and drop empty text parts when they build the wire request; Google skips a content entry left with no parts.
- **Tool definitions are converted per request** by the adapters, so a `ToolSource` that rebuilds its list every step costs a conversion, not a growing cache.

## The request

A `ModelRequest` is everything one step needs, read-only for the model:

| Field | What it holds |
|---|---|
| `System` | The instructions plus the advertised tools' `PromptSnippet` text. |
| `Messages` | The transcript so far, as a fresh slice. |
| `Tools` | The tools this step advertises and will dispatch against, as a fresh slice. |
| `Thinking` | The reasoning level for this step; the zero value keeps the provider default. |
| `SequentialTools` | True under `Sequential()` or `Parallelism(1)`: ask the provider not to emit parallel tool-call batches. |
| `ToolChoice` | Whether the step must call some tool, a named tool, or none; the zero value is the provider default. |
| `Params` | Sampling overrides (`Temperature`, `TopP`, `MaxTokens`, `Stop`, `Seed`) for this request; nil fields keep the adapter's defaults. |

`PrepareStep` functions can rewrite any of these before the model sees them ([Rewrite the request each step](https://weftgo.dev/docs/guides/prepare-step/)).

## Stream events

[`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) is a sealed interface with five types:

| Event | Fields | Meaning |
|---|---|---|
| [`ModelTextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelTextDelta) | `Text` | An increment of assistant text. |
| [`ModelReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelReasoningDelta) | `Text`, `Signature` | An increment of provider reasoning. A delta with a non-empty `Signature` closes the current reasoning block, so one `ReasoningPart` per provider block survives the round trip. |
| [`ModelToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCall) | `ID`, `Name`, `Args`, `Signature` | One complete tool call. `ID` is echoed on the matching result and must be unique within the step; `Signature` is a token some providers attach to the call itself. |
| [`ModelToolCallDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCallDelta) | `Index`, `Name`, `Args` | Progress while the model writes a call's arguments: `Index` is the provider's fragment key, `Name` the best-known name so far, `Args` the fragment. The whole call still arrives as a `ModelToolCall`. |
| [`ModelFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelFinish) | `Reason`, `Usage`, `Raw` | Closes the step: the mapped `StopReason`, the step's token `Usage`, and the provider's own stop reason in `Raw` when the mapping was approximate (`refusal`, `content_filter`, …). |

Tool calls arrive whole: assembling a provider's streamed argument fragments is the adapter's job, which keeps the loop identical across providers. Adapters whose providers send calls whole, such as Google's, yield no `ModelToolCallDelta` at all.

## Model identity

A model can name itself by implementing the optional method `Info() weft.ModelInfo`. A [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) has two fields: `Provider` (`"openai"`, `"anthropic"`, `"wefttest"`) and `Name`, the vendor's model id. The loop puts it on `RunStart.Model`, the spans and the manifest. `Model` itself stays one method.

[`weft.InfoOf(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) returns `m`'s `ModelInfo`, or the zero value when `m` does not implement `Info`. Model middleware forwards identity with it, so a wrapped model still reports the model underneath. The `countingModel` middleware in `concepts/models.go` forwards both optional methods:

```go title="concepts/models.go"
func (m countingModel) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m countingModel) Unwrap() weft.Model   { return m.next }
```

[concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go)

## Unwrap

Middleware also declares the model it wraps with the optional method `Unwrap() weft.Model`. [`weft.Unwrap(m)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) walks one level and returns nil for a model that is not a wrapper, so a caller walks a chain without knowing the wrapper types:

```go title="concepts/models.go"
counting := func(next weft.Model) weft.Model { return countingModel{next: next, calls: &calls} }
agt := weft.New(echoModel{}, weft.WrapModel(counting))
for m := agt.Model(); m != nil; m = weft.Unwrap(m) {
	fmt.Fprintf(w, "%T %v\n", m, weft.InfoOf(m))
}
```

[concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go)

```text
main.countingModel {docs echo-1}
main.echoModel {docs echo-1}
```

`agt.Model()` is the chain as the loop calls it, outermost first. `mw.Retry`, `mw.Fallback` (unwrapping to its primary, the model its `Info` names), `mw.Log` and `mw.RepairJSON` all implement `Unwrap`. The walk ends at the first model that is not a wrapper. `weft/thread` walks the chain this way to find provider-native compaction under an agent's middleware. The core example [`ExampleAgent_Model`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.Model) pins the walk.

## Raw wire bodies

Code inside the model chain can report each provider request's raw wire exchange to the run's record. [`weft.ReportFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) returns the [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) of the model call `ctx` belongs to; outside a run's model call it is a no-op reporter, never nil. Reporting is not a seam: no report changes a step, a retry or a result.

- [`rep.WantsRaw()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.WantsRaw) reports whether a raw report would be recorded now. It is true only inside a run's model call, with content capture on, and with a destination that asked for raw bodies (`otel.RawBodies(true)`, development only). An adapter asks first and buffers no body when the answer is false.
- [`rep.Raw(pair)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) reports one attempt's exchange as a `weft.raw` record, attributed to the step and to the attempt in flight. A layer that reports both an attempt and its body reports `Raw` first.

A [`weft.RawPair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawPair) holds what the reporter knows; zero fields are left out of the record:

| Field | What it holds |
|---|---|
| `Request`, `Response` | The request as sent and the response as received; a streamed response is the raw stream bytes. |
| `MediaType`, `ResponseMediaType` | The two sides' media types, e.g. `application/json`, `text/event-stream`. |
| `Method`, `URL` | The request line. The record drops the URL's userinfo and credential query values. |
| `Status` | The HTTP status; 0 when no response arrived. |
| `RequestHeaders`, `ResponseHeaders` | The headers. The record never carries a credential header (`Authorization`, `X-Api-Key`, `Cookie`, …) or a Bearer or Basic value. |
| `RedactedHeaders` | Headers the reporter stripped itself, listed so the record says what is missing. |
| `RequestTruncated`, `ResponseTruncated` | Bytes the reporter did not keep past its own cap, counted into the record's cut. Each body is also capped at 256 KiB by the record. |
| `ResponseIncomplete` | The response body was not read to its end (closed unread, timed out, read error); the record marks that side incomplete. |

The bytes are content: the request carries the prompt. [Control what content leaves the process](https://weftgo.dev/docs/production/content-and-privacy/) covers the policy.

## What it does not do

- **A model does not run tools or keep history.** It sees one request and streams one step; the loop owns the transcript and the tool batch.
- **The loop does not retry.** A stream error fails the step; retries and fallbacks are model middleware, `mw.Retry` and `mw.Fallback` ([Retry and fall back](https://weftgo.dev/docs/guides/retries-and-fallback/)).
- **The core reads no reasoning.** Reasoning text and signatures are stored and sent back, never interpreted.

## Complete example

`concepts/models.go` runs the echo model, a stream that breaks the contract, and a middleware chain:

```go title="concepts/models.go"
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"iter"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/wefttest"
)

// echoModel is a complete weft.Model: it streams one text delta that
// repeats the last message, then exactly one ModelFinish.
type echoModel struct{}

func (echoModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	return func(yield func(weft.ModelEvent, error) bool) {
		if err := ctx.Err(); err != nil {
			yield(nil, err) // a failure is one terminal (nil, err)
			return
		}
		last := req.Messages[len(req.Messages)-1].Text()
		if !yield(weft.ModelTextDelta{Text: "you said: " + last}, nil) {
			return
		}
		yield(weft.ModelFinish{Reason: weft.StopEndTurn, Usage: weft.Usage{InputTokens: 4, OutputTokens: 3}}, nil)
	}
}

// Info names the model on RunStart.Model and in the manifest (optional).
func (echoModel) Info() weft.ModelInfo { return weft.ModelInfo{Provider: "docs", Name: "echo-1"} }

// countingModel is model middleware: it counts calls and forwards the
// rest, identity included.
type countingModel struct {
	next  weft.Model
	calls *int
}

func (m countingModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	*m.calls++
	return m.next.Stream(ctx, req)
}

func (m countingModel) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m countingModel) Unwrap() weft.Model   { return m.next }

// brokenModel shows the loop refusing a stream that never finishes.
func brokenModel(ctx context.Context, w io.Writer) error {
	noFinish := wefttest.Raw(weft.ModelTextDelta{Text: "hello"}) // a stream with no ModelFinish
	agt := weft.New(wefttest.Script(noFinish))
	_, err := agt.Generate(ctx, weft.Prompt("hi"))
	fmt.Fprintln(w, "ErrModelContract:", errors.Is(err, weft.ErrModelContract))
	fmt.Fprintln(w, err)
	return nil
}

// walkChain walks a wrapped model one middleware at a time.
func walkChain(w io.Writer) {
	var calls int
	counting := func(next weft.Model) weft.Model { return countingModel{next: next, calls: &calls} }
	agt := weft.New(echoModel{}, weft.WrapModel(counting))
	for m := agt.Model(); m != nil; m = weft.Unwrap(m) {
		fmt.Fprintf(w, "%T %v\n", m, weft.InfoOf(m))
	}
}

// demoModels runs the echo model, a contract-breaking model, and walks a
// middleware chain.
func demoModels(ctx context.Context, w io.Writer) error {
	res, err := weft.New(echoModel{}).Generate(ctx, weft.Prompt("hello"))
	if err != nil {
		return err
	}
	fmt.Fprintln(w, res.Text(), "|", res.Usage.Total(), "tokens")
	if err := brokenModel(ctx, w); err != nil {
		return err
	}
	walkChain(w)
	return nil
}
```

[concepts/models.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/concepts/models.go)

Run it from `docs-site/examples`:

```sh
go run ./concepts models
go test ./concepts
```

```text
you said: hello | 7 tokens
ErrModelContract: true
weft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinish
main.countingModel {docs echo-1}
main.echoModel {docs echo-1}
```

## Best practices & gotchas

- **Forward `Info` and `Unwrap` in every model middleware.** Without `Info`, runs report a zero model; without `Unwrap`, the chain walk stops at your wrapper. `wefttest.ConformInfo` checks the first. (Source: `weft/core/agent.go:246-253`)
- **Return when `yield` returns false.** The loop stops ranging when it fails the step, for example on an event after `ModelFinish`. Calling `yield` again makes Go panic, and the loop's recover turns that into an `ErrModelContract` run error. (Source: `weft/core/loop.go:617-628`)
- **Never modify a request's messages or tools.** The slices are copies, the values inside are not. (Source: `weft/core/model.go:149-157`)
- **Wrap `ErrUnsupported` rather than dropping a part.** A silently dropped file changes what the model sees; the error lets the caller fall back. (Source: AGENTS.md rule 2, `weft/core/errors.go:64-69`)
- **Ask `WantsRaw` before buffering a body.** Raw records exist only in development with a destination that wants them. (Source: `weft/core/report.go:202-215`)

## See also

- [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/)
- [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/)
- [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)
- [Test an agent with a scripted model](https://weftgo.dev/docs/testing/scripted-models/)

Symbols used: [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) · [`weft.ModelTextDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelTextDelta) · [`weft.ModelReasoningDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelReasoningDelta) · [`weft.ModelToolCall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCall) · [`weft.ModelToolCallDelta`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelToolCallDelta) · [`weft.ModelFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelFinish) · [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Unwrap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Unwrap) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.ErrModelContract`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelContract) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`weft.ReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) · [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) · [`weft.RawPair`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RawPair) · [`wefttest.Raw`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Raw)
