What is a Model? The provider contract
A weft.Model is the provider seam: one method, Stream(ctx, req), that takes one step’s weft.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:
// 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"} }weft.New(echoModel{}) is a working agent; asked “hello”, it answers you said: hello.
How it works
Section titled “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
Section titled “The model contract”Model.Stream returns an iter.Seq2[ModelEvent, error] that must:
- Yield any number of
ModelTextDelta,ModelReasoningDeltaandModelToolCallvalues, optionally interleaved withModelToolCallDeltaprogress, then exactly oneModelFinish. - Report a failure as a single terminal
(nil, err), with nothing after it. - 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:
noFinish := wefttest.Raw(weft.ModelTextDelta{Text: "hello"}) // a stream with no ModelFinishagt := 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)ErrModelContract: trueweft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinishAn 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: the request uses something the model cannot carry, such as aFilePartof a media type the provider does not accept. It is a run error, so a caller canerrors.Ison it and fall back to another model.weft.ErrContextOverflow: the request exceeds the model’s context window. See run errors.
The loop also protects adapters from each other and from themselves:
- Each request gets fresh copies of the
MessagesandToolsslices, of each message’sContentslice, and ofParams’ values (the pointer knobs andStop). 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’sArgs, a file’sData) and theToolDeffields 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
ToolSourcethat rebuilds its list every step costs a conversion, not a growing cache.
The request
Section titled “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).
Stream events
Section titled “Stream events”weft.ModelEvent is a sealed interface with five types:
| Event | Fields | Meaning |
|---|---|---|
ModelTextDelta | Text | An increment of assistant text. |
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 | 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 | 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 | 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
Section titled “Model identity”A model can name itself by implementing the optional method Info() weft.ModelInfo. A weft.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) 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:
func (m countingModel) Info() weft.ModelInfo { return weft.InfoOf(m.next) }func (m countingModel) Unwrap() weft.Model { return m.next }Unwrap
Section titled “Unwrap”Middleware also declares the model it wraps with the optional method Unwrap() weft.Model. weft.Unwrap(m) 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:
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))}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 pins the walk.
Raw wire bodies
Section titled “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) returns the weft.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()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)reports one attempt’s exchange as aweft.rawrecord, attributed to the step and to the attempt in flight. A layer that reports both an attempt and its body reportsRawfirst.
A weft.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 covers the policy.
What it does not do
Section titled “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.Retryandmw.Fallback(Retry and fall back). - The core reads no reasoning. Reasoning text and signatures are stored and sent back, never interpreted.
Complete example
Section titled “Complete example”concepts/models.go runs the echo model, a stream that breaks the contract, and a middleware chain:
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}Run it from docs-site/examples:
go run ./concepts modelsgo test ./conceptsyou said: hello | 7 tokensErrModelContract: trueweft: run failed at step 0: weft: model violated the stream contract: stream ended without ModelFinishmain.countingModel {docs echo-1}main.echoModel {docs echo-1}Best practices & gotchas
Section titled “Best practices & gotchas”- Forward
InfoandUnwrapin every model middleware. WithoutInfo, runs report a zero model; withoutUnwrap, the chain walk stops at your wrapper.wefttest.ConformInfochecks the first. (Source:weft/core/agent.go:246-253) - Return when
yieldreturns false. The loop stops ranging when it fails the step, for example on an event afterModelFinish. Callingyieldagain makes Go panic, and the loop’s recover turns that into anErrModelContractrun 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
ErrUnsupportedrather 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
WantsRawbefore buffering a body. Raw records exist only in development with a destination that wants them. (Source:weft/core/report.go:202-215)
See also
Section titled “See also”- Connect a model provider: OpenAI, Anthropic, Gemini
- Prove a provider adapter with the conformance suite
- Retry and fall back when a provider fails
- Test an agent with a scripted model
Symbols used: weft.Model · weft.ModelRequest · weft.ModelEvent · weft.ModelTextDelta · weft.ModelReasoningDelta · weft.ModelToolCall · weft.ModelToolCallDelta · weft.ModelFinish · weft.ModelInfo · weft.InfoOf · weft.Unwrap · weft.WrapModel · weft.ErrModelContract · weft.ErrUnsupported · weft.ErrContextOverflow · weft.ReportFromContext · weft.Reporter · weft.RawPair · wefttest.Raw