From d4eae3618f483c7ba4b41ba72249b4dbe9e157cf Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 12 Oct 2026 00:53:36 +0800 Subject: [PATCH] gateway: reasoning off goes to an Anthropic API as thinking off, and the log says the level a translated request went at (#1636, jswysnemc) jswysnemc saw a custom provider think at another level than the one the agent asked. This commit fixes two places where magpie's own translation did that. - A Chat or Responses client turning reasoning off (effort none), translated to an Anthropic endpoint, was sent thinking enabled at a 4096-token budget (buildAnthropic read Effort "none" as a level). It now goes as thinking disabled. A model that refuses disabled (alwaysThinks / mandatoryReasoning / thinkingOffRefused, e.g. GLM) is asked again at its least (thinkingBackOn), and markUnfit(offRefused) sends it that way at once until restart. - none/minimal go as low to Chat/Responses for a model whose levels aren't known (effortOf). The route, the try and the usage log all said none/minimal. The route still keeps the level asked; the try and the usage log now say the level built (noteWireEffort/wireEffort via a context slot filled in forwardTranslated). Routing already draws asked -> went from the two. The passthrough path (a client on the provider's own API, e.g. Claude Code to an Anthropic relay) is unchanged: it sends the client's level as it came. Run: go test ./internal/gateway/ (full package, 304s, green); TestTranslatedEffortLoggedAsSent (8 cases) and TestTranslatedThinkingOffRefused fail with 11 assertions when the gateway.go/anthropic.go changes are reverted. gofmt; GOOS=linux and GOOS=windows go vet. Not tried: a real vendor's Anthropic API with thinking disabled. --- docs/subsystems/gateway-routing.md | 3 +- internal/gateway/anthropic.go | 13 ++- internal/gateway/gateway.go | 28 ++++-- internal/gateway/wire_effort.go | 67 ++++++++++++++ internal/gateway/wire_effort_test.go | 126 +++++++++++++++++++++++++++ 5 files changed, 229 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/wire_effort.go create mode 100644 internal/gateway/wire_effort_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 5f5e33b8e..60acdf2c5 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -79,6 +79,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - 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 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`); 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 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. +- 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 (`alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`) 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. - 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. - Claude Code's billing line (`x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;`, its own first system block, `cch` changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (`keepsBillingLine` in [`billing_line.go`](../../internal/gateway/billing_line.go): Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (`withoutBillingLine`): a vendor's model relayed on Messages (`passthrough`), every translation to Chat, Responses or Gemini (`forwardTranslated`, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, in `attempt`). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (`withoutBillingHeader`), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which `antigravityTurnsAway` reads (#666). - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. @@ -229,7 +230,7 @@ Covered by `TestSearchMCPServesWebSearch`, `TestSearchMCPWithNoSearcher`, ## Verification ```sh -go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls' +go test -tags nogui ./internal/gateway -run 'TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls' go test -tags nogui ./internal/gateway -run 'TestVertex' go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries' go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller' diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 7c6a77991..c2d552e58 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -732,7 +732,16 @@ func buildAnthropic(r *Request, model string) []byte { if maxTokens <= 0 { maxTokens = 16384 } - if (r.Thinking || r.Effort != "") && adaptiveOnly(model) { + // a client that turned reasoning off — Codex's or a Chat client's + // effort none, which Effort reads as low — is sent thinking off, not a + // low budget: it was thinking at 4096 tokens while the log said none + // (#1636). A model that won't stop thinking is asked again as before + // (forwardTranslated); thinkingOffAsTaken fits off to each Claude + think := (r.Thinking || r.Effort != "") && !r.ThinkOff + if r.ThinkOff { + out["thinking"] = map[string]any{"type": "disabled"} + } + if think && adaptiveOnly(model) { // Opus 4.7 and later leave the thinking text out unless asked // (display "omitted" by default), and a Chat or Responses client // that asked to reason would see none of it; OpenAI is asked for @@ -744,7 +753,7 @@ func buildAnthropic(r *Request, model string) []byte { } out["output_config"] = map[string]any{"effort": e} } - } else if think, budget := r.Thinking || r.Effort != "", budgetOf(r.Effort); think && (r.MaxTokens <= 0 || r.MaxTokens > 2048) { + } else if budget := budgetOf(r.Effort); think && (r.MaxTokens <= 0 || r.MaxTokens > 2048) { if r.MaxTokens > 0 { // the client's cap is what the model can write (Pi sends the // model's own output limit): the budget fits under it, leaving diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 73fa3fd80..5e9ecb070 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1868,6 +1868,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var lastTried provider.Provider // the last try's, for its model's context window and the usage's endpoint var skipped []string sent := "" // the reasoning the last try's model was asked for + wentAt := "" // and the level that went, once translated (wireEffort, #1636) where := "" // the last try's provider.Where, for the usage again := 0 // times the last one left has been tried again resealed := 0 // what of the conversation another account sealed was taken out: its reasoning, then its compaction @@ -2095,6 +2096,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro held := false // answered as its vendor did a moment ago, without asking var queued int64 // ms it waited for a slot of its key's or account's var laneErr error // turned away by its key's or account's queue + at := &wireAt{} // the level a translated request was built at // the models Copilot's Auto picked for it, where from, and which // were refused (#256) autoPicked := func() []provider.AutoPick { return nil } @@ -2107,7 +2109,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro } else { // a stream that fails before anything is said is let go at // once (hw.stop), not read on until the vendor hangs up - ctx, stop := context.WithCancel(r.Context()) + ctx, stop := context.WithCancel(withWireAt(r.Context(), at)) if isGroup { ctx = groupTry(ctx) } @@ -2237,7 +2239,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // stream's error; logged apart from the vendor's own errors call.Status, call.Error, call.Usage.ErrType = hw.status, c.p.Name+": "+hw.looped, loopErrType } - try := Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: time.Since(began).Milliseconds(), Error: call.Error, Queued: queued, + if wentAt = sent; at.set { + wentAt = at.effort + } + try := Try{ID: c.rest, Model: c.model, Effort: wentAt, Picked: picked, Fixed: fixed, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: time.Since(began).Milliseconds(), Error: call.Error, Queued: queued, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Auto: autoPicked()} if resetFirst != nil { // the reset spent for it before it was asked @@ -2359,7 +2364,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, - CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status, + CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status, TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true} failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) @@ -2402,7 +2407,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, Requested: call.Model, Served: call.Usage.Served, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, - CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status, + CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status, TTFT: try.TTFT, FirstText: try.FirstText, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true} failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) @@ -2800,7 +2805,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount, Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, - CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: call.Millis, Status: call.Status, + CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: call.Millis, Status: call.Status, TTFT: call.TTFT, FirstText: call.FirstText, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, ResponseID: call.Usage.ResponseID, Endpoint: endpointOf(r, from, call.To, lastTried, model), Stop: call.Usage.Stop, Archive: call.archiveName()} if tries > 1 { @@ -3988,6 +3993,9 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to r := *req r.Effort, req = onEffort(p, model), &r } + if to == provider.Anthropic && req.ThinkOff && !s.fits(p.ID, offRefused(model), to) { + req = thinkingBackOn(p, model, req) + } if forcesTool(req.ToolChoice) && !s.fits(p.ID, forcedRefused(model), to) { req = unforced(req) } @@ -4054,6 +4062,7 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to if err != nil { return nil, to, err } + noteWireEffort(ctx, to, sent) if to == provider.Chat && (p.IsBedrock() || p.IsAzure()) { body = asCompletionTokens(body) } @@ -4105,6 +4114,15 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to req = &r continue } + if to == provider.Anthropic && req.ThinkOff && res.StatusCode == http.StatusBadRequest && + (alwaysThinks.Match(b) || mandatoryReasoning.Match(b) || thinkingOffRefused.Match(b)) { + // a vendor's model that always thinks (GLM-5.3, #699) refuses + // the thinking off a client asked for (#1636): asked again + // thinking at its least, as it was before, and so from then on + s.markUnfit(p.ID, offRefused(model), to) + req = thinkingBackOn(p, model, req) + continue + } if req.GeminiCompat && res.StatusCode == http.StatusBadRequest { if l := geminiRefusedLevel(b); l != "" { // a thinking level the model hasn't, turned away: Gemini's diff --git a/internal/gateway/wire_effort.go b/internal/gateway/wire_effort.go new file mode 100644 index 000000000..1d906ba1c --- /dev/null +++ b/internal/gateway/wire_effort.go @@ -0,0 +1,67 @@ +package gateway + +import ( + "context" + + "github.com/yetone/magpie/internal/provider" +) + +// thinkingBackOn is req with the thinking off it asked for taken back, for +// a model that refused it: at the least the model has, as a request asking +// none was sent before thinking could be turned off (#1636). +func thinkingBackOn(p provider.Provider, model string, req *Request) *Request { + r := *req + r.ThinkOff = false + if r.Effort == "" || offEffort(r.Effort) { + r.Effort = onEffort(p, model) + } + return &r +} + +// wireAt is where a translated request leaves the reasoning it was built +// at, for the log (wireEffortOf); set says it was. +type wireAt struct { + effort string + set bool +} + +type wireAtKey struct{} + +// withWireAt is ctx carrying w, which forwardTranslated fills. +func withWireAt(ctx context.Context, w *wireAt) context.Context { + return context.WithValue(ctx, wireAtKey{}, w) +} + +// noteWireEffort leaves, where the request's context has a place for it, +// the reasoning req goes to to at. +func noteWireEffort(ctx context.Context, to provider.Protocol, req *Request) { + w, _ := ctx.Value(wireAtKey{}).(*wireAt) + if w == nil { + return + } + if e, ok := wireEffort(to, req); ok { + w.effort, w.set = e, true + } +} + +// wireEffort is the reasoning a request built from req asks the model for, +// in the words the log uses: what the client asked can go as another +// level once translated — effort none and minimal read as low where the +// model's levels don't say it can stop (effortOf), thinking turned off +// goes as off to Anthropic's API — and the log said the one asked while +// another was sent (#1636). false for an API whose builder says it its own +// way (Gemini's levels and budgets), which the log leaves as asked. +func wireEffort(to provider.Protocol, req *Request) (string, bool) { + switch { + case req.GeminiCompat: + return "", false + case to == provider.Anthropic: + if req.ThinkOff { + return "none", true + } + return req.Effort, true + case to == provider.Chat || to == provider.Responses: + return req.Effort, true + } + return "", false +} diff --git a/internal/gateway/wire_effort_test.go b/internal/gateway/wire_effort_test.go new file mode 100644 index 000000000..d16469326 --- /dev/null +++ b/internal/gateway/wire_effort_test.go @@ -0,0 +1,126 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +var anthropicHi = sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","usage":{"input_tokens":7}}}`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`, + `data: {"type":"content_block_stop","index":0}`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `data: {"type":"message_stop"}`) + +var chatHi = sse( + `data: {"id":"c1","model":"m1","choices":[{"delta":{"role":"assistant","content":"hi"}}]}`, + `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`) + +// A user-added provider whose model's levels no one lists (#1636, +// jswysnemc): a client asking reasoning off or minimal on another API +// than the provider's went at another level, while the request log and +// Routing said the one asked. Reasoning off went to an Anthropic API as +// thinking at a 4096-token budget; it goes as thinking off now. Where the +// level asked can't go as it is — none and minimal read as low for a +// model not known to stop (effortOf) — the route keeps what was asked +// and the try and the log what went. +func TestTranslatedEffortLoggedAsSent(t *testing.T) { + for _, c := range []struct { + up provider.Protocol + path, body string + asked, went, thing string // thing: what the upstream body asks, as "field=value" + }{ + {provider.Anthropic, "/v1/responses", `{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"none"}}`, "none", "none", "thinking=disabled"}, + {provider.Anthropic, "/v1/chat/completions", `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"none"}`, "none", "none", "thinking=disabled"}, + {provider.Anthropic, "/v1/responses", `{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"high"}}`, "high", "high", "thinking=enabled"}, + {provider.Chat, "/v1/responses", `{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"minimal"}}`, "minimal", "low", "reasoning_effort=low"}, + {provider.Chat, "/v1/responses", `{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"none"}}`, "none", "low", "reasoning_effort=low"}, + {provider.Chat, "/v1/responses", `{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"xhigh"}}`, "xhigh", "xhigh", "reasoning_effort=xhigh"}, + {provider.Responses, "/v1/chat/completions", `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"none"}`, "none", "low", "reasoning.effort=low"}, + // the same API: it goes as it came, and the log says so + {provider.Chat, "/v1/chat/completions", `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}],"reasoning_effort":"none"}`, "none", "none", "reasoning_effort=none"}, + } { + f := &fake{t: t, reply: chatHi} + if c.up == provider.Anthropic { + f.reply = anthropicHi + } + setup(t, c.up, f) + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(c.body))) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", c.body, rec.Code, rec.Body) + } + var got map[string]any + json.Unmarshal(f.got, &got) + field, want, _ := strings.Cut(c.thing, "=") + var v any + switch field { + case "thinking": + m, _ := got["thinking"].(map[string]any) + v = m["type"] + case "reasoning.effort": + m, _ := got["reasoning"].(map[string]any) + v = m["effort"] + default: + v = got[field] + } + if v != want { + t.Errorf("%s to %s: sent %s", c.body, c.up, f.got) + } + r := lastRoute(s) + if r.Effort != c.asked || len(r.Tries) != 1 || r.Tries[0].Effort != c.went { + t.Errorf("%s to %s: route at %q, tries %+v; want asked %q, went %q", c.body, c.up, r.Effort, r.Tries, c.asked, c.went) + } + recs := usage.Load(time.Time{}) + if len(recs) == 0 || recs[len(recs)-1].Effort != c.went { + t.Errorf("%s to %s: logged %+v, want %q", c.body, c.up, recs, c.went) + } + } +} + +// A vendor's model on its Anthropic API that won't stop thinking (Z.ai's +// GLM-5.3, #699) refuses the thinking off a Codex asking none is now sent +// (#1636): asked again thinking at its least, as before, and from then on +// asked so at once. +func TestTranslatedThinkingOffRefused(t *testing.T) { + var sent []string + f := &fake{t: t, reply: anthropicHi} + f.refuse = func(b []byte) (int, string) { + var v struct { + Thinking struct { + Type string `json:"type"` + } `json:"thinking"` + } + json.Unmarshal(b, &v) + sent = append(sent, v.Thinking.Type) + if v.Thinking.Type == "disabled" { + return 400, `{"type":"error","error":{"type":"invalid_request_error","message":"GLM-5.3 always engages in thinking and cannot be disabled"}}` + } + return 0, "" + } + setup(t, provider.Anthropic, f) + s := New() + for turn, want := range []string{"disabled,enabled", "enabled"} { + sent = nil + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"m1","stream":true,"input":"hi","reasoning":{"effort":"none"}}`))) + if rec.Code != 200 { + t.Fatalf("turn %d: %d %s", turn+1, rec.Code, rec.Body) + } + if strings.Join(sent, ",") != want { + t.Errorf("turn %d: thinking sent %v, want %s", turn+1, sent, want) + } + if r := lastRoute(s); len(r.Tries) != 1 || r.Tries[0].Effort != "low" { + t.Errorf("turn %d: tries %+v, want it logged at low", turn+1, r.Tries) + } + } +}