diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b7bd5c7a1..5d93a85be 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -389,7 +389,7 @@ recorded as a prediction failure (`noPrediction`). - In models.dev, entries from `deepseek`, `kimi-code-plan-cn` and `kimi-code-plan-global` gain `none` only when they have both a `toggle` and effort levels; the DeepSeek and Kimi APIs accepted that value in [#1098](https://github.com/yetone/magpie/issues/1098). Other providers keep their listed levels because their APIs may reject `none`; toggle-only entries remain level-less ([`mdModel.efforts`](../../internal/catalog/catalog.go)). - Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 or 422 whose error names `extra_body`, `include_thoughts` or thinking at all (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, its least, or at the model's lowest level where it has no `minimal` (`geminiLevels`: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (`geminiRefusedLevel`): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (`levelRefused`), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own `none` or `minimal` that Gemini turns away this way is asked again at the model's lowest level (`onEffort`), and that level goes at the lowest from then on (`turnedAway`); the other still goes as sent, as AI Studio takes `none` from gemini-3.8-flash. A refusal that names the levels the model takes (`effortLevelsNamed`, Command Code's for Qoder's `none`) marks reasoning off as a whole (`offRefused`): both go at the lowest from then on; one that lists the other among the levels taken (`otherOffNamed`, quoted, OpenAI's for gpt-5.1's `minimal`) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking. - A Gemini 3 or later model (by its id, `geminiGeneration`) on an Anthropic or Chat upstream that isn't Gemini's own API (a relay serving Gemini under a host of its own) is asked a thinking level, never a budget, as Gemini 4 turns every `thinkingBudget` away (#2083) and such a relay makes one from what it is sent (`geminiLevelBody` in [`gemini_level_body.go`](../../internal/gateway/gemini_level_body.go), run in `passthrough` and `forwardTranslated` after `xaiBody`; Mamba_asr on X). Anthropic: thinking `enabled` with `budget_tokens` goes as thinking `adaptive` with `output_config.effort`, the budget bucketed by `effortOfBudget` unless the request names an effort. Chat: `extra_body.google.thinking_config`'s budget goes as its `thinking_level` (-1 as none, 0 as `low`). Either way the level is fitted to the model's (`geminiLevelFor`: the catalog's levels, else nothing above `high`, and `medium` as `high` on a Gemini 3 Pro). Another vendor's model and a Gemini 2.x keep the body as sent (`TestGeminiRelayAskedALevel`). A relay that doesn't know `adaptive` uses the model's default thinking. -- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses a turn's effort on a `{role: "system"}` message (`withoutTurnEffort`: a relay's "messages.1.output_config: Extra inputs are not permitted", or OpenRouter's "Mid-conversation reasoning effort (configuration_update) is not supported on " on DeepSeek and GLM, #3696; `TestOpenRouterTurnEffortLeftOut`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471). +- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses a turn's effort on a `{role: "system"}` message (`withoutTurnEffort`: a relay's "messages.1.output_config: Extra inputs are not permitted", or OpenRouter's "Mid-conversation reasoning effort (configuration_update) is not supported on " on DeepSeek and GLM, #3696; `TestOpenRouterTurnEffortLeftOut`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). `thinking.display` is Claude's: a model not read as a Claude (no `claudeVersion` match and no "claude" in its name) is sent its thinking without it (`withoutForeignDisplay` in [`anthropic_shapes.go`](../../internal/gateway/anthropic_shapes.go)), since pi-ai, dsh's client, asks `display: "summarized"` beside every reasoning model's budget and Alibaba Cloud's Anthropic endpoint answered a Qwen model with 400 (StudyingPython on X; `TestDisplayGoesToClaudeOnly`); a display forced in the provider's own fields still goes. A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471). - 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, MiniMax's MiniMax-M3.1-Flash and its -Preview, and any `gpt-` id on a Messages endpoint, such as a relay's: it showed every request at medium on the relay's console, zxz8009195489 on Discord, `TestGPTMessagesEffortInOutputConfig`) 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. diff --git a/internal/gateway/anthropic_shapes.go b/internal/gateway/anthropic_shapes.go index 042399e67..13a9701fb 100644 --- a/internal/gateway/anthropic_shapes.go +++ b/internal/gateway/anthropic_shapes.go @@ -202,6 +202,28 @@ func (s *Server) withoutRefusedShapes(p provider.Provider, body []byte) []byte { return body } +// withoutForeignDisplay is body without thinking.display when its model +// isn't a Claude. display says how Claude shows its thinking (summarized, +// omitted), and only Anthropic's models read it; pi-ai, DeepSeek Harness's +// client, asks display "summarized" with the budget of every model it +// takes to reason, and Alibaba Cloud's Anthropic endpoint (Bailian, its +// Coding Plan) turned the request away with a 400 for a Qwen model +// (StudyingPython on X). A model named as a Claude however a relay spells +// it (claudeVersionOf), or with "claude" anywhere in its name, keeps the +// display it was asked, and so does a body that names no model. The +// user's own fields for the provider go on after this, so a display they +// put there themselves is sent. +func withoutForeignDisplay(body []byte) []byte { + if !bodyHas(body, `"display"`) || !gjson.GetBytes(body, "thinking.display").Exists() { + return body + } + m := modelOf(body) + if _, _, ok := claudeVersionOf(m); ok || m == "" || strings.Contains(strings.ToLower(m), "claude") { + return body + } + return withDisplay(body, true) +} + // withDisplay is body with thinking.display left out, or (not all) only a // value beyond summarized and omitted: "highlights" as "summarized", the // thinking still shown; "updates", or any other, left out, as Claude Code diff --git a/internal/gateway/foreign_display_test.go b/internal/gateway/foreign_display_test.go new file mode 100644 index 000000000..9165e0595 --- /dev/null +++ b/internal/gateway/foreign_display_test.go @@ -0,0 +1,110 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// displayStrictVendor stands in for an Anthropic-compatible endpoint whose +// non-Claude models take thinking enabled with a budget but turn +// thinking.display away with a 400, as Alibaba Cloud's did for a Qwen +// model (StudyingPython on X). The refusal's words here are a stand-in: +// Alibaba's own weren't seen. +type displayStrictVendor struct { + mu sync.Mutex + bodies []map[string]any +} + +func (v *displayStrictVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var m map[string]any + json.Unmarshal(b, &m) + v.mu.Lock() + v.bodies = append(v.bodies, m) + v.mu.Unlock() + th, _ := m["thinking"].(map[string]any) + model, _ := m["model"].(string) + w.Header().Set("Content-Type", "application/json") + if _, ok := th["display"]; ok && !strings.Contains(model, "claude") { + w.WriteHeader(400) + io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"<400> InternalError.Algo.InvalidParameter: thinking.display is not supported"}}`) + return + } + if m["stream"] == true { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, anthropicSSE("ok")) + return + } + io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"`+model+`","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`) +} + +func (v *displayStrictVendor) last() map[string]any { + v.mu.Lock() + defer v.mu.Unlock() + if len(v.bodies) == 0 { + return nil + } + return v.bodies[len(v.bodies)-1] +} + +// DeepSeek Harness's client (pi-ai's anthropic-messages) asks every model +// it takes to reason for thinking enabled with a budget and display +// "summarized". display is Claude's alone, and Alibaba Cloud's Anthropic +// endpoint answered a Qwen model's request with a 400. A non-Claude model +// is sent its budget without display; a Claude, relayed or translated, +// keeps the display it is asked (#1485), and a display the user put in the +// provider's own fields is sent as they wrote it. +func TestDisplayGoesToClaudeOnly(t *testing.T) { + fresh(t) + up := &displayStrictVendor{} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "bailian", Name: "Bailian Token Plan", Key: "k", Preset: "bailian-token-plan", + Anthropic: srv.URL + "/apps/anthropic", Models: []string{"qwen3.7-plus", "glm-5", "kimi-k2.5"}}); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL, + Models: []string{"claude-opus-4-7", "claude-sonnet-4-5", "claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + piAI := func(model string) string { + return `{"model":"` + model + `","max_tokens":32000,"stream":false,"thinking":{"type":"enabled","budget_tokens":1024,"display":"summarized"},"messages":[{"role":"user","content":"hi"}]}` + } + for _, c := range []struct { + name, path, body, thinking string + }{ + {"Qwen on Bailian", "/v1/messages", piAI("bailian/qwen3.7-plus"), `{"budget_tokens":1024,"type":"enabled"}`}, + {"GLM on Bailian", "/v1/messages", piAI("bailian/glm-5"), `{"budget_tokens":1024,"type":"enabled"}`}, + {"Kimi on Bailian, adaptive asked", "/v1/messages", + `{"model":"bailian/kimi-k2.5","max_tokens":32000,"thinking":{"type":"adaptive","display":"summarized"},"messages":[{"role":"user","content":"hi"}]}`, + `{"type":"adaptive"}`}, + {"an older Claude keeps its display", "/v1/messages", piAI("relay/claude-sonnet-4-5"), `{"budget_tokens":1024,"display":"summarized","type":"enabled"}`}, + {"an adaptive Claude keeps it", "/v1/messages", piAI("relay/claude-opus-4-7"), `{"display":"summarized","type":"adaptive"}`}, + {"a Responses client's summary to Claude", "/v1/responses", + `{"model":"relay/claude-opus-5-5","reasoning":{"effort":"high","summary":"auto"},"input":[{"role":"user","content":"hi"}]}`, + `{"display":"summarized","type":"adaptive"}`}, + } { + t.Run(c.name, func(t *testing.T) { + if code, body := post(t, c.path, c.body); code != 200 { + t.Fatalf("status %d: %s", code, body) + } + if th, _ := json.Marshal(up.last()["thinking"]); string(th) != c.thinking { + t.Errorf("thinking = %s, want %s", th, c.thinking) + } + }) + } + + // a display the user forced in the provider's own fields is theirs to send + withExtraBody(t, "bailian", `{"!thinking":{"type":"enabled","budget_tokens":2048,"display":"omitted"}}`) + post(t, "/v1/messages", piAI("bailian/qwen3.7-plus")) + if th, _ := json.Marshal(up.last()["thinking"]); string(th) != `{"budget_tokens":2048,"display":"omitted","type":"enabled"}` { + t.Errorf("with the user's own fields, thinking = %s", th) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 5cbf9acfc..73753a246 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6190,6 +6190,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // "enabled" (thinkingNeededRefusal): that type it keeps body = adaptiveThinking(body) } + // display is Claude's: pi-ai (DeepSeek Harness) asks it of every + // model that reasons, and Alibaba Cloud's Qwen turns it away + body = withoutForeignDisplay(body) body = s.withoutRefusedShapes(p, body) // the thinking blocks it refused as another conversation's // (thinking_bound.go), every route to it alike