From 40812f1d2bd2b50f9ba1dba8974ecf8d104c65ab Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 26 Sep 2026 01:26:23 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20vendor=20saying=20the=20conversa?= =?UTF-8?q?tion=20is=20too=20long=20is=20said=20the=20client's=20way,=20so?= =?UTF-8?q?=20the=20agent=20compacts=20and=20retries=20=E2=80=94=20Volceng?= =?UTF-8?q?ine's=20"Input=20exceeds=20the=20context=20limit=20(1048568=20t?= =?UTF-8?q?okens)"=20reached=20Claude=20Code=20and=20Codex=20as=20a=20plai?= =?UTF-8?q?n=20error=20they=20stop=20on;=20a=204xx=20that=20says=20the=20i?= =?UTF-8?q?nput=20is=20past=20the=20model's=20context=20(context=5Flength?= =?UTF-8?q?=5Fexceeded,=20maximum=20context=20length,=20prompt=20is=20too?= =?UTF-8?q?=20long,=20exceeds=20the=20context=20limit,=20=E8=B6=85?= =?UTF-8?q?=E8=BF=87=E4=B8=8A=E4=B8=8B=E6=96=87=E2=80=A6)=20now=20answers?= =?UTF-8?q?=20400=20with=20Anthropic's=20"prompt=20is=20too=20long:=20?= =?UTF-8?q?=E2=80=A6"=20on=20/v1/messages=20and=20code=20context=5Flength?= =?UTF-8?q?=5Fexceeded=20on=20chat=20and=20Responses;=20one=20about=20max?= =?UTF-8?q?=5Ftokens=20is=20left=20alone?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/gateway.go | 32 ++++++++++++++++++- internal/gateway/toolong_test.go | 55 ++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/toolong_test.go diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 092521c5e..2b5639eeb 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -14,6 +14,7 @@ import ( "net" "net/http" "os" + "regexp" "slices" "sort" "strings" @@ -1112,6 +1113,15 @@ func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg case status == 529: typ = "overloaded_error" } + var code any + if tooLong(status, msg) { + // said the way the client's own API says it, so the agent + // compacts the conversation and tries again rather than stopping + status, typ, code = 400, "invalid_request_error", "context_length_exceeded" + if proto == provider.Anthropic && !strings.Contains(strings.ToLower(msg), "prompt is too long") { + msg = "prompt is too long: " + msg + } + } var v any switch proto { case provider.Anthropic: @@ -1124,8 +1134,28 @@ func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg } v = map[string]any{"error": map[string]any{"code": status, "message": msg, "status": st}} default: - v = map[string]any{"error": map[string]any{"message": msg, "type": typ, "code": nil, "param": nil}} + v = map[string]any{"error": map[string]any{"message": msg, "type": typ, "code": code, "param": nil}} } writeJSON(w, status, v) return status } + +// tooLongRe matches how vendors say a request is more than the model's +// context holds: OpenAI's context_length_exceeded, Anthropic's "prompt is +// too long", Volcengine's "Input exceeds the context limit", "maximum +// context length", "context window"… +var tooLongRe = regexp.MustCompile(`(?i)context_length_exceeded|prompt is too long|input is too long|(exceeds?|exceeded|over|beyond)( the)?( model'?s?)?( maximum)? context|context (length|limit|window) (exceeded|is exceeded)|maximum context length|too many (input |prompt )?tokens|上下文(长度)?(超|过长)|超(过|出)(了)?(模型)?(的)?(最大)?上下文`) + +// tooLong is whether a vendor's error says the conversation no longer +// fits. One about max_tokens is left alone: the reply's allowance, not +// the conversation, is what is too big there, and compacting won't help. +func tooLong(status int, msg string) bool { + if status < 400 || status >= 500 { + return false + } + m := strings.ToLower(msg) + if strings.Contains(m, "max_tokens") || strings.Contains(m, "max_output_tokens") || strings.Contains(m, "max_completion_tokens") { + return false + } + return tooLongRe.MatchString(msg) +} diff --git a/internal/gateway/toolong_test.go b/internal/gateway/toolong_test.go new file mode 100644 index 000000000..c583be25d --- /dev/null +++ b/internal/gateway/toolong_test.go @@ -0,0 +1,55 @@ +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()) + } + } +}