Control reasoning (thinking)
weft.Thinking(weft.ThinkingConfig{…}) sets how hard the model reasons, on a provider-neutral scale. Passed to weft.New it is every run’s default; passed to Generate or Stream it overrides that default for one run. Each adapter writes the level in its provider’s own form.
An agent that does not reason unless asked, in thinking/main.go:
agt := weft.New(model, weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkOff}), // every run's default)How it works
Section titled “How it works”The loop puts the run’s configuration on every model request as ModelRequest.Thinking. The adapter maps it to the provider: reasoning_effort for OpenAI, a thinking object for Anthropic and the OpenAI-compatible gateways that take one, a thinking budget or level for Gemini. What a provider cannot express, the adapter drops and documents. Two examples: the Google adapter also asks Gemini to return thought summaries (IncludeThoughts) when a level or budget is set (not for ThinkOff), and the OpenAI adapter’s reasoning_effort form has no off switch and no budget, so it drops ThinkOff and Budget. The full per-adapter mapping is on Connect a model provider.
Reasoning the provider returns comes back as weft.ReasoningDelta events while the step streams and as weft.ReasoningPart blocks in the transcript. weft keeps them and does not act on them.
Choose a level
Section titled “Choose a level”weft.ThinkingConfig has two fields: Level, a weft.ThinkingLevel, and Budget, a token count for providers whose depth control is a cap.
| Level | Meaning |
|---|---|
weft.ThinkUnset | The zero value. Nothing is sent; the provider default applies. |
weft.ThinkOff | Suppress reasoning where the provider allows it. |
weft.ThinkLow | Low effort. |
weft.ThinkMedium | Medium effort. |
weft.ThinkHigh | High effort. |
Level and Budget combine:
- A level without a budget leaves the depth to the provider: Anthropic’s adaptive thinking, Gemini’s own level mapping.
- A budget without a level pins the depth to that many tokens: Anthropic’s
budget_tokens, Gemini’s thinking budget. ThinkOffwith a budget: off wins.
weft.Thinking returns a weft.ThinkingOption, an interface that is both an Option and a RunOption, which is why one call works in both places.
Set the agent default
Section titled “Set the agent default”The option on weft.New sets every run’s default, as in the snippet above. agt.Thinking() returns it; the zero value means the provider default.
An adapter declares how it sends a configuration with the optional method ThinkingWire(weft.ThinkingConfig) string: the provider field it writes, or none. The loop finds it along the model’s Unwrap chain, so it survives middleware such as mw.Retry, and records it on each request record as thinking.wire; Studio shows it on the step. The method never calls the provider. The first-party adapters implement it; a custom adapter may. weft exports no interface for it: it is a convention, like Info.
Override it for one run
Section titled “Override it for one run”Pass weft.Thinking beside the prompt to change one run without rebuilding the agent: fast by default, think on demand:
deep := weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkHigh, Budget: 2048})if _, err := agt.Generate(ctx, deep, weft.Prompt("Plan the migration.")); err != nil { return err}if _, err := agt.Generate(ctx, weft.Prompt("What time is it in UTC?")); err != nil { return err}run 1 asked for: level=high budget=2048run 2 asked for: level=off budget=0The run option replaces the agent’s configuration whole for that run; the second run, with no option, falls back to the agent’s ThinkOff. A weft.PrepareStep function can also change Thinking per step, and the request record lists thinking among the fields it rewrote. The package example is ExampleThinking; per-run options in general are on Change an agent’s configuration for one run.
Read reasoning parts
Section titled “Read reasoning parts”While a step streams, reasoning arrives as ReasoningDelta events in the order the model produced it relative to TextDelta. After the run, the assistant message holds one ReasoningPart per provider block, before the TextPart of the same message:
run := agt.Stream(ctx, weft.Prompt("Hi."))for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ReasoningDelta: fmt.Fprintln(w, "reasoning:", ev.Text) case weft.TextDelta: fmt.Fprintln(w, "text:", ev.Text) }}res, err := run.Wait()if err != nil { return err}for _, p := range res.Messages[1].Content { // the assistant message switch p := p.(type) { case weft.ReasoningPart: fmt.Fprintf(w, "part: reasoning %q, signed: %t\n", p.Text, p.Signature != "") case weft.TextPart: fmt.Fprintf(w, "part: text %q\n", p.Text) }}reasoning: The user greets; reply in kind.text: Hello!part: reasoning "The user greets; reply in kind.", signed: falsepart: text "Hello!"A ReasoningPart has two fields. Text is the reasoning. Signature is the provider’s opaque token for the block: Anthropic rejects thinking sent back without it, and Gemini validates its own on the next request. Signatures are not streamed; they are only on the part. The anthropic and google adapters send them back unchanged, so a transcript you feed back with weft.Messages keeps them; the openai adapter sends no reasoning back. The complete example scripts a signed block and checks the signature reaches the next request.
What each adapter does with a ReasoningPart it is given:
| Part | openai | anthropic | google |
|---|---|---|---|
| Signed | dropped: Chat Completions takes no reasoning input | sent as a thinking block with its signature, whichever provider signed it | sent as a thought part with its signature, whichever provider signed it; on a step with tool calls, only the signatures go back, on the function-call parts |
| Unsigned | dropped | dropped, with no error | dropped, with no error |
One kind of Anthropic block does not round-trip at all. A redacted_thinking block, reasoning the provider returns encrypted, is skipped by the anthropic stream like any block that is not text, thinking or tool_use. It never becomes a ReasoningPart, so it is not in res.Messages and is never sent back. ADR 0013 lists redacted thinking blocks as a known gap of the anthropic adapter.
A part is unsigned when it came from the openai adapter (a server’s DeepSeek-style reasoning_content), from wefttest.Think, or from Gemini thought text on a step with tool calls, whose signature rides the function call instead. Anthropic’s thinking blocks and Gemini’s thoughts on a step without calls are signed, and neither adapter can tell whose signature a part carries: after a provider switch each sends the other’s signature as if it were its own. On Gemini, a step with tool calls returns each call’s own signature on that call; when no call has one (a transcript recorded before per-call signatures), the reasoning’s signature goes back on the first call.
A step yields one part per provider block: a delta that carries a signature closes the block, and the next reasoning delta opens a new one. Reasoning without any signature accumulates into a single block. The package example is ExampleReasoningPart.
Switch providers
Section titled “Switch providers”Strip ReasoningParts from a transcript before a different provider reads it. A signed part is sent as it is, so Anthropic would get a thinking block carrying Gemini’s signature, and Gemini would get Anthropic’s signature as a thoughtSignature. Neither is that provider’s own signature, so the request is expected to be rejected (Gemini validates the signatures it gets back). weft has no helper for this; a plain filter, in thinking/main.go:
// withoutReasoning returns msgs with every ReasoningPart dropped, for a// transcript another provider is about to read.func withoutReasoning(msgs []weft.Message) []weft.Message { out := make([]weft.Message, 0, len(msgs)) for _, m := range msgs { parts := make([]weft.Part, 0, len(m.Content)) for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); !ok { parts = append(parts, p) } } out = append(out, weft.Message{Role: m.Role, Content: parts}) } return out}
// noReasoning wraps a backup model so it never receives reasoning.type noReasoning struct{ weft.Model }
func (m noReasoning) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { req.Messages = withoutReasoning(req.Messages) return m.Model.Stream(ctx, req)}
// Info names the wrapped adapter in mw.Fallback's attempt report.func (m noReasoning) Info() weft.ModelInfo { return weft.InfoOf(m.Model) }
// Unwrap lets mw.Fallback find a self-reporting model inside, such as// one wrapped in mw.Retry, so its attempts are not reported twice.func (m noReasoning) Unwrap() weft.Model { return m.Model }Wrap a cross-provider mw.Fallback backup in the filter, and filter res.Messages before you continue the conversation on another model with weft.UseModel:
agt := weft.New(primary, lookup, weft.WrapModel(mw.Fallback(noReasoning{backup})), // the backup gets no reasoning)res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { return err}// Continue on another provider: filter the transcript first.if _, err := agt.Generate(ctx, weft.Messages(withoutReasoning(res.Messages)...), weft.Prompt("Thanks."), weft.UseModel(other)); err != nil { return err}transcript keeps: 1 reasoning partbackup received: 0 reasoning partsother model received: 0 reasoning partsThe filter changes only what the other provider reads; res.Messages keeps every part. Wrap only the backup: the primary still needs its own signatures (gotcha). A step the backup answered leaves the backup’s signed parts in the transcript, and the primary’s next request carries them. With reasoning on at both ends, filter the primary’s requests too, and accept that the primary then loses its own signatures. Info forwards the adapter’s identity, so mw.Fallback’s attempt report names the backup. Unwrap lets mw.Fallback find a backup that reports its own attempts, such as one wrapped in mw.Retry, so those attempts are not reported twice.
Complete example
Section titled “Complete example”thinking/main.go sets a default, overrides it per run, streams reasoning, round-trips a signed block, and strips reasoning before a provider switch:
// Command thinking runs the examples of the guide "Control reasoning// (thinking)": go run ./thinking. Every model is scripted with wefttest,// so it runs offline; swap in a provider adapter for a real one.package main
import ( "context" "encoding/json" "errors" "fmt" "io" "iter" "os"
"github.com/weftgo/weft" "github.com/weftgo/weft/mw" "github.com/weftgo/weft/wefttest")
// levels names the neutral scale for printing.var levels = map[weft.ThinkingLevel]string{ weft.ThinkUnset: "unset", weft.ThinkOff: "off", weft.ThinkLow: "low", weft.ThinkMedium: "medium", weft.ThinkHigh: "high",}
// perRun: the agent thinks off by default; one run asks for high.func perRun(ctx context.Context, w io.Writer) error { model := wefttest.Script(wefttest.Say("ok"), wefttest.Say("ok")) agt := weft.New(model, weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkOff}), // every run's default )
deep := weft.Thinking(weft.ThinkingConfig{Level: weft.ThinkHigh, Budget: 2048}) if _, err := agt.Generate(ctx, deep, weft.Prompt("Plan the migration.")); err != nil { return err } if _, err := agt.Generate(ctx, weft.Prompt("What time is it in UTC?")); err != nil { return err } for i, req := range model.Requests() { // the scripted model records what each run asked for fmt.Fprintf(w, "run %d asked for: level=%s budget=%d\n", i+1, levels[req.Thinking.Level], req.Thinking.Budget) } return nil}
// parts streams a reasoning step and reads its parts back.func parts(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Think("The user greets; reply in kind.", wefttest.Say("Hello!")), ) agt := weft.New(model) run := agt.Stream(ctx, weft.Prompt("Hi.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.ReasoningDelta: fmt.Fprintln(w, "reasoning:", ev.Text) case weft.TextDelta: fmt.Fprintln(w, "text:", ev.Text) } } res, err := run.Wait() if err != nil { return err } for _, p := range res.Messages[1].Content { // the assistant message switch p := p.(type) { case weft.ReasoningPart: fmt.Fprintf(w, "part: reasoning %q, signed: %t\n", p.Text, p.Signature != "") case weft.TextPart: fmt.Fprintf(w, "part: text %q\n", p.Text) } } return nil}
// signed scripts a provider block that carries a signature, the way// Anthropic and Gemini send theirs.func signed(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.Raw( weft.ModelReasoningDelta{Text: "Check the order first."}, weft.ModelReasoningDelta{Signature: "sig-abc"}, // closes the block weft.ModelTextDelta{Text: "Order 1234 has shipped."}, weft.ModelFinish{Reason: weft.StopEndTurn}, ), wefttest.Say("You are welcome."), ) agt := weft.New(model) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } for _, p := range res.Messages[1].Content { if r, ok := p.(weft.ReasoningPart); ok { fmt.Fprintf(w, "signed block: %q signature=%s\n", r.Text, r.Signature) } } // The transcript goes back to the model with the signature intact. if _, err := agt.Generate(ctx, weft.Messages(res.Messages...), weft.Prompt("Thanks.")); err != nil { return err } for _, p := range model.LastRequest().Messages[1].Content { if r, ok := p.(weft.ReasoningPart); ok { fmt.Fprintf(w, "sent back: signature=%s\n", r.Signature) } } return nil}
// withoutReasoning returns msgs with every ReasoningPart dropped, for a// transcript another provider is about to read.func withoutReasoning(msgs []weft.Message) []weft.Message { out := make([]weft.Message, 0, len(msgs)) for _, m := range msgs { parts := make([]weft.Part, 0, len(m.Content)) for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); !ok { parts = append(parts, p) } } out = append(out, weft.Message{Role: m.Role, Content: parts}) } return out}
// noReasoning wraps a backup model so it never receives reasoning.type noReasoning struct{ weft.Model }
func (m noReasoning) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] { req.Messages = withoutReasoning(req.Messages) return m.Model.Stream(ctx, req)}
// Info names the wrapped adapter in mw.Fallback's attempt report.func (m noReasoning) Info() weft.ModelInfo { return weft.InfoOf(m.Model) }
// Unwrap lets mw.Fallback find a self-reporting model inside, such as// one wrapped in mw.Retry, so its attempts are not reported twice.func (m noReasoning) Unwrap() weft.Model { return m.Model }
// countReasoning counts the ReasoningParts in msgs.func countReasoning(msgs []weft.Message) int { n := 0 for _, m := range msgs { for _, p := range m.Content { if _, ok := p.(weft.ReasoningPart); ok { n++ } } } return n}
// switchProviders sends a transcript with a signed block to a backup// and to another model, without the block.func switchProviders(ctx context.Context, w io.Writer) error { type lookupInput struct { OrderID string `json:"order_id"` } lookup := weft.Tool("lookup_order", "Look up an order by ID.", func(ctx context.Context, in lookupInput) (string, error) { return "shipped", nil }) primary := wefttest.Script( wefttest.Raw( weft.ModelReasoningDelta{Text: "Look the order up.", Signature: "sig-primary"}, weft.ModelToolCall{ID: "c1", Name: "lookup_order", Args: json.RawMessage(`{"order_id":"1234"}`)}, weft.ModelFinish{Reason: weft.StopToolCalls}, ), wefttest.Fail(errors.New("primary down")), ) backup := wefttest.Script(wefttest.Say("Order 1234 has shipped.")) other := wefttest.Script(wefttest.Say("You are welcome.")) agt := weft.New(primary, lookup, weft.WrapModel(mw.Fallback(noReasoning{backup})), // the backup gets no reasoning ) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } // Continue on another provider: filter the transcript first. if _, err := agt.Generate(ctx, weft.Messages(withoutReasoning(res.Messages)...), weft.Prompt("Thanks."), weft.UseModel(other)); err != nil { return err } fmt.Fprintf(w, "transcript keeps: %d reasoning part\n", countReasoning(res.Messages)) fmt.Fprintf(w, "backup received: %d reasoning parts\n", countReasoning(backup.LastRequest().Messages)) fmt.Fprintf(w, "other model received: %d reasoning parts\n", countReasoning(other.LastRequest().Messages)) return nil}
func run(ctx context.Context, w io.Writer) error { steps := []struct { title string fn func(context.Context, io.Writer) error }{ {"per run", perRun}, {"parts", parts}, {"signed", signed}, {"switch providers", switchProviders}, } for _, s := range steps { fmt.Fprintf(w, "== %s\n", s.title) if err := s.fn(ctx, w); err != nil { return fmt.Errorf("%s: %w", s.title, err) } } return nil}
func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }}View on GitHub · run it from docs-site/examples:
go run ./thinkinggo test ./thinking== per runrun 1 asked for: level=high budget=2048run 2 asked for: level=off budget=0== partsreasoning: The user greets; reply in kind.text: Hello!part: reasoning "The user greets; reply in kind.", signed: falsepart: text "Hello!"== signedsigned block: "Check the order first." signature=sig-abcsent back: signature=sig-abc== switch providerstranscript keeps: 1 reasoning partbackup received: 0 reasoning partsother model received: 0 reasoning partsBest practices & gotchas
Section titled “Best practices & gotchas”- Leave the level unset to keep the provider’s default.
ThinkUnsetsends nothing, so an adapter’s construction setting, such asanthropic.Thinking(true), applies. (Source:weft/core/model.go:64-78) - Do not strip
ReasoningParts from a transcript you send back to the same provider. They carry the signatures the anthropic adapter returns asthinkingblocks and the google adapter returns on the turn’s thought or function-call parts; strip them and the provider gets its own reasoning back without them. (Source:weft/anthropic/convert.go:270-285,weft/google/convert.go:259-327) - Do not count on Anthropic’s redacted thinking reaching the next request. The anthropic adapter drops
redacted_thinkingblocks when it reads the stream, so a step that returned one goes back to the API without it, and nothing in the transcript or the events shows it was there. (Source:weft/anthropic/stream.go:90-103, ADR 0013docs/adr/0013-adapter-contract.md:159) - Strip reasoning before a provider switch. After
weft.UseModelor a cross-providermw.Fallback, anthropic and google send a signed part from the other provider as their own, and the request is expected to be rejected. An unsigned part is dropped silently, and openai drops every part. Filter the transcript the other provider reads (Switch providers). (Source:weft/anthropic/convert.go:278-281,weft/google/convert.go:278-322,weft/openai/convert.go:203-208; scratch httptest capture) - Expect a level to be dropped where a provider has no form for it. Adapters map what the provider can express and document what they drop; check the request’s
thinking.wirein Studio. (Source:weft/core/agent.go:328-329, ADR 0013) - Use
wefttest.Thinkto test reasoning offline. It prefixes a scripted turn with an unsigned reasoning delta; script signed blocks withwefttest.Raw. (Source:wefttest.Thinkgodoc)
See also
Section titled “See also”- Connect a model provider: what each adapter sends
- What is a Model? The provider contract
- Change an agent’s configuration for one run
- Stream a run’s events
Symbols used: weft.Thinking · weft.ThinkingOption · weft.ThinkingConfig · weft.ThinkingLevel · weft.ThinkUnset · weft.ThinkOff · weft.ThinkLow · weft.ThinkMedium · weft.ThinkHigh · Agent.Thinking · weft.ReasoningPart · weft.ReasoningDelta · weft.ModelReasoningDelta · weft.ModelRequest · weft.Unwrap · weft.UseModel · weft.InfoOf · mw.Fallback · weft.PrepareStep · weft.Messages · weft.New · wefttest.Think · wefttest.Raw