From 39c1f96fc22b1ac187206e06eede7071ac0dfec6 Mon Sep 17 00:00:00 2001 From: Kaiyi Date: Thu, 5 Mar 2026 18:26:13 +0800 Subject: [PATCH] fix(embedded): classify model_context_window_exceeded as context overflow error --- ...embedded-helpers.isbillingerrormessage.test.ts | 15 +++++++++++++++ src/agents/pi-embedded-helpers/errors.ts | 3 +++ 2 files changed, 18 insertions(+) diff --git a/src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts b/src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts index c9d073ce8c9..8d9c678035a 100644 --- a/src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts +++ b/src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts @@ -269,6 +269,21 @@ describe("isContextOverflowError", () => { } }); + it("matches model_context_window_exceeded stop reason surfaced by pi-ai", () => { + // Anthropic API (and some OpenAI-compatible providers like ZhipuAI/GLM) return + // stop_reason: "model_context_window_exceeded" when the context window is hit. + // The pi-ai library surfaces this as "Unhandled stop reason: model_context_window_exceeded". + const samples = [ + "Unhandled stop reason: model_context_window_exceeded", + "model_context_window_exceeded", + "context_window_exceeded", + "Unhandled stop reason: context_window_exceeded", + ]; + for (const sample of samples) { + expect(isContextOverflowError(sample)).toBe(true); + } + }); + it("matches Chinese context overflow error messages from proxy providers", () => { const samples = [ "上下文过长", diff --git a/src/agents/pi-embedded-helpers/errors.ts b/src/agents/pi-embedded-helpers/errors.ts index 30112b74fb6..630071df451 100644 --- a/src/agents/pi-embedded-helpers/errors.ts +++ b/src/agents/pi-embedded-helpers/errors.ts @@ -105,6 +105,9 @@ export function isContextOverflowError(errorMessage?: string): boolean { (lower.includes("max_tokens") && lower.includes("exceed") && lower.includes("context")) || (lower.includes("input length") && lower.includes("exceed") && lower.includes("context")) || (lower.includes("413") && lower.includes("too large")) || + // Anthropic API and OpenAI-compatible providers (e.g. ZhipuAI/GLM) return this stop reason + // when the context window is exceeded. pi-ai surfaces it as "Unhandled stop reason: model_context_window_exceeded". + lower.includes("context_window_exceeded") || // Chinese proxy error messages for context overflow errorMessage.includes("上下文过长") || errorMessage.includes("上下文超出") ||