gateway: a chat request to DeepSeek that asks max_completion_tokens reaches it as max_tokens, not ignored at DeepSeek's 8K default (#2355, h4rk8s)

DeepSeek's chat API reads the reply length from max_tokens only (its
create-chat-completion docs list no max_completion_tokens). A Chat client
that asks OpenAI's way, as DSH's pi-ai does for a custom provider at
magpie's address, had the field passed through as it came, so DeepSeek
fell back to its default: the reporter's non-thinking turn asked 393216
and stopped at length after 8192.

deepseekTokenField (deepseek_schema.go), in forwardOnce beside
deepseekToolPatterns, renames the top-level key in place when the
provider is the deepseek preset or api.deepseek.com and the wire is Chat.
Only the key's bytes change. A request that names max_tokens too goes as
it is, since DeepSeek reads that one. Other vendors' chat APIs are not
touched (OpenAI's and Azure's want max_completion_tokens; Bedrock/Azure
keep asCompletionTokens). A request translated from another protocol
already went out as max_tokens (buildChat), so passthrough was the only
path that missed it.

Tested: TestDeepSeekChatGetsMaxTokens, through New().Handler() with the
deepseek preset on a fake upstream: max_completion_tokens (also with
spaces around the colon) arrives as max_tokens; max_tokens alone and both
fields go as sent; a custom provider gets max_completion_tokens
unchanged; a message whose text says "max_completion_tokens" keeps it.
Broken by hand: the forwardOnce call removed -> FAIL "upstream got
{...max_completion_tokens":393216...}"; the DeepSeek scope dropped -> FAIL
on relay/m; the max_tokens-present guard dropped -> FAIL on the both-
fields case. go test -run 'DeepSeek|MaxOutput|Tokens|Bedrock|Azure|Chat'
./internal/gateway ok; gofmt clean; vet darwin/linux/windows on gateway
ok. Not tried against the real DeepSeek API: the owner's key answers 402
Insufficient Balance to both fields.

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:03 +08:00
parent 0889fdb844
commit 62020b9c26
3 changed files with 101 additions and 0 deletions
+31
View File
@@ -165,3 +165,34 @@ func unicodeNullEscape(pattern string) string {
}
return out.String()
}
// deepseekTokenField names a chat request's reply length max_tokens, the
// field DeepSeek's chat API reads: it has no max_completion_tokens and
// ignores one, so a client that asks OpenAI's way (DSH's pi-ai with a
// custom provider) got DeepSeek's default, 8K without thinking (#2355).
// Only the key is renamed, in place, so the rest of the body keeps its
// bytes. A request that names max_tokens too goes as it is, since
// DeepSeek reads that one. Another vendor's chat API is left alone:
// OpenAI's and Azure's want max_completion_tokens.
func deepseekTokenField(p provider.Provider, to provider.Protocol, body []byte) []byte {
if to != provider.Chat || p.Preset != "deepseek" && provider.HostOf(p.Base(to)) != "api.deepseek.com" {
return body
}
if !bytes.Contains(body, []byte(`"max_completion_tokens"`)) || gjson.GetBytes(body, "max_tokens").Exists() {
return body
}
v := gjson.GetBytes(body, "max_completion_tokens")
if !v.Exists() || v.Index <= 0 {
return body
}
// the key is the last string before its value: only a colon and
// spaces lie between them
key := bytes.LastIndex(body[:v.Index], []byte(`"max_completion_tokens"`))
if key < 0 || strings.Trim(string(body[key+len(`"max_completion_tokens"`):v.Index]), " \t\r\n:") != "" {
return body
}
out := make([]byte, 0, len(body))
out = append(out, body[:key]...)
out = append(out, `"max_tokens"`...)
return append(out, body[key+len(`"max_completion_tokens"`):]...)
}
+69
View File
@@ -0,0 +1,69 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A chat client that asks DeepSeek for its reply length OpenAI's way
// (max_completion_tokens, as DSH's pi-ai does for a custom provider) gets
// it as max_tokens, the field DeepSeek reads: before, DeepSeek got the
// field it ignores and answered with its default 8K (#2355, h4rk8s).
// Another vendor's chat API gets the request as the client sent it.
func TestDeepSeekChatGetsMaxTokens(t *testing.T) {
fresh(t)
f := &fake{reply: sse(
`data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"}}]}`,
`data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
`data: [DONE]`,
)}
up := httptest.NewServer(f)
defer up.Close()
p, err := provider.FromPreset("deepseek")
if err != nil {
t.Fatal(err)
}
p.Key = "fixture-key"
p.Chat = up.URL + "/v1"
p.Models = []string{"deepseek-flash"}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
other := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: up.URL + "/v1", Models: []string{"m"}}
if err := provider.Save(other); err != nil {
t.Fatal(err)
}
// a message that names the field keeps its text
said := `{"role":"user","content":"what is \"max_completion_tokens\"?"}`
for _, c := range []struct {
model, fields string
maxTokens, maxCompl any
}{
{"deepseek/deepseek-flash", `"max_completion_tokens":393216`, float64(393216), nil},
{"deepseek/deepseek-flash", `"max_completion_tokens" : 5`, float64(5), nil},
{"deepseek/deepseek-flash", `"max_tokens":5`, float64(5), nil},
// both named: DeepSeek reads max_tokens, which goes as it is
{"deepseek/deepseek-flash", `"max_tokens":7,"max_completion_tokens":5`, float64(7), float64(5)},
{"relay/m", `"max_completion_tokens":5`, nil, float64(5)},
} {
body := `{"model":"` + c.model + `","stream":true,` + c.fields + `,"messages":[` + said + `]}`
code, reply := post(t, "/v1/chat/completions", body)
if code != 200 {
t.Fatalf("%s: HTTP %d: %s", c.fields, code, reply)
}
var sent map[string]any
if err := json.Unmarshal(f.got, &sent); err != nil {
t.Fatal(err)
}
if sent["max_tokens"] != c.maxTokens || sent["max_completion_tokens"] != c.maxCompl {
t.Fatalf("%s %s: upstream got %s", c.model, c.fields, f.got)
}
if !strings.Contains(string(f.got), `what is \"max_completion_tokens\"?`) {
t.Fatalf("%s: message text changed: %s", c.fields, f.got)
}
}
}
+1
View File
@@ -3576,6 +3576,7 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
ctx = s.metered(p.Via(ctx), p, "")
body = deepseekToolPatterns(p, to, body)
body = grokToolPatterns(p, to, body)
body = deepseekTokenField(p, to, body)
body = toolOneOfAsAnyOf(p, to, body)
body = kimiToolEnumTypes(p, to, body)
body = kimiLockedSampling(p, to, body)