Skip to content

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

chore(experiments): enhance error handling in LLM call and implement retry logic for experiment creation jobs (#7632)

marliessophiea42cf72d2ac2
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 169b172bce..374993d184 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -30,7 +30,7 @@ import {
test,
vi,
} from "vitest";
-import { compileHandlebarString } from "../features/utilities";
+import { compileHandlebarString } from "../features/utils/utilities";
import { OpenAIServer } from "./network";
import { pruneDatabase } from "./utils";
import {
@@ -38,10 +38,7 @@ import {
evaluate,
extractVariablesFromTracingData,
} from "../features/evaluation/evalService";
-import {
- requiresDatabaseLookup,
- requiresObservationData,
-} from "../features/evaluation/traceFilterUtils";
+import { requiresDatabaseLookup } from "../features/evaluation/traceFilterUtils";
let OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const hasActiveKey = Boolean(OPENAI_API_KEY);
if (!hasActiveKey) {
diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.ts
index a1729669a8..f18210e03f 100644
--- a/worker/src/__tests__/experimentsService.test.ts
+++ b/worker/src/__tests__/experimentsService.test.ts
@@ -5,10 +5,10 @@ import { randomUUID } from "crypto";
import { pruneDatabase } from "./utils";
import { LLMAdapter } from "@langfuse/shared";
import { encrypt } from "@langfuse/shared/encryption";
-import { callLLM } from "../features/utilities";
+import { callLLM } from "../features/utils/utilities";
import { PROMPT_EXPERIMENT_ENVIRONMENT } from "@langfuse/shared/src/server";
-vi.mock("../features/utilities", () => ({
+vi.mock("../features/utils/utilities", () => ({
callLLM: vi.fn().mockResolvedValue({ id: "test-id" }),
compileHandlebarString: vi.fn().mockImplementation((str, context) => {
// Simple mock that replaces handlebars variables with their values
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 7d544bf52c..9f382cced7 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -53,10 +53,7 @@ import {
} from "@langfuse/shared";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
import { backOff } from "exponential-backoff";
-import {
- callStructuredLLM,
- compileHandlebarString,
-} from "../../features/utilities";
+import { callStructuredLLM, compileHandlebarString } from "../utils";
import { env } from "../../env";
import { JSONPath } from "jsonpath-plus";
diff --git a/worker/src/features/experiments/experimentService.ts b/worker/src/features/experiments/experimentService.ts
index f4686adbda..4b9e6c4144 100644
--- a/worker/src/features/experiments/experimentService.ts
+++ b/worker/src/features/experiments/experimentService.ts
@@ -30,11 +30,10 @@ import {
stringifyValue,
} from "@langfuse/shared";
import { backOff } from "exponential-backoff";
-import { callLLM } from "../../features/utilities";
+import { callLLM, compileHandlebarString } from "../../features/utils";
import { QueueJobs, redis } from "@langfuse/shared/src/server";
import { randomUUID } from "node:crypto";
import { v4 } from "uuid";
-import { compileHandlebarString } from "../../features/utilities";
import { DatasetStatus } from "../../../../packages/shared/dist/prisma/generated/types";
const isValidPrismaJsonObject = (
diff --git a/worker/src/features/utils/index.ts b/worker/src/features/utils/index.ts
new file mode 100644
index 0000000000..5d1926aa63
--- /dev/null
+++ b/worker/src/features/utils/index.ts
@@ -0,0 +1,2 @@
+export * from "./utilities";
+export * from "./retry-handler";
diff --git a/worker/src/features/utils/retry-handler.ts b/worker/src/features/utils/retry-handler.ts
new file mode 100644
index 0000000000..fa2fbb47c7
--- /dev/null
+++ b/worker/src/features/utils/retry-handler.ts
@@ -0,0 +1,94 @@
+import { ApiError } from "@langfuse/shared";
+import { logger, recordIncrement } from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+import { kyselyPrisma } from "@langfuse/shared/src/db";
+
+const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
+
+/**
+ * Configuration for retry handling with rate limiting and age checks
+ */
+interface RetryConfig {
+ /** Database table to check age against */
+ table: "dataset_runs" | "job_executions";
+ /** Name of the ID field in the payload */
+ idField: "runId" | "jobExecutionId";
+ /** Queue instance to add retry job to */
+ queue: any;
+ /** Queue name for the retry job */
+ queueName: string;
+ /** Job name for the retry job */
+ jobName: string;
+ /** Metric name for rate limit tracking */
+ metricName: string;
+ /** Function to generate retry delay in milliseconds */
+ delayFn: () => number;
+}
+
+/**
+ * Handles rate limiting and retry logic for queue jobs
+ * Automatically retries jobs that fail with 429/5xx errors unless they're older than 24h
+ *
+ * @param error - The error that occurred
+ * @param job - The job that failed
+ * @param config - Retry configuration
+ * @returns true if retry was handled and job was added to the queue, false if regular processing should continue
+ */
+export async function handleRetryableError(
+ error: unknown,
+ job: { data: { payload: { projectId: string; [key: string]: any } } },
+ config: RetryConfig,
+): Promise<boolean> {
+ // Only handle specific retryable errors
+ if (
+ !(error instanceof ApiError) ||
+ (error.httpCode !== 429 && error.httpCode < 500)
+ ) {
+ return false; // Not a retryable error
+ }
+
+ try {
+ const jobId = job.data.payload[config.idField];
+
+ // Check if the job is older than 24h
+ const record = await kyselyPrisma.$kysely
+ .selectFrom(config.table)
+ .select("created_at")
+ .where("id", "=", jobId)
+ .where("project_id", "=", job.data.payload.projectId)
+ .executeTakeFirstOrThrow();
+
+ if (record.created_at < new Date(Date.now() - ONE_DAY_IN_MS)) {
+ logger.info(
+ `Job ${jobId} is rate limited for more than 24h. Stop retrying.`,
+ );
+ return false; // Don't retry
+ } else {
+ // Retry the job with delay
+ const delay = config.delayFn();
+ logger.info(`Job ${jobId} is rate limited. Retrying in ${delay}ms.`);
+
+ recordIncrement(config.metricName);
+
+ await config.queue?.add(
+ config.queueName,
+ {
+ name: config.jobName,
+ id: randomUUID(),
+ timestamp: new Date(),
+ payload: job.data.payload,
+ },
+ { delay },
+ );
+
+ return true; // Do not continue regular processing, job was added to the queue
+ }
+ } catch (innerErr) {
+ const jobId = job.data.payload[config.idField];
+ logger.error(
+ `Failed to handle 429 retry for ${jobId}. Continuing regular processing.`,
+ innerErr,
+ );
+ return false; // Failed to handle retry - fallback to regular processing
+ }
+}
diff --git a/worker/src/features/utilities.ts b/worker/src/features/utils/utilities.ts
similarity index 59%
rename from worker/src/features/utilities.ts
rename to worker/src/features/utils/utilities.ts
index 0785767b78..012e8856d9 100644
--- a/worker/src/features/utilities.ts
+++ b/worker/src/features/utils/utilities.ts
@@ -10,9 +10,40 @@ import { z } from "zod/v4";
import { z as zodV3 } from "zod/v3";
import { ZodSchema as ZodV3Schema } from "zod/v3";
import { decrypt } from "@langfuse/shared/encryption";
-import { tokenCount } from "./tokenisation/usage";
+import { tokenCount } from "../tokenisation/usage";
import Handlebars from "handlebars";
+/**
+ * Standard error handling for LLM operations
+ * Handles common LLM errors like quota limits and throttling with appropriate status codes
+ *
+ * @param operation - The async LLM operation to execute
+ * @param operationName - Name for error context (e.g., "call LLM")
+ * @returns The result of the operation or throws an ApiError
+ */
+async function withLLMErrorHandling<T>(
+ operation: () => Promise<T>,
+ operationName: string = "LLM operation",
+): Promise<T> {
+ try {
+ return await operation();
+ } catch (e) {
+ // Handle specific LLM provider errors with appropriate status codes
+ if (
+ e instanceof Error &&
+ (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
+ ) {
+ throw new ApiError(e.name, 429);
+ }
+
+ // Handle all other errors with preserved status codes
+ throw new ApiError(
+ `Failed to ${operationName}: ${e}`,
+ (e as any)?.response?.status ?? (e as any)?.status,
+ );
+ }
+}
+
export async function callStructuredLLM<T extends ZodV3Schema>(
jeId: string,
llmApiKey: z.infer<typeof LLMApiKeySchema>,
@@ -22,7 +53,7 @@ export async function callStructuredLLM<T extends ZodV3Schema>(
model: string,
structuredOutputSchema: T,
): Promise<zodV3.infer<T>> {
- try {
+ return withLLMErrorHandling(async () => {
const { completion } = await fetchLLMCompletion({
streaming: false,
apiKey: decrypt(llmApiKey.secretKey), // decrypt the secret key
@@ -41,19 +72,7 @@ export async function callStructuredLLM<T extends ZodV3Schema>(
});
return structuredOutputSchema.parse(completion);
- } catch (e) {
- if (
- e instanceof Error &&
- (e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
- ) {
- throw new ApiError(e.name, 429);
- }
-
- throw new ApiError(
- `Failed to call LLM: ${e}`,
- (e as any)?.response?.status ?? (e as any)?.status,
- );
- }
+ }, "call LLM");
}
export async function callLLM(
@@ -64,31 +83,33 @@ export async function callLLM(
model: string,
traceParams?: Omit<TraceParams, "tokenCountDelegate">,
): Promise<string> {
- const { completion, processTracedEvents } = await fetchLLMCompletion({
- streaming: false,
- apiKey: decrypt(llmApiKey.secretKey),
- extraHeaders: decryptAndParseExtraHeaders(llmApiKey.extraHeaders),
- baseURL: llmApiKey.baseURL || undefined,
- messages,
- modelParams: {
- provider,
- model,
- adapter: llmApiKey.adapter,
- ...modelParams,
- },
- config: llmApiKey.config,
- traceParams: traceParams
- ? { ...traceParams, tokenCountDelegate: tokenCount }
- : undefined,
- maxRetries: 1,
- throwOnError: false,
- });
+ return withLLMErrorHandling(async () => {
+ const { completion, processTracedEvents } = await fetchLLMCompletion({
+ streaming: false,
+ apiKey: decrypt(llmApiKey.secretKey),
+ extraHeaders: decryptAndParseExtraHeaders(llmApiKey.extraHeaders),
+ baseURL: llmApiKey.baseURL || undefined,
+ messages,
+ modelParams: {
+ provider,
+ model,
+ adapter: llmApiKey.adapter,
+ ...modelParams,
+ },
+ config: llmApiKey.config,
+ traceParams: traceParams
+ ? { ...traceParams, tokenCountDelegate: tokenCount }
+ : undefined,
+ maxRetries: 1,
+ throwOnError: false,
+ });
- if (traceParams) {
- await processTracedEvents();
- }
+ if (traceParams) {
+ await processTracedEvents();
+ }
- return completion;
+ return completion;
+ }, "call LLM");
}
export function compileHandlebarString(
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 6602f9e7ae..0631874c65 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -14,10 +14,10 @@ import {
traceException,
EvalExecutionQueue,
QueueJobs,
- recordIncrement,
} from "@langfuse/shared/src/server";
import { createEvalJobs, evaluate } from "../features/evaluation/evalService";
-import { randomUUID } from "crypto";
+import { delayInMs } from "./utils/delays";
+import { handleRetryableError } from "../features/utils";
export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
@@ -88,52 +88,18 @@ export const evalJobExecutorQueueProcessor = async (
return true;
} catch (e) {
// If the job fails with a 429, we want to retry it unless it's older than 24h.
- if (
- (e instanceof ApiError && e.httpCode === 429) || // retry all rate limits
- (e instanceof ApiError && e.httpCode >= 500) // retry all 5xx errors
- ) {
- try {
- // Check if the job execution is older than 24h
- const jobExecution = await kyselyPrisma.$kysely
- .selectFrom("job_executions")
- .select("created_at")
- .where("id", "=", job.data.payload.jobExecutionId)
- .where("project_id", "=", job.data.payload.projectId)
- .executeTakeFirstOrThrow();
- if (
- // Do nothing if job execution is older than 24h
- jobExecution.created_at < new Date(Date.now() - 24 * 60 * 60 * 1000)
- ) {
- logger.info(
- `Job ${job.data.payload.jobExecutionId} is retrying for more than 24h. Stop retrying.`,
- );
- } else {
- // Add the job into the queue with a random delay between 1 and 10min and return
- const delay = Math.floor(Math.random() * 9 + 1) * 60 * 1000;
- logger.info(
- `Job ${job.data.payload.jobExecutionId} is rate limited. Retrying in ${delay}ms.`,
- );
- recordIncrement("langfuse.evaluation-execution.rate-limited");
- await EvalExecutionQueue.getInstance()?.add(
- QueueName.EvaluationExecution,
- {
- name: QueueJobs.EvaluationExecution,
- id: randomUUID(),
- timestamp: new Date(),
- payload: job.data.payload,
- },
- {
- delay,
- },
- );
- return;
- }
- } catch (innerErr) {
- logger.error(
- `Failed to handle 429 retry for ${job.data.payload.jobExecutionId}. Continuing regular processing.`,
- innerErr,
- );
- }
+ const wasRetried = await handleRetryableError(e, job, {
+ table: "job_executions",
+ idField: "jobExecutionId",
+ queue: EvalExecutionQueue.getInstance(),
+ queueName: QueueName.EvaluationExecution,
+ jobName: QueueJobs.EvaluationExecution,
+ metricName: "langfuse.evaluation-execution.rate-limited",
+ delayFn: delayInMs,
+ });
+
+ if (wasRetried) {
+ return;
}
// we are left with 4xx and application errors here.
diff --git a/worker/src/queues/experimentQueue.ts b/worker/src/queues/experimentQueue.ts
index c94aff071a..74d85da169 100644
--- a/worker/src/queues/experimentQueue.ts
+++ b/worker/src/queues/experimentQueue.ts
@@ -1,6 +1,8 @@
import { Job } from "bullmq";
import {
+ ExperimentCreateQueue,
ExperimentMetadataSchema,
+ QueueJobs,
QueueName,
TQueueJobTypes,
logger,
@@ -9,6 +11,8 @@ import {
import { createExperimentJob } from "../features/experiments/experimentService";
import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";
import { kyselyPrisma } from "@langfuse/shared/src/db";
+import { handleRetryableError } from "../features/utils";
+import { delayInMs } from "./utils/delays";
export const experimentCreateQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.ExperimentCreate]>,
@@ -24,6 +28,23 @@ export const experimentCreateQueueProcessor = async (
});
return true;
} catch (e) {
+ // If creating any of the dataset run items associated with this experiment create job fails with a 429, we want to retry the experiment creation job unless it's older than 24h.
+ const wasRetried = await handleRetryableError(e, job, {
+ table: "dataset_runs",
+ idField: "runId",
+ queue: ExperimentCreateQueue.getInstance(),
+ queueName: QueueName.ExperimentCreate,
+ jobName: QueueJobs.ExperimentCreateJob,
+ metricName: "langfuse.experiment-create.rate-limited",
+ delayFn: delayInMs,
+ });
+
+ if (wasRetried) {
+ return;
+ }
+
+ // we are left with 4xx and application errors here.
+
if (
e instanceof InvalidRequestError ||
e instanceof LangfuseNotFoundError
diff --git a/worker/src/queues/utils/delays.ts b/worker/src/queues/utils/delays.ts
new file mode 100644
index 0000000000..466c31e314
--- /dev/null
+++ b/worker/src/queues/utils/delays.ts
@@ -0,0 +1,13 @@
+export const delayInMs = (
+ range: { minMinutes: number; maxMinutes: number } = {
+ minMinutes: 1,
+ maxMinutes: 10,
+ },
+) => {
+ const delay = Math.floor(
+ Math.random() * (range.maxMinutes - range.minMinutes + 1) +
+ range.minMinutes,
+ );
+
+ return delay * 60 * 1000;
+};