Files
magpie/internal/gateway/maxoutput.go
T
yetone b749cffbb1 gateway: a reply asked past what the window leaves is asked again for what it leaves, not failed as too long (molvqingtai, da34, Jeremy.Zhou on Discord)
DeepSeek counts the reply asked for (max_tokens) in its 1M window with
the prompt: "maximum context length is 1000000 tokens. However, you
requested N tokens (P in the messages, C in the completion)". Since
62020b9c2 (#2355) a client's max_completion_tokens reaches DeepSeek as
max_tokens, so a turn asking the model's whole 384K on a ~620K+
conversation was refused there and read as "too long for its model"
(molvqingtai: auto-deepseek-v4.1-flash, round robin, the official
member failing where WorkBuddy and OpenCode Go answered). Codex turns
are asked the model's own 393216 on Anthropic's API (#1792), and since
1a3b92688 (v0.1.1290) Claude Code beside a [1m] DeepSeek is told 1M
and compacts only near it, so both met the same refusal before they
compacted (da34: Codex "ran out of room"; Jeremy.Zhou: Claude Code).

replyLeft (maxoutput.go) reads the window and the prompt from that
refusal, in DeepSeek's/vLLM's words or Anthropic's ("input length and
`max_tokens` exceed context limit: P + C > W"), and the same account and
model are asked once more for W-P (withReplyCap: the request's own field
lowered, or max_tokens / max_output_tokens set where it named none).
Room under 8192 is left alone: the agent is told it overflowed, to
compact. The try is "room" in the Routing page ("reply asked past the
window left", zh/zh-TW/ja/de). DeepSeek's documented window stays 1M
(api-docs pricing: deepseek-flash 1M, max output 384K), as models.dev
and the catalog say, so no number changes.

Run:
- TestDeepSeekReplyFitsTheWindowLeft: deepseek preset on a fake chat
  API that refuses in DeepSeek's words when prompt+max_tokens > 1M;
  max_completion_tokens 393216, max_tokens 393216 and a Responses
  client each arrive as 393216 then 293216 and answer 200; 32000 is
  asked once; room under 8192 reaches the agent as the 400, asked once.
- TestAnthropicReplyFitsTheWindowLeft: Anthropic's wording; Claude
  Code's max_tokens 64000 -> 30000, Codex naming none -> 393216 -> 30000.
- TestReplyLeft: both wordings, vLLM's newer one, and errors with no
  room or no parts give 0.
- Broken by hand: the retry's condition off -> both tests FAIL with the
  vendor's 400; the cap not applied on the retry -> FAIL the same.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... clean.
- go test -timeout 45m ./... at 33dbdcc52 + this change: 64 packages ok,
  0 FAIL (load average 130-160). An earlier run before the Anthropic
  wording was added timed out in internal/agent (TestPortMovesEveryAgent
  at the 45m mark, load ~110), which this change doesn't touch; the
  second run passed it.
- GUI: i18n-keys, routing-*, panel-routing* in both engines and every
  language. Red here and on origin/main ab7ec8c65 alike: routing-bodies
  (#2559), routing-model-rest (#2115), routing-request-metrics WebKit
  (#2571), routing-keys-fold WebKit ja/de once (#2658).
- Not tried against the real DeepSeek API: the refusal's wording is
  DeepSeek's documented OpenAI-compatible one, not captured from the
  reporters.
2026-10-19 19:05:30 +08:00

188 lines
6.8 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 (
"bytes"
"encoding/json"
"regexp"
"strconv"
"github.com/tidwall/gjson"
"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)
}
// replyLeft reads, from a refusal that counts the reply asked for in the
// window (DeepSeek's and vLLM's "This model's maximum context length is
// 1000000 tokens. However, you requested 1100000 tokens (706784 in the
// messages, 393216 in the completion)"), the tokens the window has left
// for a reply after the prompt; 0 when the error isn't one of those, or
// the prompt alone fills the window.
func replyLeft(msg []byte) int {
window, prompt := 0, 0
if m := windowAndPrompt.FindSubmatch(msg); m != nil {
window, _ = strconv.Atoi(string(m[1]))
prompt, _ = strconv.Atoi(string(m[2]))
if m[2] == nil {
prompt, _ = strconv.Atoi(string(m[3]))
}
} else if m := inputPlusReply.FindSubmatch(msg); m != nil {
prompt, _ = strconv.Atoi(string(m[1]))
window, _ = strconv.Atoi(string(m[2]))
}
if window <= 0 || prompt <= 0 || prompt >= window {
return 0
}
return window - prompt
}
// windowAndPrompt matches the window and the prompt's part of a refusal
// that adds the reply's allowance to the prompt: "(N in the messages, M in
// the completion)", or vLLM's newer "your prompt contains at least N input
// tokens".
var windowAndPrompt = regexp.MustCompile(`(?is)maximum context length is (\d+) tokens.{0,200}?(?:\((\d+) in the messages, \d+ in the completion\)|your prompt contains at least (\d+) input tokens)`)
// inputPlusReply is Anthropic's words for the same, which an endpoint
// speaking its API may answer with: "input length and `max_tokens` exceed
// context limit: 197202 + 21333 > 200000".
var inputPlusReply = regexp.MustCompile(`(?i)input length and .{0,3}max_tokens.{0,3} exceed context limit:\s*(\d+)\s*\+\s*\d+\s*>\s*(\d+)`)
// leastReplyLeft is the least room left for a reply that is worth asking
// for: less, and the conversation needs compacting, which the refusal
// tells the agent as it is (DeepSeek's own default reply is 8K).
const leastReplyLeft = 8192
// withReplyCap is body asking for a reply of at most limit tokens, in
// proto's words, whether or not it named a limit before: a request that
// named none was given the vendor's own, which was too large. false when
// it asked for no more already, or proto keeps no such field magpie sets.
func withReplyCap(proto provider.Protocol, body []byte, limit int) ([]byte, bool) {
if limit <= 0 {
return nil, false
}
out := withMaxOutput(proto, body, limit)
if !bytes.Equal(out, body) {
return out, true
}
var key string
switch proto {
case provider.Chat:
if gjson.GetBytes(body, "max_tokens").Exists() || gjson.GetBytes(body, "max_completion_tokens").Exists() {
return nil, false
}
key = "max_tokens"
case provider.Responses:
if gjson.GetBytes(body, "max_output_tokens").Exists() {
return nil, false
}
key = "max_output_tokens"
default:
// Anthropic's always names one; Gemini's is lowered above
return nil, false
}
return withFields(body, map[string]any{key: limit}), true
}