gateway: the user's own Max output lowers a plain provider's max_tokens, not only a group's (YaCo on Discord)

Claude Code asks claude-opus-5-5 for max_tokens 128000. A relay that
holds back max_tokens x price from a key's quota answered 403 "token
quota is not enough ... need $2.59" for every turn (128000 x $20/M plus
~8K input x $4/M). Setting the provider's Max output didn't help: the
gateway lowered max_tokens with withMaxOutput only inside a group
(outputLimit), so a request routed straight to a provider went out as
the agent asked.

userOutput finds the Max output the user set for the provider's model
(provider > model or the provider's "*", Entry.OutputSet) and lowers a
larger request to it on any route. Only the user's own value does this
outside a group: a vendor's catalog figure may be stale. Group routing
is unchanged.

Run:
- TestUserMaxOutputLowersAPlainProvidersRequest (new): 128000 -> 32000
  with Max output 32k on the model, 8000 kept, a sibling model with no
  Max output kept at 128000. Red without the gateway.go change ("went
  as 128000").
- go test ./internal/gateway -count=1 (whole package, -timeout 45m):
  ok, 1200s, before rebasing onto 4e9335c96; after the rebase the
  Output/MaxTokens tests again: ok.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- A real Claude Code 2.1.29x against a fake server with the reporter's
  env: it sends max_tokens 128000 for claude-opus-5-5 with or without
  magpie. Not tried against the reporter's relay.
This commit is contained in:
yetone
2026-10-14 21:11:42 +08:00
parent 7f968b95dd
commit b9c589ebb1
4 changed files with 69 additions and 2 deletions
+1 -1
View File
@@ -145,7 +145,7 @@ recorded as a prediction failure (`noPrediction`).
- Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept.
- 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.
- A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`.
- A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`).
- A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale.
- A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`; a Zed subscription's Claude in `serveZed`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`).
## Remote magpie APIs
+5 -1
View File
@@ -2174,11 +2174,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
continue
}
// a group tells agents the longest reply a member of it gives
// (groupEntries); each member is asked for no more than its own
// (groupEntries); each member is asked for no more than its own.
// Outside a group only the user's own Max output lowers a request
// (userOutput): a vendor's figure may be stale, the user's is asked
if isGroup {
if n := outputLimit(c.p, c.model); n > 0 {
attemptBody = withMaxOutput(from, attemptBody, n)
}
} else if n := userOutput(c.p, c.model); n > 0 {
attemptBody = withMaxOutput(from, attemptBody, n)
}
picked := false // the effort asked for in place of the agent's
// a member fixed at an effort (#189), else the model asked for at
+16
View File
@@ -18,6 +18,22 @@ func outputLimit(p provider.Provider, model string) int {
return 0
}
// userOutput is the Max output the user set for p's model (provider ›
// model, or the provider's "*"), 0 when they set none. A request asking
// for more is lowered to it on any route, not only in a group: Claude Code
// asks claude-* models for their full 128000 and isn't told magpie's
// figure for them (claudeOutput), so a key whose quota is held per request
// as max_tokens times the price turned every turn away, and the field the
// editor says caps max_tokens did nothing (YaCo on Discord).
func userOutput(p provider.Provider, model string) int {
for _, e := range provider.Served() {
if e.Group == "" && e.Provider.ID == p.ID && (e.Model == model || e.ID == model) && e.OutputSet && e.Output > 0 {
return e.Output
}
}
return 0
}
// askedOutput is the reply limit a request that names none is sent on
// Anthropic's Messages API, which needs one: the model's own as the agents
// are told it (the user's Max output, else the vendor's list or
+47
View File
@@ -0,0 +1,47 @@
package gateway
import (
"net/http/httptest"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// YaCo on Discord: Claude Code asks claude-opus-5-5 for its full 128000
// (its own registry's max_output_tokens) and magpie writes no
// CLAUDE_CODE_MAX_OUTPUT_TOKENS for a claude-* model, so a key whose quota
// is held per request as max_tokens times the price was turned away on
// every turn. The Max output the user sets on the provider's model lowers
// such a request outside a group too; with none set the agent's own goes
// as it is, and a request under the user's limit isn't raised.
func TestUserMaxOutputLowersAPlainProvidersRequest(t *testing.T) {
fresh(t)
up := &adaptiveVendor{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "anth", Name: "Anth", Key: "k", Anthropic: srv.URL,
Models: []string{"claude-opus-5-5", "claude-sonnet-5-5"}}); err != nil {
t.Fatal(err)
}
if err := provider.SetModelOutput("anth/claude-opus-5-5", 32000); err != nil {
t.Fatal(err)
}
ask := func(model string, max int) float64 {
t.Helper()
body := `{"model":"anth/` + model + `","max_tokens":` + itoa(max) + `,"thinking":{"type":"adaptive","display":"omitted"},"output_config":{"effort":"medium"},"stream":false,"messages":[{"role":"user","content":"hi"}]}`
if code, out := post(t, "/v1/messages", body); code != 200 {
t.Fatalf("status %d: %s", code, out)
}
n, _ := up.last()["max_tokens"].(float64)
return n
}
if n := ask("claude-opus-5-5", 128000); n != 32000 {
t.Errorf("Claude Code's 128000 went as %v, want the user's 32000", n)
}
if n := ask("claude-opus-5-5", 8000); n != 8000 {
t.Errorf("8000 went as %v, want as asked", n)
}
if n := ask("claude-sonnet-5-5", 128000); n != 128000 {
t.Errorf("a model with no Max output set went as %v, want the agent's 128000", n)
}
}