Files
magpie/internal/gateway/toolong_test.go
T
yetone cfcd6648fc gateway: Chinese that says the input is too long is an overflow, Chinese pace words a rate limit (#4420)
A group member answered 400 "内容太长了,请精简输入或开启新对话" once a
turn passed ~730K on a model it declares at 1M. tooLongRe's Chinese only
matched wordings that name 上下文, so the try was filed as a plain
failure that rested the member, and the group's other members were never
asked. Reported by MYCF711 (Discord, issue #4420).

tooLongRe gets a third line for Chinese that names what was sent (内容,
输入, 文本, 提示词/prompt, 问题, 对话, 消息) beside its length: "…太长/过长/
超长", "…超过/超出…长度/token/字数", "输入长度/token…超过", and
"字数太多/过多". Tied to: the reporter's vendor, z.ai's 1261 "Prompt 超长",
iFlytek Spark's 10907 "token数量超过上限。对话历史+问题的字数太多,需要精简
输入". Left out on purpose: bare "超出最大长度" (a field's length), bare
"token数量超过上限" (a day's allowance is said so too), "输出过长" (the
reply), and "请求体过大" (a 413 byte limit, already handled by status).

paceWords gets Chinese pace words (速率, 频繁, 频率, 限流, 并发, 每秒/
分钟/小时/天/日, 稍后再试/重试), so "内容太长,已达到速率限制" is a rate
limit, not a size. rateWords gains 过于频繁/速率 and quotaWords 频繁/速率,
so such a 400 is asked of the next account and such a 429 is failRate.

Tests:
- TestEveryVendorsOverflow: 8 Chinese rows (red on the old code, each).
- TestChineseNotTooLong (new): pace-with-size, a field's length, the
  reply's length, a day's token cap and plain errors aren't overflows; the
  pace 400 is retryable.
- TestChineseInputTooLongGoesToTheNextMember (new): two-member group, the
  reporter's literal words, raw and \u-escaped: member b answers, failOverflow,
  nobody rests (red on the old code: a 1, b 0, 400 to the agent).
- docs/subsystems/gateway-routing.md names the new wordings.

Run (mote, via mote-run, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok 500.9s
- go vet ./internal/gateway, GOOS=linux and GOOS=windows: clean; gofmt -l clean
- Broken by hand: old gateway.go/routing.go/fallback.go with the new
  tests: all three tests red (11 failures). paceWords alone reverted:
  TestChineseNotTooLong red on 4 pace messages and the retryable check.

Not tried: the reporter's real vendor (unknown which member it is), nor a
real z.ai or iFlytek account; the wordings come from their docs. Only
internal/gateway was run, not the whole repo; the change is inside that
package's classifiers.
2026-10-30 17:52:14 +08:00

173 lines
7.3 KiB
Go

package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A vendor's "too long" reaches the agent in its own API's words, so it
// compacts and retries: Claude Code on "prompt is too long", Codex and
// chat clients on context_length_exceeded.
func TestContextOverflowSaidTheClientsWay(t *testing.T) {
volc := "Volcengine: Input exceeds the context limit (1048568 tokens)"
for _, tc := range []struct {
proto provider.Protocol
status int
msg string
wantCode string
wantMsg string
}{
{provider.Anthropic, 400, volc, "", "prompt is too long: " + volc},
{provider.Chat, 400, volc, "context_length_exceeded", volc},
{provider.Responses, 413, volc, "context_length_exceeded", volc},
{provider.Responses, 400, "relay: This model's maximum context length is 131072 tokens. However, you requested 140000 tokens", "context_length_exceeded", ""},
{provider.Anthropic, 400, "a: prompt is too long: 210000 tokens > 200000 maximum", "", "a: prompt is too long: 210000 tokens > 200000 maximum"},
{provider.Chat, 400, "zhipu: 输入内容超过模型最大上下文长度", "context_length_exceeded", ""},
// not the conversation: left as the vendor said it
{provider.Chat, 400, "x: max_tokens is too large: 100000 exceeds the model's context", "", ""},
{provider.Chat, 400, "x: invalid tool schema", "", ""},
{provider.Chat, 502, "x: upstream exceeds context budget", "", ""},
} {
w := httptest.NewRecorder()
status := writeError(w, tc.proto, tc.status, tc.msg)
var body struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
Code any `json:"code"`
} `json:"error"`
}
json.Unmarshal(w.Body.Bytes(), &body)
code, _ := body.Error.Code.(string)
overflow := tc.wantCode != "" || strings.HasPrefix(tc.wantMsg, "prompt is too long") || strings.Contains(tc.wantMsg, ": prompt is too long")
switch {
case tc.proto == provider.Anthropic && tc.wantMsg != "" && body.Error.Message != tc.wantMsg,
tc.proto != provider.Anthropic && code != tc.wantCode,
overflow && (status != 400 || body.Error.Type != "invalid_request_error"),
!overflow && status != tc.status:
t.Errorf("%s %d %q: status %d body %s", tc.proto, tc.status, tc.msg, status, w.Body.String())
}
}
}
// Each vendor's way of saying the conversation is too long, as pi
// collected them (packages/ai/src/utils/overflow.ts), reaches the agent as
// context_length_exceeded, so it compacts; and none is taken for a used-up
// plan or asked of another account, which holds the conversation no
// better: Kimi's "exceeded model token limit" rested the account as out of
// quota, z.ai's model_context_window_exceeded went to every account in
// turn.
func TestEveryVendorsOverflow(t *testing.T) {
for _, tc := range []struct {
status int
msg string
}{
{400, "The input token count (1196265) exceeds the maximum number of tokens allowed (1048575)"},
{400, "This model's maximum prompt length is 131072 but the request contains 537812 tokens"},
{400, "Please reduce the length of the messages or completion"},
{400, "Input length 2000 exceeds the maximum allowed input length of 1000 tokens."},
{400, "The input (2000 tokens) is longer than the model's context length (1000 tokens)."},
{400, "the request exceeds the available context size, try increasing it"},
{400, "tokens to keep from the initial prompt is greater than the context length"},
{400, "prompt token count of 2000 exceeds the limit of 1000"},
{400, "invalid params, context window exceeds limit"},
{400, "Your request exceeded model token limit: 1000 (requested: 2000)"},
{400, "Prompt has 2000 tokens, but the configured context size is 1000 tokens"},
{400, `{"code":"1261","message":"Prompt too long"}`},
{400, `{"code":"1261","message":"Prompt exceeds max length"}`},
{400, "model_context_window_exceeded"},
{400, "prompt too long; exceeded max context length by 100 tokens"},
{400, "Range of input length should be [1, 98304]"},
{400, "token limit exceeded"},
// Chinese that names the input, not the context (#4420, MYCF711)
{400, "内容太长了,请精简输入或开启新对话"},
{400, `{"error":{"code":"1261","message":"Prompt 超长"}}`},
{400, "token数量超过上限。对话历史+问题的字数太多,需要精简输入"},
{400, "输入过长,请缩短后重试"},
{400, "输入长度超过限制"},
{400, "输入内容超过模型最大token数"},
{400, "提示词超出最大长度"},
{413, "请求内容过长"},
} {
if !tooLong(tc.status, tc.msg) {
t.Errorf("%q isn't taken for a conversation too long", tc.msg)
}
if retryable(tc.status, []byte(tc.msg)) {
t.Errorf("%q is asked of another account", tc.msg)
}
if f := failure(tc.status, []byte(tc.msg)); f != failOther {
t.Errorf("%q is a %s failure", tc.msg, f)
}
}
// a rate limit worded with tokens is still one
if tooLong(429, "Too many tokens, please wait before trying again.") {
t.Error("a rate limit taken for a conversation too long")
}
}
// A Chinese pace limit beside words of size, or a length that isn't the
// conversation's, isn't taken for a conversation too long (#4420): told
// so, the agent compacts for nothing, and a pace limit worded so would
// never be asked of the next account.
func TestChineseNotTooLong(t *testing.T) {
for _, msg := range []string{
"内容太长,已达到速率限制",
"请求过于频繁,输入内容过长的请求请稍后再试",
"输入token数超过每分钟限制",
"输入过长:已超过并发上限",
"每日token数量超过上限",
"token数量超过上限",
"名称超出最大长度",
"输出过长,请调小 max_tokens",
"文件名过长",
"参数错误",
"服务出现问题,请联系管理员",
"模型不存在",
} {
if tooLong(400, msg) {
t.Errorf("%q taken for a conversation too long", msg)
}
}
// the pace limit said with size still goes to the next account
if !retryable(400, []byte("内容太长,已达到速率限制")) {
t.Error("a pace limit worded with size isn't asked of the next account")
}
for _, msg := range []string{"请求过于频繁", "已达到速率限制"} {
if f := failure(429, []byte(msg)); f != failRate {
t.Errorf("429 %q is a %s failure", msg, f)
}
}
}
// A spent budget, like a used-up plan (pi's retry.ts lists both as not to
// be retried), goes to the next account at once rather than being asked
// again in place: "out of budget" was a rate limit, asked three times.
func TestOutOfBudgetIsntRetriedInPlace(t *testing.T) {
for _, tc := range []struct {
status int
msg string
}{
{429, "out of budget"},
{400, "Budget exceeded for this key"},
{429, `{"error":{"type":"GoUsageLimitError","message":"Monthly usage limit reached"}}`},
{429, `{"error":{"code":"subscription_sharing_usage_limit_exceeded"}}`},
} {
if !retryable(tc.status, []byte(tc.msg)) {
t.Errorf("%d %q isn't asked of the next account", tc.status, tc.msg)
}
if f := failure(tc.status, []byte(tc.msg)); f != failQuota {
t.Errorf("%d %q is a %s failure", tc.status, tc.msg, f)
}
if _, again := passing(tc.status, nil, []byte(tc.msg), 0); again {
t.Errorf("%d %q is asked again in place", tc.status, tc.msg)
}
}
if _, again := passing(429, nil, []byte("Rate limit reached for requests"), 0); !again {
t.Error("a rate limit isn't asked again")
}
}