Files
magpie/internal/gateway/maxoutput.go
T
yetone b9c589ebb1 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.
2026-10-14 21:11:42 +08:00

112 lines
3.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package gateway
import (
"encoding/json"
"github.com/yetone/magpie/internal/provider"
)
// outputLimit is the most a reply of a provider's model may hold, where
// known: its catalog entry's (the user's setting, else the vendor's list
// or models.dev).
func outputLimit(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.Output > 0 {
return e.Output
}
}
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
// models.dev, within the window), or 0 when none is known. A Codex turn
// names none, and was sent a flat 16384, which a long thinking and tool
// turn ran out of, Codex showing "Incomplete response returned, reason:
// max_output_tokens" (#1792, tensornull).
func askedOutput(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) {
return e.PublishedOutput()
}
}
return 0
}
// defaultMaxTokens is what a request naming no reply limit is sent on
// Anthropic's API for a model whose limit isn't known.
const defaultMaxTokens = 16384
// withMaxOutput is body, in proto's words, asking for a reply of at most
// limit tokens: a request that asks for more is lowered to limit, and
// Anthropic's thinking budget, which must be under it, with it. A request
// that asks for limit or less, or names no limit, goes as it is.
func withMaxOutput(proto provider.Protocol, body []byte, limit int) []byte {
var v struct {
MaxTokens int `json:"max_tokens"`
MaxCompletionTokens int `json:"max_completion_tokens"`
MaxOutputTokens int `json:"max_output_tokens"`
Thinking *struct {
Type string `json:"type"`
Budget int `json:"budget_tokens"`
} `json:"thinking"`
GenerationConfig map[string]any `json:"generationConfig"`
}
if limit <= 0 || json.Unmarshal(body, &v) != nil {
return body
}
fields := map[string]any{}
switch proto {
case provider.Chat:
if v.MaxCompletionTokens > limit {
fields["max_completion_tokens"] = limit
}
if v.MaxTokens > limit {
fields["max_tokens"] = limit
}
case provider.Responses:
if v.MaxOutputTokens > limit {
fields["max_output_tokens"] = limit
}
case provider.Anthropic:
if v.MaxTokens <= limit {
return body
}
fields["max_tokens"] = limit
if t := v.Thinking; t != nil && t.Type == "enabled" && t.Budget >= limit {
if limit-1 >= 1024 {
fields["thinking"] = map[string]any{"type": "enabled", "budget_tokens": limit - 1}
} else {
// no budget fits under it (Anthropic's least is 1024)
fields["thinking"] = map[string]any{"type": "disabled"}
}
}
case provider.Gemini:
if n, ok := v.GenerationConfig["maxOutputTokens"].(float64); ok && int(n) > limit {
v.GenerationConfig["maxOutputTokens"] = limit
fields["generationConfig"] = v.GenerationConfig
}
}
if len(fields) == 0 {
return body
}
return withFields(body, fields)
}