---
title: 'Connect a model provider: OpenAI, Anthropic, Gemini'
description: Construct weft's first-party adapters — openai.Model, anthropic.Model, google.Model — point them at a compatible server, and set their sampling, retry, timeout and escape-hatch options.
url: https://weftgo.dev/docs/guides/providers/
type: how-to
sources:
  - 'W11-auditA2-fix, v0.20.2: weft/core/request.go:219 (an address over 128 bytes reads empty), 227-254 (wireNames: duplicates and empty names not counted in dropped)'
  - weft/README.md:875-919 (Providers; prompt caching)
  - weft/openai/doc.go:1-35; weft/anthropic/doc.go:1-42; weft/google/doc.go:1-32
  - weft/openai/model.go:18-22 (Option; zero configuration), 49-53 (BaseURL; provider stays "openai"), 56 (APIKey), 58-66 (Client), 68-99 (MaxTokens, Temperature, TopP, Stop, Seed), 101-112 (IdleTimeout), 114-124 (MaxRetries), 126-161 (ExtraBody, ExtraHeaders), 163-173 (Model), 202-208 (OPENAI_BASE_URL), 292-297 (Info)
  - weft/openai/thinking.go:18-42 (ThinkingDialect, Dialect), 44-75 (resolveDialect hosts), 77-107 (effort and object mappings), 132-150 (ThinkingWire)
  - weft/openai/stream.go:36-42 (kill switch), 101, 183-190 (reasoning_content)
  - weft/openai/convert.go:157-180 (images only)
  - weft/anthropic/model.go:18-22, 48-54, 56-64, 66-91 (MaxTokens default 4096; no seed), 93-124, 116-122 (Thinking), 124-144 (PromptCache), 146-182, 184-192, 220-226 (ANTHROPIC_BASE_URL)
  - weft/anthropic/convert.go:58 (Seed dropped), 220-256 (image and PDF only), 366-382 (ThinkingWire)
  - weft/google/model.go:15-19 (credentials discovery), 44-60, 62-70 (int32 MaxTokens), 92-99 (Seed int32), 101-154 (ExtraBody, ExtraHeaders, IdleTimeout, MaxRetries off unless asked), 160-165 (lazy client), 238-251 (initClient)
  - weft/google/convert.go:186, 201, 94 (int32 ceilings wrap ErrUnsupported), 220-255 (file parts), 460-474 (ThinkingWire)
  - weft/google/stream.go:20-31 (kill switch before client init)
  - weft/core/env.go:5-20 (ModelRequestsAllowed); weft/core/errors.go:71-84 (ErrStreamIdle, ErrModelRequestsDenied)
  - weft/anthropic/convert.go:64-67 (Thinking(true) with an unset level sends adaptive)
  - the anthropic-sdk-go v1.72.0 module, its client file lines 63-80 (ANTHROPIC_AUTH_TOKEN); the genai v1.71.0 module, its client file lines 133-170 (GOOGLE_API_KEY, GEMINI_API_KEY, GOOGLE_GENAI_USE_VERTEXAI)
  - weft/openai/model.go:202-219, weft/anthropic/model.go:220-234 (client built at construction)
  - weft/core/model.go:50-61 (ModelInfo), 76-98 (ThinkingConfig, ThinkingWire convention)
  - 'v0.20.2, the WireFacts convention: weft/core/request.go:145-149 (32 names of 128 bytes), 152-194 (wireFacts: the first model along the Unwrap chain with WireFacts() (string, []string, []string); names only, sanitised whatever the method returns; nil when none answers; behind mw.Fallback the primary''s), 196-203 (serverAddress: host[:port], no host when an @ lies past the authority''s cut); weft/openai/model.go:203, 299-305 (WireFacts at 303); weft/anthropic/model.go:221, 314-317; weft/google/model.go:195, 280-283; weft/internal/adapterkit/wire.go:14-38 (sorted keys and header names; Endpoint: BaseURL, else the env var, else the default host); weft/docs/record-contract.md:640-664 (server_address per adapter, none for an injected Client; the Fallback primary rule and the attempt span''s model; extra_headers lowercased; 32 names, dropped)'
  - 'weft/core/model.go:185-192 (ToolChoice constrains what the provider is asked to emit, never execution: a call it emits anyway runs)'
  - weft/openai/conformance_test.go:89; weft/anthropic/conformance_test.go:93-101; weft/google/conformance_test.go:85-94; weft/core/wefttest/conformance/conformance.go:28-63 (Caps)
  - weft/openai/example_test.go ExampleModel, ExampleDialect; weft/anthropic/example_test.go ExampleModel; weft/google/example_test.go ExampleModel
  - weft/openai/extrabody_test.go:TestExtraBodyAndHeaders
  - weft/CHANGELOG.md:5660-5673 (MaxRetries(0) forwards 0), 6001-6005 (escape hatch), 6007-6017 (Usage cache fields), 6022-6026 (PromptCache), 6477-6492 (openai and google wire fixes), 6741-6745 (SDK retry default)
  - weft/docs/adr/0013-adapter-contract.md
  - weft/AGENTS.md:638-654 (conformance, live tag, WEFT_MODEL_REQUESTS)
  - docs-site/examples/providers/main_test.go:TestProviders, TestInjectedClientIgnoresDeny
  - weft/openai/convert.go:256-279 (mapFinish), 280-291 (toUsage); weft/openai/stream.go:88-90 (usage from the chunk that carries it)
  - 'weft/anthropic/stream.go:90-103 (redacted_thinking is not a text, thinking or tool_use block: skipped); weft/docs/adr/0013-adapter-contract.md:159'
  - weft/anthropic/convert.go:343-366 (mapStopReason, refusal category); weft/anthropic/stream.go:78-87 (input with cache read and creation folded in), 138-154 (stop reason, category, output and thinking tokens), 194-200
  - weft/google/convert.go:438-458 (mapFinish); weft/google/stream.go:60-78 (usage), 173
  - weft/core/model.go:20-26 (Usage subsets), 42-49 (StopReason values), 288-298 (ModelFinish.Raw); weft/core/run.go:668-677 (StepRecord.RawStopReason); weft/core/events.go:124-131 (StepFinish.Raw)
  - weft/docs/adr/0013-adapter-contract.md:165-182 (openai stop reasons and usage), 213-217 (anthropic), 255-260 (google), 303-305 (cache and thought tokens folded in)
  - 'weft/google/model.go:255-262 (an injected Client(c)''s transport is never wrapped: no raw pair)'
  - weft/anthropic/model.go:294-300, weft/openai/model.go:279-285 (CaptureRaw as the innermost per-request middleware)
  - 'weft/docs/adr/0028-the-request-record.md:682-691 (Capture: one pair per HTTP call)'
  - weft/CHANGELOG.md:986-992 (an injected google client is not captured)
  - 'weft/openai/convert.go:56-71 (one tool message per result, content the text, no error flag), 160-200 (userParts: the (empty message) placeholder), 48-55 and 203-241 (assistantMessage: reasoning dropped, nothing sendable skipped)'
  - 'weft/anthropic/convert.go:129-134 (an assistant message with nothing sendable skipped), 136-158 (tool_result blocks: (empty tool output), is_error from IsError), 259-266 (the (empty message) placeholder), 268-285 (assistantBlocks: an unsigned ReasoningPart dropped)'
  - weft/anthropic/doc.go:12-20 (empty content and unsigned reasoning)
  - weft/anthropic/convert.go:278-281 (a signed ReasoningPart is sent as a thinking block whoever signed it); weft/google/convert.go:278-283, 298-305, 316-322 (a signed part goes out as a thoughtSignature on a thought part or the first call)
  - 'scratch proof (weft v0.17.0, httptest capture): anthropic sent a Gemini signature in a thinking block; google sent an Anthropic signature as thoughtSignature, on a thought part and on a functionCall'
  - weft/thread/turn.go:1661-1671 (the trigger's baseline is the final step's reported InputTokens plus the tail estimate, 0 included); weft/thread/compaction.go:1332-1338 (only a never-measured session stands down), 1424-1428 (the default trigger)
  - 'weft/google/convert.go:20-33 (an all-empty user message skipped), 34-39 (a model content with no parts skipped), 40-67 (functionResponse: output, or error when IsError), 259-327 (modelParts: unsigned reasoning dropped; on a step with calls the signatures ride the calls)'
  - weft/docs/adr/0013-adapter-contract.md:205-209 (anthropic's placeholders, model-visible)
  - 'weft/docs/adr/0013-adapter-contract.md:484-496 (provider-executed tools and the Responses API: a stance, not wrapped)'
  - weft/openai/doc.go:31-32 (the Responses API, reasoning items and built-in tools, not wrapped)
  - weft/google/doc.go:30-32 (grounding, search and code-execution tools not wrapped)
  - weft/anthropic/stream.go:99-103 (server_tool_use and other blocks are kind other), 122-126 (server tools' input fragments dropped)
  - weft/google/stream.go:98-136 (only functionCall, thought, text and signature parts are read)
  - 'weft/internal/adapterkit/adapterkit.go:108-114 (MergeBody: arrays replace)'
  - weft/openai/stream.go:95-100 (delta.refusal streams as text); weft/docs/adr/0013-adapter-contract.md:171-174 (content_filter rides Raw)
  - 'weft/google/stream.go:80-84 (candidates only; promptFeedback never read), 172-173 (mapFinish on an empty finish); weft/google/convert.go:441-458 (empty finish, no calls: stop, empty raw)'
---

# Connect a model provider: OpenAI, Anthropic, Gemini

Each provider is one constructor that returns a [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model): [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) for the OpenAI Chat Completions API and every compatible server, [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) for the Anthropic Messages API, and [`google.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) for the Gemini API. Pass the result to `weft.New`; swapping providers is swapping that one line.

In `providers/main.go`, the official OpenAI API and a local compatible server:

```go title="providers/main.go"
official = openai.Model("gpt-4o-mini") // reads $OPENAI_API_KEY and $OPENAI_BASE_URL

local = openai.Model("llama3.2",
	openai.BaseURL("http://localhost:11434/v1"), // any Chat Completions server
	openai.APIKey("unused"),
	openai.MaxTokens(1024),
	openai.Temperature(0.2),
	openai.MaxRetries(0), // the SDK retries nothing; mw.Retry owns retries
)
```

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

Constructing a model performs no I/O. `openai.Model` and `anthropic.Model` build their SDK client then, so they read the key from the environment when the model is built; `google.Model` defers its client, and credential discovery, to the first run.

## The adapters

The three adapters wrap the vendors' official Go SDKs (`openai-go`, `anthropic-sdk-go`, `google.golang.org/genai`): weft never owns an HTTP client, and every request goes through the SDK's client. They are packages of the framework module, so `go get github.com/weftgo/weft@v0.20.2` brings all three, and Go compiles only the ones you import.

Every adapter takes the same kind of functional options, each package's own `Option` type. A model is immutable and safe for concurrent runs.

| Option | `openai` | `anthropic` | `google` | Effect |
|---|---|---|---|---|
| `APIKey(k)` | ✓ | ✓ | ✓ | The key; default from the environment (below) |
| `BaseURL(u)` | ✓ | ✓ | ✓ | A gateway, proxy or compatible server |
| `Client(c)` | ✓ | ✓ | ✓ | Your configured SDK client; overrides `BaseURL`, `APIKey`, `MaxRetries` |
| `MaxTokens(n)` | ✓ | ✓ (default 4096) | ✓ | Per-step output-token cap; zero keeps the provider default |
| `Temperature(t)`, `TopP(p)`, `Stop(s...)` | ✓ | ✓ | ✓ | Sampling; not sent unless given |
| `Seed(s)` | ✓ | — | ✓ | A best-effort determinism hint |
| `IdleTimeout(d)` | ✓ | ✓ | ✓ | Longest gap between stream chunks; default 60s, 0 disables |
| `MaxRetries(n)` | ✓ (SDK default 2) | ✓ (SDK default 2) | ✓ (off unless asked) | The SDK's transport retries on 429, 5xx and connection errors |
| `ExtraBody(m)`, `ExtraHeaders(h)` | ✓ | ✓ | ✓ | [The escape hatch](#escape-hatch) |
| `Dialect(d)` | ✓ | — | — | [How thinking reaches a compatible server](#openai) |
| `Thinking(on)` | — | ✓ | — | Adaptive thinking when the run sets no level |
| `PromptCache()` | — | ✓ | — | [Prompt caching](#prompt-caching) |

The sampling options are construction defaults. A per-run or per-step `weft.Params(weft.RequestParams{…})` overrides them for one call: see [Configure one run](https://weftgo.dev/docs/guides/run-options/).

Credentials and endpoints come from the environment when no option names them:

| Adapter | Key | Endpoint |
|---|---|---|
| `openai` | `OPENAI_API_KEY` | `OPENAI_BASE_URL` |
| `anthropic` | `ANTHROPIC_API_KEY` (the SDK also accepts `ANTHROPIC_AUTH_TOKEN`, a bearer token) | `ANTHROPIC_BASE_URL` |
| `google` | `GOOGLE_API_KEY` (wins when both are set) or `GEMINI_API_KEY`; on the Vertex AI backend (`GOOGLE_GENAI_USE_VERTEXAI=true`), application default credentials | the SDK's own `GOOGLE_GEMINI_BASE_URL` |

## OpenAI

`openai.Model(name, opts...)` speaks the Chat Completions API. With [`openai.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#BaseURL) it reaches any compatible server: a gateway, Ollama, vLLM, a hosted open-weights provider. That is the region above. The model's `Info()` reports provider `openai` whatever the base URL, so a host name never becomes a telemetry dimension.

[`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) takes an `openai-go` client you configured yourself, for Azure endpoints, a custom transport or a test double. The package example [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#example-Model) builds an agent with the default configuration.

Chat Completions has two ways to express reasoning. The official API takes `reasoning_effort`; the z.ai and Moonshot gateways take a `thinking` object the SDK's typed request has no field for. A [`openai.ThinkingDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ThinkingDialect) picks one:

| Dialect | Sends |
|---|---|
| [`DialectAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectAuto) (default) | Detected from the base URL: the object for hosts ending `.z.ai`, `.bigmodel.cn`, `.moonshot.ai`, `.moonshot.cn`; effort for everything else |
| [`DialectEffort`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectEffort) | `reasoning_effort`: `low`, `medium` or `high` |
| [`DialectObject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectObject) | `thinking: {"type": "enabled"}` or `{"type": "disabled"}`, injected into the body |
| [`DialectNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectNone) | Nothing, for strict servers that reject unknown fields |

Pin one with [`openai.Dialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Dialect) when the host does not tell, as in [`ExampleDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#example-Dialect):

```go title="providers/main.go"
// z.ai is a known gateway host: thinking goes out as a thinking object.
detected = openai.Model("glm-4.6", openai.BaseURL("https://api.z.ai/api/paas/v4"))

// An unrecognized host would get reasoning_effort; pin the object form.
pinned = openai.Model("kimi-k2.7",
	openai.BaseURL("https://gw.internal/v1"),
	openai.Dialect(openai.DialectObject))
```

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

A client passed through `Client(c)` hides its endpoint; `DialectAuto` then reads `OPENAI_BASE_URL`, and with none assumes the official API.

What else the adapter does on the wire:

- **Reasoning is output only.** DeepSeek-style `reasoning_content` streams as reasoning; assistant `ReasoningPart`s are dropped on the way back, because Chat Completions has no reasoning input.
- **Empty tool-call arguments become `{}`** when a transcript is sent back, matching its stream side and the other adapters.
- **`parallel_tool_calls` is sent only with a tool catalog**, since several compatible servers reject the hint without one. `weft.Sequential()` sets it to `false`.
- **Missing call ids are synthesised** as `call_<i>`, skipping ids the server already used in the same step.
- **A function name streamed in repeated fragments** is overwritten, not concatenated.

## Anthropic

`anthropic.Model(name, opts...)` speaks the Messages API. [`anthropic.Thinking(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Thinking) sends `thinking: {"type": "adaptive"}` and streams thinking blocks, with their signatures, as reasoning; without it nothing is sent and the model's default applies. `redacted_thinking` blocks are dropped: they never reach the transcript or the next request ([Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/#read-reasoning-parts)). A run's own `weft.Thinking` level overrides it ([Thinking](#thinking)).

```go title="providers/main.go"
m := anthropic.Model("claude-sonnet-5", // reads $ANTHROPIC_API_KEY and $ANTHROPIC_BASE_URL
	anthropic.Thinking(true),  // adaptive thinking unless a run sets a level
	anthropic.PromptCache(),   // cache_control on the stable prefix edges
	anthropic.MaxTokens(8192), // required by the API; 4096 when unset
)
```

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

`max_tokens` is required by the API, so [`anthropic.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxTokens) defaults to 4096. The Messages API has no seed: the adapter has no `Seed` option, and a `RequestParams.Seed` is dropped. [`anthropic.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Client) is the way in for Vertex AI and Bedrock clients. The package example is [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#example-Model).

### Prompt caching

[`anthropic.PromptCache()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#PromptCache) marks three stable prefix edges with `cache_control: {"type": "ephemeral"}`: the system block, the final tool definition, and the last content block of the last message. That spends three of Anthropic's four breakpoints and leaves one free. Without the option, no `cache_control` appears anywhere.

Cache writes bill 1.25× and cache reads 0.1× the base input price, so a transcript whose prefix repeats across steps saves from the second step on. `Usage.CachedInputTokens` and `Usage.CacheWriteTokens` show the effect.

Keeping the prefix stable is your job. A `PrepareStep` that trims messages invalidates the trailing breakpoint. To stop tool calls on a step without removing the tool definitions, and the cached prefix they anchor, use `weft.ToolChoiceNone` instead of dropping the tools. It is a request, not a filter: a call the server emits anyway runs ([Enforce a choice](https://weftgo.dev/docs/guides/run-options/#enforce-a-choice)).

## Google

`google.Model(name, opts...)` speaks the Gemini API through `google.golang.org/genai`. The SDK client is created on the first run, because credential discovery needs a context; a failed attempt is not cached, so the next run tries again.

```go title="providers/main.go"
m := google.Model("gemini-2.5-flash", // $GOOGLE_API_KEY / $GEMINI_API_KEY, then application default
	google.Temperature(0.2),
	google.Seed(7),
	google.MaxRetries(2), // the SDK retries nothing unless asked
)
```

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

Unlike the other two, the Gemini SDK retries nothing unless [`google.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxRetries) asks. [`google.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Client) takes a `genai.Client` you configured, for Vertex AI projects and regions. The package example is [`ExampleModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#example-Model).

What else the adapter does on the wire:

- **Integer limits fail loudly.** `MaxTokens`, `Seed` and `ThinkingConfig.Budget` are int32 on the wire; a larger value fails the call wrapping `weft.ErrUnsupported` instead of wrapping around. Options carry no error, so the check happens when the request is built.
- **Thought signatures round-trip**, including one riding an empty non-thought text part: Gemini validates its return on the next request.
- **Function calls arrive whole**, so there are no argument deltas. Missing call ids are synthesised as `call_<i>`, skipping ids the API populated.
- **`weft.Sequential()` has no Gemini switch**; function calling stays `AUTO`.
- **An injected client records no raw wire pair.** genai has no per-request middleware, so for [`otel.RawBodies`](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only) the adapter wraps the transport of the HTTP client it built for its own SDK client. A `genai.Client` passed through `Client(c)` is yours and is never touched, so its runs record no raw pair; Studio shows `not_recorded` for them. openai and anthropic capture through the SDK's innermost per-request middleware, so they record one pair per HTTP call with or without `Client(c)`, and an SDK transport retry shows as a pair of its own.

## Escape hatch

`ExtraBody(map[string]any)` adds fields to every request's JSON body, and `ExtraHeaders(http.Header)` adds headers verbatim. They are for vendor parameters weft has no option for:

```go title="providers/main.go"
client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test"))
m := openai.Model("gpt-4o-mini",
	openai.Client(&client), // an SDK client you configured: Azure, a proxy, a test server
	openai.ExtraBody(map[string]any{
		"service_tier":   "flex",                                       // a new key is added
		"stream_options": map[string]any{"include_obfuscation": false}, // maps deep-merge
	}),
	openai.ExtraHeaders(http.Header{"X-Request-Source": {"docs"}}),
)
```

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

The body is deep-merged into what weft built: nested maps merge, every other value replaces, and your key wins on a conflict. Both options are construction-time snapshots, so changing the map afterwards never reaches the model. They apply through an injected `Client(c)` too. In the complete example, `stream_options` reaches the server as `{"include_obfuscation":false,"include_usage":true}`: weft's `include_usage` and your key, merged.

### What the run record names

Each request record carries a `wire` object, names only: the endpoint and the escape hatches' keys ([`RequestWire`](https://weftgo.dev/docs/reference/obsdb-records/#requestwire)). A model declares them with the optional method `WireFacts() (serverAddress string, extraBodyKeys, extraHeaderNames []string)`. All three adapters implement it, as they implement `ThinkingWire`.

- **The core walks the `Unwrap` chain** from the agent's model and asks the first model that has the method. Your own model, or a wrapping middleware, may declare it too. A layer without `Unwrap` hides the adapter below it, and the record then has no `wire`. A model with no such method along the chain, such as a `wefttest` model, records none.
- **`server_address`** is the adapter's `BaseURL`, else the SDK's `OPENAI_BASE_URL` or `ANTHROPIC_BASE_URL`, else `api.openai.com` or `api.anthropic.com`. `google` names a `BaseURL` alone. An injected `Client(c)` names none.
- **The core sanitises what the method returns.** It keeps `host[:port]` and drops a URL's scheme, userinfo, path, query and fragment. It names no host when the URL is ambiguous about where the credentials end. Keys are top-level `ExtraBody` keys; headers are names, lowercased, never values. Each list keeps at most 32 names of at most 128 bytes, and `dropped` counts the names left out for length or past the 32; a duplicate or an empty name is dropped without being counted. An address over 128 bytes reads empty.
- **Behind `mw.Fallback` the facts are always the primary's.** `Fallback`'s `Unwrap` is its primary, so a backup's endpoint is never recorded. A fallback attempt's record names the primary's wire; its `attempt` span's `gen_ai.request.model` names the model that served it.

## What the adapters do not wrap

Tools the provider runs itself have no weft mapping: a `weft.Tool` or `weft.RawTool` is executed in your process, and nothing in the process executes these. ADR 0013 records this as a stance, not an oversight. None of the three adapters wraps them:

| Adapter | Not wrapped |
|---|---|
| `anthropic` | Server tools such as `web_search` and `code_execution` |
| `google` | Grounding, search and code-execution tools |
| `openai` | The Responses API, with its reasoning items and built-in tools; the adapter speaks Chat Completions only |

Turning one on through `ExtraBody` does not make its output part of the run. The anthropic stream skips `server_tool_use` blocks and every other block that is not text, thinking or `tool_use`, and drops a server tool's argument fragments, so the transcript gets none of the tool's calls or results. The google stream reads only function calls, thought parts, text and thought signatures from a candidate's parts. A `tools` key in `ExtraBody` also replaces weft's own tool list rather than merging with it, because arrays replace in the merge.

## Idle timeout

`IdleTimeout(d)` is the longest gap between two stream chunks. When it passes, the call fails with an error wrapping [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle), the same error from every adapter. The default is 60 seconds; zero disables it.

```go title="providers/main.go"
m := openai.Model("gpt-4o-mini",
	openai.Client(&client),
	openai.IdleTimeout(200*time.Millisecond), // default 60s; 0 disables it
)
_, err := weft.New(m).Generate(ctx, weft.Prompt("hi"))
if errors.Is(err, weft.ErrStreamIdle) {
	fmt.Fprintln(w, "the stream stalled:", err)
}
```

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

The `ctx` deadline stays the hard limit on the whole call; the idle timer only catches a stalled stream, so a slow response that keeps streaming is never killed.

## Retries

The weft loop never retries a model call. Transport retries on 429, 5xx and connection errors belong to the SDK, set by `MaxRetries(n)`:

- **openai and anthropic** inherit the SDK default of 2 retries when the option is absent. `MaxRetries(0)` switches them off; a negative n is 0.
- **google** retries nothing unless `MaxRetries(n)` is given.

The wait for response headers is the idle timer's first gap, and it contains the SDK's retries and their sleeps. A rate-limited call whose `retry-after` the SDK sleeps on can therefore fail as `ErrStreamIdle`, with the 429 discarded. Pair `MaxRetries(0)` with `mw.Retry`, which then owns every retry and reads the provider's `retry-after` itself: see [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/).

## Thinking

[`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) asks for a reasoning depth on a provider-neutral scale; each adapter writes it in its own field. Each adapter declares the field with the optional method `ThinkingWire(weft.ThinkingConfig) string`, which Studio shows as the request's thinking wire. The complete example prints it for every adapter:

| `weft.ThinkingConfig` | `openai` (effort) | `openai` (object) | `anthropic` | `google` |
|---|---|---|---|---|
| zero value (`ThinkUnset`) | `none` | `none` | `none` | `none` |
| `Level: ThinkOff` | `none` (no off switch) | `thinking` (`disabled`) | `thinking.disabled` | `thinking_budget` (zeroed) |
| `Level: ThinkLow`, `ThinkMedium`, `ThinkHigh` | `reasoning_effort` | `thinking` (`enabled`) | `thinking.adaptive` | `thinking_level` |
| `Budget: 2048` | `none` (dropped) | `none` | `thinking.budget_tokens` | `thinking_budget` |

The table shows `ThinkingWire`'s label, not always what is sent. A run that sets no level keeps the adapter's construction default: with `anthropic.Thinking(true)` an unset level still sends `thinking.adaptive`, which the label reports as `none`. Setting levels per agent and per run is on [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/).

## Capabilities

What each adapter carries, as its conformance run declares it, with the details from the adapter code (`openai/stream.go`, `openai/convert.go`, `anthropic/convert.go`, `google/convert.go`):

| | `openai` | `anthropic` | `google` |
|---|---|---|---|
| Tools and streaming | ✓ | ✓ | ✓ |
| Tool-argument deltas | ✓ | ✓ | — (calls arrive whole) |
| Sequential tools hint | ✓ | ✓ | — |
| Tool choice | ✓ | ✓ | ✓ |
| Reasoning in and out | out only, via `reasoning_content` | ✓ | ✓ |
| File input | images | images (PNG, JPEG, GIF, WebP) and PDF | inline data or a file URI, any media type |
| Usage reported | ✓ | ✓ | ✓ |
| `retry-after` readable by `mw.Retry` | ✓ | ✓ | — (backs off instead) |
| Raw wire pairs under `otel.RawBodies` | ✓ one per HTTP call | ✓ one per HTTP call | ✓ only for a client the adapter built, not `Client(c)` |

Structured output is not a row: `weft.Output` registers an ordinary tool, `submit_output`, so every adapter that carries tools carries it ([Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/)).

A file an adapter cannot carry fails the call wrapping `weft.ErrUnsupported`: see [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/).

## How the transcript is sent

Each adapter rewrites weft's messages into its provider's shape, and some content changes on the way. The placeholders are text the model reads:

| In the transcript | `openai` | `anthropic` | `google` |
|---|---|---|---|
| A tool result | a `tool` message per result, the text as `content` | a `tool_result` block per result, all on one user message | a `functionResponse` per result with `{"output": <text>}` |
| A tool error result (`IsError`) | the same `tool` message: Chat Completions has no error flag, so only the text says it failed | the `tool_result` block with `is_error` set | `{"error": <text>}` in place of `{"output": …}`: Gemini has no flag either |
| An empty tool result | passed unchanged | `(empty tool output)` | `{"output": ""}` |
| A user message whose every part is empty text | `(empty message)` | `(empty message)` | dropped |
| An assistant message with nothing sendable | skipped | skipped | skipped |

A tool error's text is the loop's, such as `INVALID_INPUT: …` or a `ToolError`'s code and message, so an OpenAI model reads the failure from the text alone.

What each adapter sends back for a signed or unsigned `ReasoningPart` is on [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/#read-reasoning-parts), with how to [switch providers](https://weftgo.dev/docs/guides/thinking/#switch-providers) without sending one provider's signatures to another.

## Stop reasons

Each adapter maps the provider's finish reason onto one of three [`weft.StopReason`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StopReason) values: `stop` (`StopEndTurn`), `tool_calls` (`StopToolCalls`) or `max_tokens` (`StopMaxTokens`). When the mapping is approximate, the provider's own word is kept beside it: on `StepRecord.RawStopReason` (in `res.Steps`) and on the `StepFinish` event's `Raw`. An exact mapping leaves it empty.

| Adapter | Provider value | `StopReason` | `RawStopReason` |
|---|---|---|---|
| `openai` | `stop` | `stop` | empty |
| | `tool_calls` | `tool_calls` | empty |
| | `length` | `max_tokens` | empty |
| | none sent (some compatible servers) | `tool_calls` if the step has calls, else `stop` | empty |
| | `content_filter`, anything else | `stop` | the value, e.g. `content_filter` |
| `anthropic` | `end_turn` | `stop` | empty |
| | `tool_use` | `tool_calls` | empty |
| | `max_tokens` | `max_tokens` | empty |
| | `refusal` | `stop` | `refusal`, or `refusal:<category>` when the API names `stop_details.category` |
| | `stop_sequence`, `pause_turn`, anything newer | `stop` | the value |
| `google` | `STOP` | `tool_calls` if the step has calls (Gemini reports `STOP` either way), else `stop` | empty |
| | `MAX_TOKENS` | `max_tokens` | empty |
| | none sent | `tool_calls` if the step has calls, else `stop` | empty |
| | `SAFETY`, `RECITATION`, anything else | `stop` | the value, e.g. `SAFETY` |

A safety-blocked Gemini reply, an OpenAI `content_filter` and an Anthropic refusal all read `stop`, like a normal answer. To tell them apart, check the last step's `RawStopReason` (or `StepFinish.Raw` on a stream); `res.StopReason` carries the mapped value only.

An OpenAI safety refusal streams its message in `delta.refusal`, and the adapter passes it on as ordinary text: the refusal is the answer in `res.Text()`, and the step's `RawStopReason` is `content_filter`.

A prompt Gemini blocks before writing any candidate is not caught by `RawStopReason`. The adapter never reads the response's `promptFeedback`, so such a stream ends the run successfully with `stop`, an empty `RawStopReason` and empty text.

## Token usage

Every adapter fills [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) from the provider's own usage fields. `InputTokens` and `OutputTokens` are the billed totals; `CachedInputTokens` and `CacheWriteTokens` are parts of `InputTokens`, and `ReasoningTokens` is part of `OutputTokens`, never added on top.

| `weft.Usage` field | `openai` (the final chunk's `usage`) | `anthropic` (`message_start` and `message_delta`) | `google` (`usageMetadata`) |
|---|---|---|---|
| `InputTokens` | `prompt_tokens` | `input_tokens` + `cache_read_input_tokens` + `cache_creation_input_tokens` | `promptTokenCount` + `toolUsePromptTokenCount` |
| `OutputTokens` | `completion_tokens` | `output_tokens` | `candidatesTokenCount` + `thoughtsTokenCount` |
| `CachedInputTokens` | `prompt_tokens_details.cached_tokens` | `cache_read_input_tokens` | `cachedContentTokenCount` |
| `CacheWriteTokens` | not reported (0) | `cache_creation_input_tokens` | not reported (0) |
| `ReasoningTokens` | `completion_tokens_details.reasoning_tokens` | `output_tokens_details.thinking_tokens` | `thoughtsTokenCount` |

The openai adapter asks for usage with `stream_options.include_usage`. A compatible server that never sends it reports zero usage rather than an estimate. Gemini's thought tokens count as output because they are billed as output, so a `UsageLimit` on `OutputTokens` includes them.

## Test without the network

Set `WEFT_MODEL_REQUESTS=deny` and every adapter that built its own client fails its first call with [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied), before any I/O. [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) reads the variable on every call, so a test can toggle it with `t.Setenv`.

A client injected through `Client(c)` stays reachable under deny: it is a test double by construction, and where it sends requests is your responsibility. The complete example relies on that to point the escape-hatch and idle-timeout demos at a local `httptest` server.

The adapters' own parsing is proven by the shared conformance suite, `wefttest/conformance`, offline against recorded fixtures and live behind `-tags live`: see [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/).

## Complete example

`providers/main.go` builds every model above, shows each refusing under the kill switch, prints the thinking wire table, and runs the escape hatch and the idle timeout against local servers:

```go title="providers/main.go"
// Command providers builds the three first-party adapters (weft/openai,
// weft/anthropic, weft/google) and shows what each would send, without
// reaching a provider: WEFT_MODEL_REQUESTS=deny stops every adapter that
// built its own client, and the two wire demos talk to a local
// httptest server through an injected SDK client.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"time"

	openaisdk "github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/weftgo/weft"
	"github.com/weftgo/weft/anthropic"
	"github.com/weftgo/weft/google"
	"github.com/weftgo/weft/openai"
)

func main() {
	// This demo never reaches a provider: the kill switch makes every
	// adapter that built its own client refuse before any I/O.
	os.Setenv("WEFT_MODEL_REQUESTS", "deny")
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

// openaiModels returns the official API and an OpenAI-compatible
// local server.
func openaiModels() (official, local weft.Model) {
	official = openai.Model("gpt-4o-mini") // reads $OPENAI_API_KEY and $OPENAI_BASE_URL

	local = openai.Model("llama3.2",
		openai.BaseURL("http://localhost:11434/v1"), // any Chat Completions server
		openai.APIKey("unused"),
		openai.MaxTokens(1024),
		openai.Temperature(0.2),
		openai.MaxRetries(0), // the SDK retries nothing; mw.Retry owns retries
	)
	return official, local
}

// gatewayModels returns two gateway models: one whose thinking wire
// form is detected from its host, one pinned with Dialect.
func gatewayModels() (detected, pinned weft.Model) {
	// z.ai is a known gateway host: thinking goes out as a thinking object.
	detected = openai.Model("glm-4.6", openai.BaseURL("https://api.z.ai/api/paas/v4"))

	// An unrecognized host would get reasoning_effort; pin the object form.
	pinned = openai.Model("kimi-k2.7",
		openai.BaseURL("https://gw.internal/v1"),
		openai.Dialect(openai.DialectObject))
	return detected, pinned
}

func anthropicModel() weft.Model {
	m := anthropic.Model("claude-sonnet-5", // reads $ANTHROPIC_API_KEY and $ANTHROPIC_BASE_URL
		anthropic.Thinking(true),  // adaptive thinking unless a run sets a level
		anthropic.PromptCache(),   // cache_control on the stable prefix edges
		anthropic.MaxTokens(8192), // required by the API; 4096 when unset
	)
	return m
}

func googleModel() weft.Model {
	m := google.Model("gemini-2.5-flash", // $GOOGLE_API_KEY / $GEMINI_API_KEY, then application default
		google.Temperature(0.2),
		google.Seed(7),
		google.MaxRetries(2), // the SDK retries nothing unless asked
	)
	return m
}

// extrasModel is an openai model whose requests carry fields and
// headers weft has no option for.
func extrasModel(baseURL string) weft.Model {
	client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test"))
	m := openai.Model("gpt-4o-mini",
		openai.Client(&client), // an SDK client you configured: Azure, a proxy, a test server
		openai.ExtraBody(map[string]any{
			"service_tier":   "flex",                                       // a new key is added
			"stream_options": map[string]any{"include_obfuscation": false}, // maps deep-merge
		}),
		openai.ExtraHeaders(http.Header{"X-Request-Source": {"docs"}}),
	)
	return m
}

// stallModel talks to a server that sends one chunk and then goes quiet.
func stallModel(ctx context.Context, w io.Writer, baseURL string) error {
	client := openaisdk.NewClient(option.WithBaseURL(baseURL), option.WithAPIKey("test"))
	m := openai.Model("gpt-4o-mini",
		openai.Client(&client),
		openai.IdleTimeout(200*time.Millisecond), // default 60s; 0 disables it
	)
	_, err := weft.New(m).Generate(ctx, weft.Prompt("hi"))
	if errors.Is(err, weft.ErrStreamIdle) {
		fmt.Fprintln(w, "the stream stalled:", err)
	}
	return err
}

// thinkingWire is the optional method an adapter declares to name the
// provider field a thinking configuration is written to.
type thinkingWire interface {
	ThinkingWire(weft.ThinkingConfig) string
}

func run(ctx context.Context, w io.Writer) error {
	official, local := openaiModels()
	detected, pinned := gatewayModels()
	claude, gemini := anthropicModel(), googleModel()

	// Constructing a model performs no I/O (openai and anthropic read the key
	// then; google on its first run).
	// Under WEFT_MODEL_REQUESTS=deny the first run fails before any request.
	for _, m := range []weft.Model{official, local, claude, gemini} {
		info := weft.InfoOf(m)
		_, err := weft.New(m).Generate(ctx, weft.Prompt("hi"))
		fmt.Fprintf(w, "%s/%s: denied=%v\n", info.Provider, info.Name, errors.Is(err, weft.ErrModelRequestsDenied))
	}

	// What each adapter writes for each thinking configuration.
	configs := []struct {
		name string
		cfg  weft.ThinkingConfig
	}{
		{"unset", weft.ThinkingConfig{}},
		{"off", weft.ThinkingConfig{Level: weft.ThinkOff}},
		{"high", weft.ThinkingConfig{Level: weft.ThinkHigh}},
		{"budget 2048", weft.ThinkingConfig{Budget: 2048}},
	}
	fmt.Fprintf(w, "\n%-12s %-17s %-12s %-23s %s\n", "thinking", "openai", "z.ai", "anthropic", "google")
	for _, c := range configs {
		fmt.Fprintf(w, "%-12s %-17s %-12s %-23s %s\n", c.name,
			official.(thinkingWire).ThinkingWire(c.cfg),
			detected.(thinkingWire).ThinkingWire(c.cfg),
			claude.(thinkingWire).ThinkingWire(c.cfg),
			gemini.(thinkingWire).ThinkingWire(c.cfg))
	}
	fmt.Fprintf(w, "pinned DialectObject, high: %s\n", pinned.(thinkingWire).ThinkingWire(weft.ThinkingConfig{Level: weft.ThinkHigh}))

	// The escape hatch, against a local server that records the request.
	srv := newFakeOpenAI()
	defer srv.Close()
	extras := weft.New(extrasModel(srv.URL))
	res, err := extras.Generate(ctx, weft.Prompt("hi"))
	if err != nil {
		return err
	}
	body, header := srv.last()
	var payload map[string]any
	if err := json.Unmarshal(body, &payload); err != nil {
		return err
	}
	so, _ := json.Marshal(payload["stream_options"])
	fmt.Fprintf(w, "\nanswer: %s\n", res.Text())
	fmt.Fprintf(w, "service_tier: %v\n", payload["service_tier"])
	fmt.Fprintf(w, "stream_options: %s\n", so)
	fmt.Fprintf(w, "X-Request-Source: %s\n", header.Get("X-Request-Source"))

	// The idle timeout, against a server that stalls after one chunk.
	stall := newStallServer()
	defer stall.Close()
	if err := stallModel(ctx, w, stall.URL); !errors.Is(err, weft.ErrStreamIdle) {
		return fmt.Errorf("want ErrStreamIdle, got %v", err)
	}
	return nil
}

// textOnly is a recorded Chat Completions stream: one text answer.
const textOnly = `data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello from the model."},"finish_reason":null}]}

data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"c1","object":"chat.completion.chunk","created":1700000000,"model":"m","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":5,"total_tokens":14}}

data: [DONE]

`

type fakeOpenAI struct {
	*httptest.Server
	mu     sync.Mutex
	body   []byte
	header http.Header
}

func newFakeOpenAI() *fakeOpenAI {
	f := &fakeOpenAI{}
	f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, _ := io.ReadAll(r.Body)
		f.mu.Lock()
		f.body, f.header = b, r.Header.Clone()
		f.mu.Unlock()
		w.Header().Set("Content-Type", "text/event-stream")
		_, _ = io.WriteString(w, textOnly)
	}))
	return f
}

func (f *fakeOpenAI) last() ([]byte, http.Header) {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.body, f.header
}

// newStallServer sends the first chunk of an answer, then nothing until
// the client goes away.
func newStallServer() *httptest.Server {
	first, _, _ := strings.Cut(textOnly, "\n\n")
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		_, _ = io.WriteString(w, first+"\n\n")
		w.(http.Flusher).Flush()
		<-r.Context().Done()
	}))
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/providers) · from `docs-site/examples`:

```sh
go run ./providers
go test ./providers
```

```text
openai/gpt-4o-mini: denied=true
openai/llama3.2: denied=true
anthropic/claude-sonnet-5: denied=true
google/gemini-2.5-flash: denied=true

thinking     openai            z.ai         anthropic               google
unset        none              none         none                    none
off          none              thinking     thinking.disabled       thinking_budget
high         reasoning_effort  thinking     thinking.adaptive       thinking_level
budget 2048  none              none         thinking.budget_tokens  thinking_budget
pinned DialectObject, high: thinking

answer: Hello from the model.
service_tier: flex
stream_options: {"include_obfuscation":false,"include_usage":true}
X-Request-Source: docs
the stream stalled: weft: run failed at step 0: model stream: weft: model stream idle timeout after 200ms
```

## Best practices & gotchas

- **Set `MaxRetries(0)` when you use `mw.Retry`.** Otherwise the SDK sleeps on `retry-after` inside the idle timer and the call can fail as `ErrStreamIdle` with the 429 lost. (Source: `weft/openai/model.go:101-124`, CHANGELOG 0.3.4 `weft/CHANGELOG.md:5660`)
- **Pin `openai.Dialect` behind an unrecognized gateway.** Detection knows four host suffixes; anything else gets `reasoning_effort`. (Source: `weft/openai/thinking.go:44-75`)
- **Do not expect `ThinkOff` to stop OpenAI reasoning.** Chat Completions has no off switch, so nothing is sent under the effort dialect. (Source: `weft/openai/thinking.go:77-92`)
- **Keep the prefix stable under `PromptCache`.** Trimming messages invalidates the trailing breakpoint; `weft.ToolChoiceNone` keeps the tool definitions in the request. (Source: `weft/anthropic/model.go:124-144`)
- **`ExtraBody` keys win over weft's.** The bytes you add are yours: weft's default-bytes tests do not cover them. (Source: `weft/openai/model.go:126-147`, `weft/openai/extrabody_test.go:TestExtraBodyAndHeaders`)
- **Do not set `Authorization` or `Content-Type` with `ExtraHeaders`.** The SDK sets them and the option does not check. (Source: `weft/openai/model.go:149-161`)
- **An injected client ignores `WEFT_MODEL_REQUESTS=deny`.** Only clients the adapter built from credentials are guarded. (Source: `weft/core/env.go:5-20`, ADR 0013)
- **Check `RawStopReason`, not only `StopReason`.** Gemini `SAFETY` and `RECITATION`, OpenAI `content_filter` and Anthropic `refusal` all map to `stop`. An OpenAI refusal's message is also the run's text. A prompt Gemini blocks outright is the exception: it reads `stop` with an empty `RawStopReason` and no text, so treat an empty answer from Gemini as a possible block. (Source: `weft/google/convert.go:438-458`, `weft/google/stream.go:80-84, 172-173`, `weft/openai/convert.go:256-279`, `weft/openai/stream.go:95-100`, `weft/anthropic/convert.go:343-366`)
- **Do not turn on a provider-run tool with `ExtraBody`.** The anthropic adapter drops the blocks of `web_search`, `code_execution` and other server tools, so their calls and results never reach the transcript; the google adapter keeps only function calls, text and thought parts. A `tools` array in `ExtraBody` also replaces weft's tool list. Write a `weft.Tool` that calls the service instead. (Source: `weft/docs/adr/0013-adapter-contract.md:484-496`, `weft/anthropic/stream.go:99-103, 122-126`, `weft/google/stream.go:98-136`, `weft/internal/adapterkit/adapterkit.go:108-114`)
- **Put the failure in an OpenAI tool error's text.** Chat Completions carries no error flag, so a `ToolError`'s `Code` and `Message` are all the model sees. (Source: `weft/openai/convert.go:56-71`, ADR 0013)
- **Strip reasoning before another provider reads the transcript.** Anthropic and Gemini parts are signed, and each adapter sends a signed part as it is: anthropic as a `thinking` block with Gemini's signature, google as a `thoughtSignature` carrying Anthropic's. Neither signature is that provider's, so a `weft.UseModel` switch or a cross-provider `mw.Fallback` with reasoning on is expected to fail at the other provider. Only unsigned parts are dropped, and openai sends no reasoning back at all. Filter the parts out first ([Switch providers](https://weftgo.dev/docs/guides/thinking/#switch-providers)). (Source: `weft/anthropic/convert.go:278-281`, `weft/google/convert.go:278-322`, `weft/openai/convert.go:203-208`; scratch httptest capture)
- **Check that a compatible server reports usage.** Without `include_usage` support the openai adapter reports zero input tokens, and a `weft/thread` session's automatic compaction, which reads the reported input, then in practice never fires, and nothing is logged ([compaction](https://weftgo.dev/docs/sessions/compaction/#best-practices--gotchas)). (Source: `weft/thread/turn.go:1661-1671`, `weft/thread/compaction.go:1332-1338, 1424-1428`)
- **An injected `google.Client(c)` records no raw bodies.** Under `otel.RawBodies` only a client the google adapter built itself is captured; openai and anthropic capture either way. (Source: `weft/google/model.go:255-262`, `CHANGELOG.md:986-992`)

## See also

- [What is a Model? The provider contract](https://weftgo.dev/docs/concepts/models/)
- [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)
- [Control reasoning (thinking)](https://weftgo.dev/docs/guides/thinking/)
- [Send images and files to a model](https://weftgo.dev/docs/guides/multimodal/)
- [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/)

Symbols used: [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Params`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Params) · [`weft.RequestParams`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RequestParams) · [`weft.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Thinking) · [`weft.ThinkingConfig`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ThinkingConfig) · [`weft.ToolChoiceNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolChoiceNone) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`weft.ModelRequestsAllowed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequestsAllowed) · [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) · [`openai.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Option) · [`openai.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#APIKey) · [`openai.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#BaseURL) · [`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) · [`openai.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxTokens) · [`openai.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Temperature) · [`openai.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#TopP) · [`openai.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Stop) · [`openai.Seed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Seed) · [`openai.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#IdleTimeout) · [`openai.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxRetries) · [`openai.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ExtraBody) · [`openai.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ExtraHeaders) · [`openai.Dialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Dialect) · [`openai.ThinkingDialect`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#ThinkingDialect) · [`openai.DialectAuto`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectAuto) · [`openai.DialectEffort`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectEffort) · [`openai.DialectObject`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectObject) · [`openai.DialectNone`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#DialectNone) · [`anthropic.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Model) · [`anthropic.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Option) · [`anthropic.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#APIKey) · [`anthropic.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#BaseURL) · [`anthropic.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Client) · [`anthropic.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxTokens) · [`anthropic.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Temperature) · [`anthropic.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#TopP) · [`anthropic.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Stop) · [`anthropic.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#IdleTimeout) · [`anthropic.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxRetries) · [`anthropic.Thinking`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#Thinking) · [`anthropic.PromptCache`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#PromptCache) · [`anthropic.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#ExtraBody) · [`anthropic.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#ExtraHeaders) · [`google.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Model) · [`google.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Option) · [`google.APIKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#APIKey) · [`google.BaseURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#BaseURL) · [`google.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Client) · [`google.MaxTokens`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxTokens) · [`google.Temperature`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Temperature) · [`google.TopP`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#TopP) · [`google.Stop`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Stop) · [`google.Seed`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#Seed) · [`google.IdleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#IdleTimeout) · [`google.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#MaxRetries) · [`google.ExtraBody`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#ExtraBody) · [`google.ExtraHeaders`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/google#ExtraHeaders) · [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`weft.UseModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UseModel) · [`weft.ReasoningPart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReasoningPart) · [`conformance.Run`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest/conformance#Run)
