Files
magpie/internal/gateway/limit.go
T
yetone e57e785633 gateway: a rewritten body is written back by marshalJSON, not json.Marshal (#3394)
withReasoningText runs on every replayed request to DeepSeek and the
like (#1104), and wrote the whole body back with json.Marshal twice:
once for the input list, once for the body around it. encoding/json
writes a json.RawMessage through its scanner, a call a byte, so a long
conversation was compacted twice a request. marshalJSON (marshalRaw,
#1532) writes the same bytes, checked by jsonCheck and copied, and
falls back to json.Marshal for any other value; TestMarshalRawIsEncodingJSON
holds the two equal. The same body rewrites in affinity.go,
anthropic.go, codex_backend.go and limit.go took json.Marshal of a
map[string]json.RawMessage too, and use marshalJSON now. Nothing a
body goes out as changes.

Run:
- Real DeepSeek account in a sandbox HOME, magpie serve on 3482, 12
  streamed /v1/responses requests of a synthetic 1.5MB conversation with
  Codex 0.162.0's real tools and a codex_cli_rs/0.162.1 User-Agent, CPU
  time from ps, two rounds each: b97e0aa2a 0.74s and 0.75s, this 0.67s and
  0.66s, about 62ms -> 55ms a request. All 48 answered 200.
- go test ./internal/gateway -count 1 -timeout 45m at this tree: ok
  (370s).
- No new test: the change is the encoder, and TestMarshalRawIsEncodingJSON
  already fails if marshalJSON's bytes differ from json.Marshal's.
- gofmt -l clean; GOOS=linux and windows go vet -tags nogui ./internal/gateway ok.
2026-10-25 00:59:10 +08:00

66 lines
2.0 KiB
Go

package gateway
import (
"encoding/json"
"regexp"
"strconv"
"strings"
)
// tooFewTokens reads a provider's floor on the reply's length from the 400
// it sends when a request asks for less ("max_tokens must be greater than
// 2"). Apps checking a model is up ask for a token or two, which most
// providers answer and some turn away. A > may come JSON-escaped, as
// \u003e: the error is read from the body magpie re-encoded for the agent,
// or a vendor encodes its own that way (#260: "Expected a value >= 16").
var tooFewTokens = regexp.MustCompile(`(?i)max_(?:completion_|output_)?tokens.{0,60}?(greater than|more than|larger than|at least|(?:>|\\u003e)=?)\s*(\d+)`)
// tokenFloor is the least a provider said it takes, or 0 when the error
// isn't about that.
func tokenFloor(msg []byte) int {
m := tooFewTokens.FindSubmatch(msg)
if m == nil {
return 0
}
n, err := strconv.Atoi(string(m[2]))
if err != nil || n < 0 || n > 1024 {
return 0
}
if sign := string(m[1]); strings.EqualFold(sign, "at least") || strings.HasSuffix(sign, "=") {
return n
}
return n + 1
}
// withTokenFloor raises the reply's length the request asks for to floor,
// wherever the request's protocol keeps it; false when it asked for that
// much already, so the error was about something else.
func withTokenFloor(body []byte, floor int) ([]byte, bool) {
var q map[string]json.RawMessage
if floor <= 0 || json.Unmarshal(body, &q) != nil {
return nil, false
}
raise := func(m map[string]json.RawMessage, key string) bool {
var n int
if json.Unmarshal(m[key], &n) != nil || n >= floor {
return false
}
m[key], _ = json.Marshal(floor)
return true
}
raised := false
for _, k := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} {
raised = raise(q, k) || raised
}
var gc map[string]json.RawMessage // Gemini's
if json.Unmarshal(q["generationConfig"], &gc) == nil && raise(gc, "maxOutputTokens") {
q["generationConfig"], _ = json.Marshal(gc)
raised = true
}
if !raised {
return nil, false
}
b, err := marshalJSON(q)
return b, err == nil
}