Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: a model whose upstream says thinking.type must be "enabled" is asked again thinking

yetone25df3187bf88
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 554dedc6c..a2f149245 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -265,6 +265,7 @@ recorded as a prediction failure (`noPrediction`).
- A vendor's model that takes its level in `output_config.effort` beside thinking on (`effortInOutputConfig` in [`anthropic.go`](../../internal/gateway/anthropic.go): Z.ai's GLM-5.2 and GLM-5.3, and MiniMax's MiniMax-M3.1-Flash and its -Preview) is sent the effort there next to the budget: built from a Chat or Responses client's effort (`buildAnthropic`, when it sends a budget), or added to an Anthropic client's request from its budget's nearest level, fitted to the model's levels (`withOutputEffort`, in `passthrough`). A budget alone left GLM at its default, and under an 8192 cap gave MiniMax's medium to max one budget, 7168 (shin4 on plugins#316). A client that asks such a model adaptively, with its level in `output_config.effort`, has both kept (Z.ai takes adaptive with the level, tried live on GLM-5.3); dsh is written to ask them so (GLM-5.2 and GLM-5.3: `AdaptiveWithEffort`, `forceAdaptiveThinking` in `dshKindConfig`; MiniMax not yet, #3496), since pi-ai's budget path clamps Max to high's 16384 and its Max reached GLM-5.3 as high (01huadalang on Discord, 10-24). Every other model, Claude and MiniMax-M3 included, gets the budget alone. `TestGLMEffortInOutputConfig`, `TestMiniMaxPluginGetsTheNativeEffort`, `TestNativeEffortLeavesOthersAlone`, `TestAdaptiveOnOutputEffortModelAsksItsLevel`, `TestDshMaxReachesOutputEffortModels`.
- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is. So is a relay that reads `disabled` as reasoning effort `none` and turns that level away naming the ones it takes (Sub2API's gpt-6.1-sol, "does not support reasoning effort \"none\"; use low, medium, high, xhigh or max", #1465); `refusesThinkingOff` is the one list of these refusals for both routes. A relayed request refused so marks the model (`markUnfit(offRefused)`), and its later requests go with thinking left to the model at once until magpie restarts, as auto mode's classifier asks on every action.
- A Chat or Responses client's reasoning turned off (`none`, `ThinkOff`), translated to an Anthropic endpoint (`buildAnthropic`), goes as `thinking: {type: "disabled"}`; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (`refusesThinkingOff`: `alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`, or `none` turned away naming the levels taken) is asked again at its least (`thinkingBackOn`), and `markUnfit(offRefused)` sends it so at once until magpie restarts. A translated request's level can differ from the one asked: `none` and `minimal` go as `low` where the model's levels don't say it stops (`effortOf`). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (`noteWireEffort`, `wireEffort` in [`wire_effort.go`](../../internal/gateway/wire_effort.go)). Gemini's builders say theirs their own way and are logged as asked.
+- An upstream that takes a model only with thinking enabled answers a request sent none, or sent it off (`thinkingOffUnlessAsked` for a vendor's model), with a 400 saying `thinking.type must be "enabled"` (`thinkingNeededRefusal`, read off the reply at any depth of a relay's wrapping, never off the provider: cybercaius's own 天翼云 relay turned Claude Desktop's connection check away so, v0.1.1862). It is asked again once thinking at Anthropic's least budget, 1024, with `max_tokens` raised past it by what was asked and `temperature`, `top_p` and `top_k` left out (`withThinkingEnabled`), and `markUnfit(thinkingNeeded)` keeps the model so until magpie restarts, by magpie's name and the vendor's (`markThinkingNeeded`): relayed, the body is given thinking at once (`passthrough`); translated, a Messages body once built, and a Chat or Responses one at its lowest effort (`thinkingBackOn`). `forwardOnce` doesn't make such a model's `enabled` adaptive (`adaptiveThinking`), `enabled` being the type it said it takes. A non-streaming client's translated request whose refusal came inside a 200 stream is asked again the same way (`translate`); a streaming client's is not ([`thinking_needed.go`](../../internal/gateway/thinking_needed.go)).
- A model the user ticked no levels of (`ModelReasonless` in [settings](../../internal/settings/settings.go), `SetModelReasonless`; the provider editor's Names & levels, or `magpie model efforts <provider/model> off`) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body with `withoutAnyReasoning` ([`quiet.go`](../../internal/gateway/quiet.go): Chat's `reasoning_effort`, `reasoning`, `thinking`, `enable_thinking` and `include`'s `reasoning.encrypted_content`, Responses' `reasoning`, Anthropic's `thinking` of any type and `output_config.effort`, Gemini's `thinkingConfig`), the Anthropic relay doesn't add `thinking:{type:disabled}` for it, and `forwardTranslated` clears `Effort`, `ThinkOff` and `Thinking` for its other callers. It offers no levels (`Efforts`, `entryFor`), is `Quiet`, and as a routing-group member doesn't take the group's levels away. The learned refusals above cover only reasoning *off* and Gemini levels; a vendor that answers a plain `reasoning_effort` with 422 (yuexian7 on Discord) is not learned, so this is the user's switch. `TestReasonlessModelSentNoReasoning`, `TestReasonlessAnthropicRelay`, `TestGroupReasonlessMemberKeepsLevels`, `model-reasonless.test.cjs`.
- Levels the user kept of a model's own (`ModelEfforts`, `SetModelEfforts`; `magpie model efforts`, the editor's Names & levels, `magpie model spec --reasoning`) only narrow what is offered (#92): `provider.Efforts` returns the vendor's list's or models.dev's levels, and `fitEffort` fits a request to those, so an agent asking xhigh of a model kept to low–high still asks xhigh. A model no list knows levels of can be given them (`magpie model spec --reasoning`, Dani Ariyanto on Discord); those are then its levels, a request is fitted to them, and it counts as reasoning (`entryFor`). `AutoVision` honours the user's `ModelImages` over the model's own (`seesAt`). `TestModelSpecReachesTheGateway`, `TestNarrowedVendorLevelsAskAsBefore`, `TestAutoVisionTakesTheUsersVision`.
- A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once — a Chat or Responses client's request translated to Messages (`forwardTranslated`) as much as a relayed one.
diff --git a/internal/gateway/desktop_probe_test.go b/internal/gateway/desktop_probe_test.go
index e31c885c4..6efc7376b 100644
--- a/internal/gateway/desktop_probe_test.go
+++ b/internal/gateway/desktop_probe_test.go
@@ -2,6 +2,8 @@ package gateway
import (
"encoding/json"
+ "io"
+ "net/http"
"net/http/httptest"
"strings"
"testing"
@@ -231,3 +233,147 @@ func TestClaudeDesktopProbeAsksNoClassifier(t *testing.T) {
t.Fatalf("a user's turn asked the classifier %d times", c.n())
}
}
+
+// ctyunRefusal is the body Desktop showed (cybercaius, v0.1.1862) as
+// magpie's message after "天翼云: ": a relay's error whose message is
+// its own upstream's refusal. The 天翼云 relay wraps that whole body as
+// its message in turn, so magpie's reading of it said it word for word.
+const ctyunRefusal = `{"error":{"message":"{\"code\":\"400\",\"message\":\"thinking.type must be \\\"enabled\\\" (type: invalid_request_error)\",\"type\":\"invalid_request_error\"} (request id: 20261028170149123456789)","type":"upstream_error","code":"Invalid_request"}}`
+
+// ctyunNeedsThinking answers as cybercaius's 天翼云 did a Messages request
+// whose thinking isn't enabled.
+func ctyunNeedsThinking(body []byte) (int, string) {
+ if gjson.GetBytes(body, "thinking.type").String() != "enabled" {
+ return ctyunRefused()
+ }
+ if b, m := gjson.GetBytes(body, "thinking.budget_tokens").Int(), gjson.GetBytes(body, "max_tokens").Int(); b < 1024 || m <= b {
+ return 400, `{"type":"error","error":{"type":"invalid_request_error","message":"max_tokens must be greater than thinking.budget_tokens"}}`
+ }
+ return 0, ""
+}
+
+func ctyunRefused() (int, string) {
+ out, _ := json.Marshal(map[string]any{"error": map[string]any{"message": ctyunRefusal, "type": "upstream_error", "code": "Invalid_request"}})
+ return 400, string(out)
+}
+
+// Desktop's check to a routing group whose member's upstream takes the
+// model only thinking (cybercaius, v0.1.1862: "thinking.type must be
+// \"enabled\""): magpie sent it thinking off (a vendor's model) or none
+// (a Claude's name), the refusal is read, and the check asked again
+// thinking at 1024 under a raised max_tokens, so Desktop gets 200. It is
+// remembered for the model: the next check, and a title, go thinking in
+// one call. Read off the reply: the provider's name has no part in it.
+func TestClaudeDesktopProbeThinkingNeeded(t *testing.T) {
+ const msg = `{"id":"m","type":"message","role":"assistant","model":"x","content":[{"type":"thinking","thinking":"hm","signature":"s"},{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":3}}`
+ for _, c := range []struct {
+ name, model string
+ proto provider.Protocol
+ }{
+ {"vendor model on Messages", "glm-5", provider.Anthropic},
+ {"claude name on Messages", "claude-haiku-5-5", provider.Anthropic},
+ {"chat", "glm-5", provider.Chat},
+ {"chat, refused in its stream", "glm-5", provider.Chat},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ ctyun := &fake{t: t, reply: msg, ctype: "application/json", refuse: ctyunNeedsThinking}
+ if c.proto == provider.Chat {
+ // a relay that turns reasoning_effort into thinking enabled
+ ctyun = &fake{t: t, reply: deepseekReply, refuse: func(body []byte) (int, string) {
+ if gjson.GetBytes(body, "reasoning_effort").String() == "" || gjson.GetBytes(body, "reasoning_effort").String() == "none" {
+ return ctyunRefused()
+ }
+ return 0, ""
+ }}
+ }
+ var h http.Handler = ctyun
+ if strings.HasSuffix(c.name, "in its stream") {
+ // the refusal as an event of a 200 stream
+ h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ ctyun.got = b
+ ctyun.calls++
+ if e := gjson.GetBytes(b, "reasoning_effort").String(); e == "" || e == "none" {
+ _, refusal := ctyunRefused()
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, "data: "+refusal+"\n\n")
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, deepseekReply)
+ })
+ }
+ setup(t, provider.Anthropic, &fake{t: t})
+ cu := httptest.NewServer(h)
+ t.Cleanup(cu.Close)
+ p := provider.Provider{ID: "ctyun", Name: "天翼云", Key: "k", Models: []string{c.model}}
+ if c.proto == provider.Chat {
+ p.Chat = cu.URL + "/v1"
+ } else {
+ p.Anthropic = cu.URL
+ }
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ if err := provider.SaveGroup(provider.Group{ID: "tianyi", Name: "天翼云", Members: []string{"ctyun/" + c.model}, Routing: provider.Ordered}); err != nil {
+ t.Fatal(err)
+ }
+ if err := provider.SetModelOrder("claude-desktop", []string{"group/tianyi"}); err != nil {
+ t.Fatal(err)
+ }
+ desktopPicked.Lock()
+ desktopPicked.model, desktopPicked.from = "", ""
+ desktopPicked.Unlock()
+ srv := New()
+ send := func(body string) (int, string) {
+ t.Helper()
+ req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
+ req.Header.Set("x-api-key", Token+"-claude-desktop")
+ req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh) Claude/2.7032.0 Chrome/140.0 Electron/38.0")
+ rec := httptest.NewRecorder()
+ srv.Handler().ServeHTTP(rec, req)
+ return rec.Code, rec.Body.String()
+ }
+ const probe = `{"model":"magpie-0958175816.anthropic.claude-haiku-5-5[1m]","max_tokens":1,"messages":[{"role":"user","content":"."}]}`
+ if code, body := send(probe); code != 200 {
+ t.Fatalf("check: %d %s (sent %s)", code, body, ctyun.got)
+ }
+ if ctyun.calls != 2 {
+ t.Fatalf("check: %d calls, want the refusal and one more", ctyun.calls)
+ }
+ if c.proto == provider.Anthropic {
+ if th := gjson.GetBytes(ctyun.got, "thinking"); th.Get("type").String() != "enabled" || th.Get("budget_tokens").Int() != 1024 || gjson.GetBytes(ctyun.got, "max_tokens").Int() <= 1024 {
+ t.Fatalf("check asked again with %s", ctyun.got)
+ }
+ }
+ // remembered: the next check and a title go thinking at once
+ for _, body := range []string{probe, `{"model":"ctyun/` + c.model + `","max_tokens":200,"system":"You write short session titles.","messages":[{"role":"user","content":"hi"}]}`} {
+ ctyun.calls = 0
+ if code, out := send(body); code != 200 || ctyun.calls != 1 {
+ t.Fatalf("after: %d in %d calls, %s (sent %s)", code, ctyun.calls, out, ctyun.got)
+ }
+ }
+ })
+ }
+}
+
+// withThinkingEnabled leaves a request that thinks as it is, and gives
+// one that doesn't the least budget under a limit raised past it.
+func TestWithThinkingEnabled(t *testing.T) {
+ for in, want := range map[string]string{
+ `{"max_tokens":16,"temperature":0}`: `{"max_tokens":1040,"thinking":{"budget_tokens":1024,"type":"enabled"}}`,
+ `{"max_tokens":8000,"thinking":{"type":"disabled"}}`: `{"max_tokens":8000,"thinking":{"budget_tokens":1024,"type":"enabled"}}`,
+ `{"max_tokens":2,"thinking":{"type":"between_tools"}}`: `{"max_tokens":1026,"thinking":{"budget_tokens":1024,"type":"enabled"}}`,
+ } {
+ got, ok := withThinkingEnabled([]byte(in))
+ var a, b any
+ if !ok || json.Unmarshal(got, &a) != nil || json.Unmarshal([]byte(want), &b) != nil || !jsonEqual(a, b) {
+ t.Errorf("withThinkingEnabled(%s) = %s %v, want %s", in, got, ok, want)
+ }
+ }
+ for _, in := range []string{`{"thinking":{"type":"enabled","budget_tokens":2048}}`, `{"thinking":{"type":"adaptive"}}`, `not json`} {
+ if _, ok := withThinkingEnabled([]byte(in)); ok {
+ t.Errorf("withThinkingEnabled(%s) changed it", in)
+ }
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index c9e7fcb23..353c16ec7 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -4244,7 +4244,11 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
// what every path to an Anthropic endpoint sends, relayed or
// built, with the model named as the vendor names it; before the
// shapes a provider refused are taken out, as it asks a display
- body = adaptiveThinking(body)
+ if m := modelOf(body); m == "" || s.fits(p.ID, thinkingNeeded(m), to) {
+ // not for a model whose upstream said thinking must be
+ // "enabled" (thinkingNeededRefusal): that type it keeps
+ body = adaptiveThinking(body)
+ }
body = s.withoutRefusedShapes(p, body)
if isKimi(p, to) || p.IsOpenCode() && strings.Contains(strings.ToLower(modelOf(body)), "deepseek") {
// Claude Code's deferred-tool blocks, for which Kimi's
@@ -4666,6 +4670,13 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
body = nb
}
}
+ if !s.fits(p.ID, thinkingNeeded(model), proto) {
+ // a model whose upstream said thinking must be enabled (below):
+ // sent thinking from the start, not refused on every request
+ if nb, ok := withThinkingEnabled(body); ok {
+ body = nb
+ }
+ }
}
// the effort as the agent sent it, fitted to the model's levels: Qoder's
// permission check asks "none", which Command Code turns away; and
@@ -5021,6 +5032,15 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(nb), r.Header); err != nil {
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
}
+ } else if nb, ok := withThinkingEnabled(body); ok && thinkingNeededRefusal.Match(b) {
+ // thinking left out or off, turned away by an upstream that
+ // takes the model only thinking (Claude Desktop's check, a
+ // title): asked again thinking at the least budget, and so
+ // from then on
+ s.markThinkingNeeded(p, proto, model, upstream)
+ if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(nb), r.Header); err != nil {
+ return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
+ }
} else if nb, ok := withoutSampling(body); ok && samplingDeprecated.Match(b) {
// a Claude by a name samplingAsTaken doesn't know refusing
// temperature, top_p or top_k (#1454)
@@ -5505,6 +5525,12 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
if to == provider.Anthropic && req.ThinkOff && !s.fits(p.ID, offRefused(model), to) {
req = thinkingBackOn(p, model, req)
}
+ if to != provider.Anthropic && (req.ThinkOff || req.Effort == "" || offEffort(req.Effort)) && !s.fits(p.ID, thinkingNeeded(model), to) {
+ // a model whose upstream said thinking must be enabled: asked
+ // to reason at its least on Chat or Responses (Anthropic's
+ // body is given thinking once built, below)
+ req = thinkingBackOn(p, model, req)
+ }
if forcesTool(req.ToolChoice) && !s.fits(p.ID, forcedRefused(model), to) {
req = unforced(req)
}
@@ -5629,6 +5655,14 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
return nil, to, err
}
noteWireEffort(ctx, to, sent)
+ if to == provider.Anthropic && !s.fits(p.ID, thinkingNeeded(model), to) {
+ // a model whose upstream said thinking must be enabled
+ // (thinkingNeededRefusal): a request built thinking off, or
+ // with none (a short one), goes thinking at the least budget
+ if nb, ok := withThinkingEnabled(body); ok {
+ body = nb
+ }
+ }
if to == provider.Chat && (p.IsBedrock() || p.IsAzure()) {
body = asCompletionTokens(body)
}
@@ -5738,6 +5772,16 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
req = thinkingBackOn(p, model, req)
continue
}
+ if res.StatusCode == http.StatusBadRequest && thinkingNeededRefusal.Match(b) && s.fits(p.ID, thinkingNeeded(model), to) {
+ if _, off := withThinkingEnabled(body); to == provider.Anthropic && off || to != provider.Anthropic && (req.ThinkOff || req.Effort == "" || offEffort(req.Effort)) {
+ // sent no thinking, or thinking off, which the upstream
+ // takes the model only with (Claude Desktop's check, a
+ // title): asked again thinking at its least, and so from
+ // then on
+ s.markThinkingNeeded(p, to, model, wire)
+ continue
+ }
+ }
if req.GeminiCompat && res.StatusCode == http.StatusBadRequest {
if l := geminiRefusedLevel(b); l != "" {
// a thinking level the model hasn't, turned away: Gemini's
@@ -6481,6 +6525,13 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
// a failure after it, which rested the account (#3274). Nothing has
// reached the client yet, so it is told the refusal, as it would be
// with nothing said
+ if col.err != "" && !saidAnything(col.res.Parts) && thinkingNeededRefusal.MatchString(col.err) && s.fits(p.ID, thinkingNeeded(model), actual) {
+ // the refusal of a request sent no thinking, carried in the
+ // stream rather than as a 400 (forwardTranslated asks again for
+ // that one): remembered, and asked once more, thinking
+ s.markThinkingNeeded(p, actual, model, provider.UpstreamNameIn(wiresOf(r.Context()), p.ID, model))
+ return s.translate(w, r, p, from, to, model, body, u)
+ }
if col.err != "" && (!saidAnything(col.res.Parts) || col.errSaid != nil) {
said := col.err
if markAntigravityRefused(w, p, request.System, said) {
diff --git a/internal/gateway/thinking_needed.go b/internal/gateway/thinking_needed.go
new file mode 100644
index 000000000..c669f0467
--- /dev/null
+++ b/internal/gateway/thinking_needed.go
@@ -0,0 +1,64 @@
+package gateway
+
+import (
+ "regexp"
+
+ "github.com/tidwall/gjson"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// thinkingNeededRefusal is an upstream turning away a Messages request
+// whose thinking isn't "enabled": thinking left out, or turned off as
+// magpie does for a vendor's model asked without it
+// (thinkingOffUnlessAsked). A relay in front of such a model answered
+// Claude Desktop's connection check ({"max_tokens":1,"messages":[…"."]},
+// no thinking) with `thinking.type must be "enabled"` (cybercaius on
+// Discord, v0.1.1862, his own 天翼云 provider). Read off the reply, not
+// the provider: any upstream that says it is asked again thinking.
+var thinkingNeededRefusal = regexp.MustCompile(`(?i)thinking[._ ]type\W+(?:must|should|has to) be\W+enabled\b`)
+
+// thinkingNeeded is how unfit remembers an upstream that takes model only
+// with thinking enabled (thinkingNeededRefusal).
+func thinkingNeeded(model string) string { return "thinking needed\x00" + model }
+
+// neededBudget is the thinking budget a request that asked for none is
+// sent at, for a model that needs thinking: Anthropic's least, which the
+// reply limit is raised past (withThinkingEnabled).
+const neededBudget = 1024
+
+// withThinkingEnabled is a Messages body that asked for no thinking, or
+// turned it off, sent thinking at the least budget instead, for a model
+// that takes no other: max_tokens is raised past the budget by what was
+// asked (a budget must be below it), and the sampling a thinking request
+// is refused with (temperature, top_p, top_k) left out. false for a body
+// that asks to think already, or isn't JSON.
+func withThinkingEnabled(body []byte) ([]byte, bool) {
+ if !gjson.ValidBytes(body) {
+ return nil, false
+ }
+ switch gjson.GetBytes(body, "thinking.type").String() {
+ case "enabled", "adaptive":
+ return nil, false
+ }
+ maxTokens := gjson.GetBytes(body, "max_tokens").Int()
+ if maxTokens <= neededBudget {
+ maxTokens = neededBudget + max(maxTokens, 1)
+ }
+ out := withoutFields(body, "temperature", "top_p", "top_k")
+ out = withFields(out, map[string]any{
+ "thinking": map[string]any{"type": "enabled", "budget_tokens": neededBudget},
+ "max_tokens": maxTokens,
+ })
+ return out, true
+}
+
+// markThinkingNeeded remembers that p takes model only thinking, by the
+// name magpie knows it and the vendor's (wire), which forwardOnce reads
+// off the body: thinking enabled isn't made adaptive for it there, as
+// "enabled" is the one type it said it takes.
+func (s *Server) markThinkingNeeded(p provider.Provider, to provider.Protocol, model, wire string) {
+ s.markUnfit(p.ID, thinkingNeeded(model), to)
+ if wire != "" && wire != model {
+ s.markUnfit(p.ID, thinkingNeeded(wire), to)
+ }
+}