Skip to content

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

chore(evals): graceful failure in case of timeouts of LLM providers (#8752)

marliessophiefe6c647c2b56
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 3ca4e7a094..8c5daf7c1c 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -217,6 +217,12 @@ const EnvSchema = z.object({
.int()
.positive()
.default(600_000), // 10 minutes
+
+ LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS: z.coerce
+ .number()
+ .int()
+ .positive()
+ .default(120_000), // 2 minutes
});
export const env: z.infer<typeof EnvSchema> =
diff --git a/packages/shared/src/errors/utils/constants.ts b/packages/shared/src/errors/utils/constants.ts
index 83fddb7f18..e0553c025e 100644
--- a/packages/shared/src/errors/utils/constants.ts
+++ b/packages/shared/src/errors/utils/constants.ts
@@ -7,4 +7,5 @@ export const QUEUE_ERROR_MESSAGES = {
TOO_LOW_MAX_TOKENS_ERROR: "Error: Unterminated string in JSON at position",
OUTPUT_TOKENS_TOO_LONG_ERROR:
"Could not parse response content as the length limit was reached",
+ TIMEOUT_ERROR: "Request timed out",
};
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 07ef45649f..3a4611bfe2 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -221,6 +221,7 @@ export async function fetchLLMCompletion(
// Common proxy configuration for all adapters
const proxyUrl = env.HTTPS_PROXY;
const proxyAgent = proxyUrl ? new HttpsProxyAgent(proxyUrl) : undefined;
+ const timeoutMs = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;
let chatModel:
| ChatOpenAI
@@ -239,7 +240,7 @@ export async function fetchLLMCompletion(
callbacks: finalCallbacks,
clientOptions: {
maxRetries,
- timeout: 1000 * 60 * 2, // 2 minutes timeout
+ timeout: timeoutMs,
...(proxyAgent && { httpAgent: proxyAgent }),
},
invocationKwargs: modelParams.providerOptions,
@@ -260,7 +261,7 @@ export async function fetchLLMCompletion(
...(proxyAgent && { httpAgent: proxyAgent }),
},
modelKwargs: modelParams.providerOptions,
- timeout: 1000 * 60 * 2, // 2 minutes timeout
+ timeout: timeoutMs,
});
} else if (modelParams.adapter === LLMAdapter.Azure) {
chatModel = new AzureChatOpenAI({
@@ -273,7 +274,7 @@ export async function fetchLLMCompletion(
topP: modelParams.top_p,
callbacks: finalCallbacks,
maxRetries,
- timeout: 1000 * 60 * 2, // 2 minutes timeout
+ timeout: timeoutMs,
configuration: {
defaultHeaders: extraHeaders,
...(proxyAgent && { httpAgent: proxyAgent }),
@@ -297,7 +298,7 @@ export async function fetchLLMCompletion(
topP: modelParams.top_p,
callbacks: finalCallbacks,
maxRetries,
- timeout: 1000 * 60 * 2, // 2 minutes timeout
+ timeout: timeoutMs,
additionalModelRequestFields: modelParams.providerOptions as any,
});
} else if (modelParams.adapter === LLMAdapter.VertexAI) {
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 304b737fa7..d771840db6 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -40,6 +40,21 @@ import {
extractVariablesFromTracingData,
} from "../features/evaluation/evalService";
import { requiresDatabaseLookup } from "../features/evaluation/traceFilterUtils";
+
+// Mock fetchLLMCompletion module with default passthrough behavior
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ fetchLLMCompletion: vi
+ .fn()
+ .mockImplementation(actual.fetchLLMCompletion as any),
+ };
+});
+
+// Import the mocked function
+import { fetchLLMCompletion } from "@langfuse/shared/src/server";
+
let OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const hasActiveKey = Boolean(OPENAI_API_KEY);
if (!hasActiveKey) {
@@ -1715,6 +1730,121 @@ describe("eval service tests", () => {
expect(jobs[0].start_time).not.toBeNull();
expect(jobs[0].end_time).not.toBeNull();
}, 20_000);
+
+ test("handles LLM timeout gracefully", async () => {
+ // Set up the mock to simulate timeout for this test only
+ const mockFetchLLMCompletion = vi.mocked(fetchLLMCompletion);
+ mockFetchLLMCompletion.mockRejectedValueOnce(
+ new ApiError("Request timeout after 120000ms", 500),
+ );
+
+ const traceId = randomUUID();
+
+ await upsertTrace({
+ id: traceId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ user_id: "a",
+ input: JSON.stringify({ input: "This is a great prompt" }),
+ output: JSON.stringify({ output: "This is a great response" }),
+ timestamp: convertDateToClickhouseDateTime(new Date()),
+ created_at: convertDateToClickhouseDateTime(new Date()),
+ updated_at: convertDateToClickhouseDateTime(new Date()),
+ });
+
+ const templateId = randomUUID();
+ await kyselyPrisma.$kysely
+ .insertInto("eval_templates")
+ .values({
+ id: templateId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "test-template",
+ version: 1,
+ prompt: "Please evaluate toxicity {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ provider: "openai",
+ model_params: {},
+ output_schema: {
+ reasoning: "Please explain your reasoning",
+ score: "Please provide a score between 0 and 1",
+ },
+ })
+ .executeTakeFirst();
+
+ const jobConfiguration = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: [
+ {
+ type: "string",
+ value: "a",
+ column: "User ID",
+ operator: "contains",
+ },
+ ],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ evalTemplateId: templateId,
+ },
+ });
+
+ const jobExecutionId = randomUUID();
+
+ await kyselyPrisma.$kysely
+ .insertInto("job_executions")
+ .values({
+ id: jobExecutionId,
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ job_configuration_id: jobConfiguration.id,
+ status: sql`'PENDING'::"JobExecutionStatus"`,
+ start_time: new Date(),
+ job_input_trace_id: traceId,
+ })
+ .execute();
+
+ await kyselyPrisma.$kysely
+ .insertInto("llm_api_keys")
+ .values({
+ id: randomUUID(),
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ secret_key: encrypt(String(OPENAI_API_KEY)),
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ custom_models: [],
+ display_secret_key: "123456",
+ })
+ .execute();
+
+ const payload = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ jobExecutionId: jobExecutionId,
+ delay: 1000,
+ };
+
+ // Test that timeout error is thrown
+ await expect(evaluate({ event: payload })).rejects.toThrowError(
+ /timeout/i,
+ );
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ expect(jobs[0].project_id).toBe("7a88fb47-b4e2-43b8-a06c-a5ce950dc53a");
+ expect(jobs[0].job_input_trace_id).toBe(traceId);
+ // Job should still be PENDING because the error will be handled by the queue processor
+ expect(jobs[0].status.toString()).toBe("PENDING");
+
+ // Clean up the mock after this test
+ mockFetchLLMCompletion.mockReset();
+ }, 15_000);
});
describe("test variable extraction", () => {
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 7bafe2fa0d..25b55788ba 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -19,6 +19,32 @@ import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
import { delayInMs } from "./utils/delays";
import { handleRetryableError } from "../features/utils";
+function isExpectedError(error: unknown): boolean {
+ return (
+ error instanceof LangfuseNotFoundError ||
+ (error instanceof BaseError &&
+ error.message.includes(
+ QUEUE_ERROR_MESSAGES.OUTPUT_TOKENS_TOO_LONG_ERROR,
+ )) || // output tokens too long
+ (error instanceof BaseError &&
+ error.message.includes(QUEUE_ERROR_MESSAGES.API_KEY_ERROR)) || // api key not provided
+ (error instanceof BaseError &&
+ error.message.includes(QUEUE_ERROR_MESSAGES.NO_DEFAULT_MODEL_ERROR)) || // api key not provided
+ (error instanceof ApiError &&
+ error.httpCode >= 400 &&
+ error.httpCode < 500) || // do not error and retry on 4xx errors. They are visible to the user in the UI but do not alert us.
+ (error instanceof ApiError && error.message.includes("TypeError")) || // Zod parsing the response failed. User should update prompt to consistently return expected output structure.
+ (error instanceof ApiError &&
+ error.message.includes(QUEUE_ERROR_MESSAGES.TOO_LOW_MAX_TOKENS_ERROR)) || // When evaluator model is configured with too low max_tokens, the structured output response is invalid JSON
+ (error instanceof ApiError &&
+ error.message.includes(QUEUE_ERROR_MESSAGES.INVALID_JSON_ERROR)) || // When evaluator model is not consistently returning valid JSON on structured output calls
+ (error instanceof BaseError &&
+ error.message.includes(QUEUE_ERROR_MESSAGES.MAPPED_DATA_ERROR)) || // Trace not found.
+ (error instanceof ApiError &&
+ error.message.toLowerCase().includes(QUEUE_ERROR_MESSAGES.TIMEOUT_ERROR)) // LLM provider timeout - graceful failure
+ );
+}
+
export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
) => {
@@ -115,25 +141,7 @@ export const evalJobExecutorQueueProcessor = async (
.execute();
// do not log expected errors (api failures + missing api keys not provided by the user)
- if (
- e instanceof LangfuseNotFoundError ||
- (e instanceof BaseError &&
- e.message.includes(
- QUEUE_ERROR_MESSAGES.OUTPUT_TOKENS_TOO_LONG_ERROR,
- )) || // output tokens too long
- (e instanceof BaseError &&
- e.message.includes(QUEUE_ERROR_MESSAGES.API_KEY_ERROR)) || // api key not provided
- (e instanceof BaseError &&
- e.message.includes(QUEUE_ERROR_MESSAGES.NO_DEFAULT_MODEL_ERROR)) || // api key not provided
- (e instanceof ApiError && e.httpCode >= 400 && e.httpCode < 500) || // do not error and retry on 4xx errors. They are visible to the user in the UI but do not alert us.
- (e instanceof ApiError && e.message.includes("TypeError")) || // Zod parsing the response failed. User should update prompt to consistently return expected output structure.
- (e instanceof ApiError &&
- e.message.includes(QUEUE_ERROR_MESSAGES.TOO_LOW_MAX_TOKENS_ERROR)) || // When evaluator model is configured with too low max_tokens, the structured output response is invalid JSON
- (e instanceof ApiError &&
- e.message.includes(QUEUE_ERROR_MESSAGES.INVALID_JSON_ERROR)) || // When evaluator model is not consistently returning valid JSON on structured output calls
- (e instanceof BaseError &&
- e.message.includes(QUEUE_ERROR_MESSAGES.MAPPED_DATA_ERROR)) // Trace not found.
- ) {
+ if (isExpectedError(e)) {
return;
}