Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(eval): stop retrying context overflow errors (#13930)

Tobias Wochingerb0481b4ae117
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index eb87f9f47b..24a0e5d0fd 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -12,6 +12,7 @@ import {
SystemMessage,
ToolMessage,
} from "@langchain/core/messages";
+import { ContextOverflowError } from "@langchain/core/errors";
import {
BytesOutputParser,
StringOutputParser,
@@ -74,6 +75,7 @@ const NON_RETRYABLE_LLM_ERROR_PATTERNS = [
"Unterminated string in JSON at position",
"TypeError",
"reached the end of its life",
+ "prompt is too long",
// secureLlmFetch validation failures: synchronous, status-less errors that
// would otherwise default to 500 + retryable and burn the eval-retry budget
// on permanent config or redirect-target failures.
@@ -669,12 +671,7 @@ export async function fetchLLMCompletion(
return completion;
} catch (e) {
- const responseStatusCode =
- (e as any)?.response?.status ??
- (e as any)?.status ??
- // Bedrock errors have status code in $metadata.httpStatusCode
- (e as any)?.$metadata?.httpStatusCode ??
- 500;
+ const responseStatusCode = getErrorResponseStatusCode(e) ?? 500;
const rawMessage = e instanceof Error ? e.message : String(e);
// Anthropic/OpenAI/Azure SDKs wrap synchronous fetch errors as
// `APIConnectionError { message: "Connection error.", cause: original }`,
@@ -695,7 +692,9 @@ export async function fetchLLMCompletion(
// - Non-retryable patterns: not retryable
let isRetryable = false;
- if (
+ if (ContextOverflowError.isInstance(e)) {
+ isRetryable = false;
+ } else if (
e instanceof Error &&
(e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
) {
@@ -816,28 +815,57 @@ function processOpenAIBaseURL(params: {
return url.replace("{model}", modelName);
}
-function findNonRetryableCauseMessage(error: unknown): string | undefined {
+// Walks an error and its `.cause` chain (cycle-safe), yielding each link.
+function* walkCauseChain(error: unknown): Generator<unknown> {
const visited = new Set<unknown>();
for (
let current: unknown = error;
- current;
+ current && !visited.has(current);
current = (current as any).cause
) {
- if (visited.has(current)) break;
visited.add(current);
+ yield current;
+ }
+}
+
+function findNonRetryableCauseMessage(error: unknown): string | undefined {
+ for (const current of walkCauseChain(error)) {
if (!(current instanceof Error)) continue;
const message = extractCleanErrorMessage(current.message);
- if (
- NON_RETRYABLE_LLM_ERROR_PATTERNS.some((pattern) =>
- message.includes(pattern),
- )
- ) {
+ if (NON_RETRYABLE_LLM_ERROR_PATTERNS.some((p) => message.includes(p))) {
return message;
}
}
return undefined;
}
+function getErrorResponseStatusCode(error: unknown): number | undefined {
+ for (const current of walkCauseChain(error)) {
+ if (!current || typeof current !== "object") continue;
+ const errorLike = current as any;
+ const statusCode = [
+ errorLike.response?.status,
+ errorLike.status,
+ errorLike.statusCode,
+ // Bedrock errors have status code in $metadata.httpStatusCode.
+ errorLike.$metadata?.httpStatusCode,
+ ]
+ .map(toHttpStatusCode)
+ .find((code) => code !== undefined);
+ if (statusCode !== undefined) return statusCode;
+ }
+ return undefined;
+}
+
+function toHttpStatusCode(value: unknown): number | undefined {
+ return typeof value === "number" &&
+ Number.isInteger(value) &&
+ value >= 100 &&
+ value <= 599
+ ? value
+ : undefined;
+}
+
function extractCleanErrorMessage(rawMessage: string): string {
// Try to parse JSON error format (common in Google/Vertex AI errors)
// Example: '[{"error":{"code":404,"message":"Model not found..."}}]'
diff --git a/worker/src/__tests__/fetchLLMCompletionErrors.test.ts b/worker/src/__tests__/fetchLLMCompletionErrors.test.ts
new file mode 100644
index 0000000000..4be994d8ba
--- /dev/null
+++ b/worker/src/__tests__/fetchLLMCompletionErrors.test.ts
@@ -0,0 +1,147 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const anthropicInvokeMock = vi.fn();
+const chatAnthropicConstructorMock = vi.fn().mockImplementation(function () {
+ return {
+ invoke: anthropicInvokeMock,
+ pipe: vi.fn().mockReturnValue({
+ invoke: anthropicInvokeMock,
+ }),
+ withStructuredOutput: vi.fn().mockReturnValue({
+ invoke: anthropicInvokeMock,
+ }),
+ };
+});
+
+process.env.CLICKHOUSE_URL ??= "http://localhost:8123";
+process.env.CLICKHOUSE_USER ??= "default";
+process.env.CLICKHOUSE_PASSWORD ??= "password";
+process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";
+process.env.ENCRYPTION_KEY ??=
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+
+class MockLLMCompletionError extends Error {
+ responseStatusCode: number;
+ isRetryable: boolean;
+ blockReason: null;
+
+ constructor(params: {
+ message: string;
+ responseStatusCode?: number;
+ isRetryable?: boolean;
+ }) {
+ super(params.message);
+ this.name = "LLMCompletionError";
+ this.responseStatusCode = params.responseStatusCode ?? 500;
+ this.isRetryable = params.isRetryable ?? false;
+ this.blockReason = null;
+ }
+
+ shouldBlockConfig() {
+ return false;
+ }
+
+ getEvaluatorBlockReason() {
+ return null;
+ }
+}
+
+describe("fetchLLMCompletion provider error classification", () => {
+ let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
+ let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
+
+ beforeEach(async () => {
+ anthropicInvokeMock.mockReset();
+ chatAnthropicConstructorMock.mockClear();
+ vi.resetModules();
+
+ vi.doMock(
+ "../../../packages/shared/node_modules/@langchain/anthropic",
+ () => ({
+ ChatAnthropic: chatAnthropicConstructorMock,
+ }),
+ );
+ vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
+ LLMCompletionError: MockLLMCompletionError,
+ }));
+
+ ({ encrypt } = await import("../../../packages/shared/src/encryption"));
+ ({ fetchLLMCompletion } =
+ await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
+ });
+
+ it("treats wrapped Anthropic context overflow errors as non-retryable", async () => {
+ const { ContextOverflowError } =
+ await import("../../../packages/shared/node_modules/@langchain/core/errors");
+ const cause = new Error(
+ '400 {"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long: 202089 tokens > 200000 maximum"},"request_id":"req_123"}',
+ );
+ (cause as Error & { status: number }).status = 400;
+
+ const contextOverflowError = ContextOverflowError.fromError(cause);
+
+ anthropicInvokeMock.mockRejectedValue(contextOverflowError);
+
+ await expect(
+ fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "Score this observation.",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "anthropic",
+ adapter: "anthropic",
+ model: "claude-haiku-4-5-20251001",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("anthropic-api-key"),
+ },
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ });
+
+ it("preserves provider status codes from wrapped error causes", async () => {
+ const cause = new Error("Provider authentication failed");
+ (cause as Error & { status: number }).status = 401;
+ const wrappedError = new Error("Connection error.", { cause });
+
+ anthropicInvokeMock.mockRejectedValue(wrappedError);
+
+ await expect(
+ fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "Score this observation.",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "anthropic",
+ adapter: "anthropic",
+ model: "claude-haiku-4-5-20251001",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("anthropic-api-key"),
+ },
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ responseStatusCode: 401,
+ isRetryable: false,
+ });
+ });
+});