Skip to content

Connect a model provider: OpenAI, Anthropic, Gemini

View as Markdown

Each provider is one constructor that returns a weft.Model: openai.Model for the OpenAI Chat Completions API and every compatible server, anthropic.Model for the Anthropic Messages API, and 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:

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

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 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.

OptionopenaianthropicgoogleEffect
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
Dialect(d)✓——How thinking reaches a compatible server
Thinking(on)—✓—Adaptive thinking when the run sets no level
PromptCache()—✓—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.

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

AdapterKeyEndpoint
openaiOPENAI_API_KEYOPENAI_BASE_URL
anthropicANTHROPIC_API_KEY (the SDK also accepts ANTHROPIC_AUTH_TOKEN, a bearer token)ANTHROPIC_BASE_URL
googleGOOGLE_API_KEY (wins when both are set) or GEMINI_API_KEY; on the Vertex AI backend (GOOGLE_GENAI_USE_VERTEXAI=true), application default credentialsthe SDK’s own GOOGLE_GEMINI_BASE_URL

openai.Model(name, opts...) speaks the Chat Completions API. With 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 takes an openai-go client you configured yourself, for Azure endpoints, a custom transport or a test double. The package example ExampleModel 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 picks one:

DialectSends
DialectAuto (default)Detected from the base URL: the object for hosts ending .z.ai, .bigmodel.cn, .moonshot.ai, .moonshot.cn; effort for everything else
DialectEffortreasoning_effort: low, medium or high
DialectObjectthinking: {"type": "enabled"} or {"type": "disabled"}, injected into the body
DialectNoneNothing, for strict servers that reject unknown fields

Pin one with openai.Dialect when the host does not tell, as in ExampleDialect:

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

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 ReasoningParts 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.Model(name, opts...) speaks the Messages API. anthropic.Thinking(true) 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)). A run’s own weft.Thinking level overrides it (Thinking).

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

max_tokens is required by the API, so 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 is the way in for Vertex AI and Bedrock clients. The package example is ExampleModel.

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

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.

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

Unlike the other two, the Gemini SDK retries nothing unless google.MaxRetries asks. google.Client takes a genai.Client you configured, for Vertex AI projects and regions. The package example is ExampleModel.

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 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.

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:

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

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.

Each request record carries a wire object, names only: the endpoint and the escape hatches’ keys (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.

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:

AdapterNot wrapped
anthropicServer tools such as web_search and code_execution
googleGrounding, search and code-execution tools
openaiThe 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.

IdleTimeout(d) is the longest gap between two stream chunks. When it passes, the call fails with an error wrapping weft.ErrStreamIdle, the same error from every adapter. The default is 60 seconds; zero disables it.

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

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.

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.

weft.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.ThinkingConfigopenai (effort)openai (object)anthropicgoogle
zero value (ThinkUnset)nonenonenonenone
Level: ThinkOffnone (no off switch)thinking (disabled)thinking.disabledthinking_budget (zeroed)
Level: ThinkLow, ThinkMedium, ThinkHighreasoning_effortthinking (enabled)thinking.adaptivethinking_level
Budget: 2048none (dropped)nonethinking.budget_tokensthinking_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).

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

openaianthropicgoogle
Tools and streaming✓✓✓
Tool-argument deltas✓✓— (calls arrive whole)
Sequential tools hint✓✓—
Tool choice✓✓✓
Reasoning in and outout only, via reasoning_content✓✓
File inputimagesimages (PNG, JPEG, GIF, WebP) and PDFinline 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).

A file an adapter cannot carry fails the call wrapping weft.ErrUnsupported: see Send images and files to a model.

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 transcriptopenaianthropicgoogle
A tool resulta tool message per result, the text as contenta tool_result block per result, all on one user messagea 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 failedthe tool_result block with is_error set{"error": <text>} in place of {"output": …}: Gemini has no flag either
An empty tool resultpassed unchanged(empty tool output){"output": ""}
A user message whose every part is empty text(empty message)(empty message)dropped
An assistant message with nothing sendableskippedskippedskipped

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), with how to switch providers without sending one provider’s signatures to another.

Each adapter maps the provider’s finish reason onto one of three weft.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.

AdapterProvider valueStopReasonRawStopReason
openaistopstopempty
tool_callstool_callsempty
lengthmax_tokensempty
none sent (some compatible servers)tool_calls if the step has calls, else stopempty
content_filter, anything elsestopthe value, e.g. content_filter
anthropicend_turnstopempty
tool_usetool_callsempty
max_tokensmax_tokensempty
refusalstoprefusal, or refusal:<category> when the API names stop_details.category
stop_sequence, pause_turn, anything newerstopthe value
googleSTOPtool_calls if the step has calls (Gemini reports STOP either way), else stopempty
MAX_TOKENSmax_tokensempty
none senttool_calls if the step has calls, else stopempty
SAFETY, RECITATION, anything elsestopthe 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.

Every adapter fills weft.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 fieldopenai (the final chunk’s usage)anthropic (message_start and message_delta)google (usageMetadata)
InputTokensprompt_tokensinput_tokens + cache_read_input_tokens + cache_creation_input_tokenspromptTokenCount + toolUsePromptTokenCount
OutputTokenscompletion_tokensoutput_tokenscandidatesTokenCount + thoughtsTokenCount
CachedInputTokensprompt_tokens_details.cached_tokenscache_read_input_tokenscachedContentTokenCount
CacheWriteTokensnot reported (0)cache_creation_input_tokensnot reported (0)
ReasoningTokenscompletion_tokens_details.reasoning_tokensoutput_tokens_details.thinking_tokensthoughtsTokenCount

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.

Set WEFT_MODEL_REQUESTS=deny and every adapter that built its own client fails its first call with weft.ErrModelRequestsDenied, before any I/O. weft.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.

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:

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()
}))
}

View providers/main.go on GitHub

View on GitHub · from docs-site/examples:

Terminal window
go run ./providers
go test ./providers
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
  • 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). (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). (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)

Symbols used: weft.Model · weft.New · weft.InfoOf · weft.Params · weft.RequestParams · weft.Thinking · weft.ThinkingConfig · weft.ToolChoiceNone · weft.Usage · weft.ErrStreamIdle · weft.ErrUnsupported · weft.ErrModelRequestsDenied · weft.ModelRequestsAllowed · openai.Model · openai.Option · openai.APIKey · openai.BaseURL · openai.Client · openai.MaxTokens · openai.Temperature · openai.TopP · openai.Stop · openai.Seed · openai.IdleTimeout · openai.MaxRetries · openai.ExtraBody · openai.ExtraHeaders · openai.Dialect · openai.ThinkingDialect · openai.DialectAuto · openai.DialectEffort · openai.DialectObject · openai.DialectNone · anthropic.Model · anthropic.Option · anthropic.APIKey · anthropic.BaseURL · anthropic.Client · anthropic.MaxTokens · anthropic.Temperature · anthropic.TopP · anthropic.Stop · anthropic.IdleTimeout · anthropic.MaxRetries · anthropic.Thinking · anthropic.PromptCache · anthropic.ExtraBody · anthropic.ExtraHeaders · google.Model · google.Option · google.APIKey · google.BaseURL · google.Client · google.MaxTokens · google.Temperature · google.TopP · google.Stop · google.Seed · google.IdleTimeout · google.MaxRetries · google.ExtraBody · google.ExtraHeaders · mw.Retry · mw.Fallback · weft.UseModel · weft.ReasoningPart · conformance.Run