Skip to content

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

feat: apply evals on history of datasets + traces (#5488)

Max Deichmanneb5ee957e601
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index be988164ce..aefdb40b98 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -267,6 +267,7 @@ export type JobConfiguration = {
variable_mapping: unknown;
sampling: string;
delay: number;
+ time_scope: Generated<string[]>;
};
export type JobExecution = {
id: string;
diff --git a/packages/shared/prisma/migrations/20250214173309_add_timescope_to_configs/migration.sql b/packages/shared/prisma/migrations/20250214173309_add_timescope_to_configs/migration.sql
new file mode 100644
index 0000000000..99fafbac4a
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250214173309_add_timescope_to_configs/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "job_configurations" ADD COLUMN "time_scope" TEXT[] DEFAULT ARRAY['NEW']::TEXT[];
diff --git a/packages/shared/prisma/migrations/migration_lock.toml b/packages/shared/prisma/migrations/migration_lock.toml
index fbffa92c2b..648c57fd59 100644
--- a/packages/shared/prisma/migrations/migration_lock.toml
+++ b/packages/shared/prisma/migrations/migration_lock.toml
@@ -1,3 +1,3 @@
# Please do not edit this file manually
-# It should be added in your version-control system (i.e. Git)
+# It should be added in your version-control system (e.g., Git)
provider = "postgresql"
\ No newline at end of file
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 86589de6d4..4708f69fc0 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -3,7 +3,7 @@
generator client {
provider = "prisma-client-js"
- previewFeatures = ["tracing", "views", "relationJoins", "metrics"]
+ previewFeatures = ["views", "relationJoins", "metrics"]
}
datasource db {
@@ -853,6 +853,7 @@ model JobConfiguration {
variableMapping Json @map("variable_mapping")
sampling Decimal // ratio of jobs that are executed for sampling (0..1)
delay Int // delay in milliseconds
+ timeScope String[] @default(["NEW"]) @map("time_scope")
JobExecution JobExecution[]
@@index([projectId, id])
diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.ts
index 13b45f072a..3a3985f526 100644
--- a/packages/shared/src/features/batchExport/types.ts
+++ b/packages/shared/src/features/batchExport/types.ts
@@ -21,6 +21,7 @@ export enum BatchExportTableName {
Sessions = "sessions",
Traces = "traces",
Generations = "generations",
+ DatasetRunItems = "dataset_run_items",
}
export const exportOptions: Record<
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 095be9e771..8302276a23 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -107,3 +107,8 @@ export const OutputSchema = z.object({
});
export const DEFAULT_TRACE_JOB_DELAY = 10_000;
+
+export const JobTimeScopeZod = z.enum(["NEW", "EXISTING"]);
+export type JobTimeScope = z.infer<typeof JobTimeScopeZod>;
+
+export const TimeScopeSchema = z.array(JobTimeScopeZod).default(["NEW"]);
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 8fdcd01ffa..575612d549 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -23,6 +23,7 @@ export * from "../server/ingestion/types";
export * from "../server/ingestion/validateAndInflateScore";
export * from "./redis/redis";
export * from "./redis/traceUpsert";
+export * from "./redis/createEvalQueue";
export * from "./redis/cloudUsageMeteringQueue";
export * from "./redis/getQueue";
export * from "./redis/traceDelete";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 7dbbe5e18e..778b217289 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -1,3 +1,4 @@
+/* eslint-disable no-unused-vars */
import { z } from "zod";
import { eventTypes } from ".";
import {
@@ -61,16 +62,55 @@ export const DataRetentionProcessingEventSchema = z.object({
projectId: z.string(),
retention: z.number(),
});
-export const BatchActionProcessingEventSchema = z.object({
- projectId: z.string(),
- actionId: z.string(),
- query: BatchActionQuerySchema,
- tableName: z.nativeEnum(BatchExportTableName),
- cutoffCreatedAt: z.date(),
- targetId: z.string().optional(),
- type: z.nativeEnum(BatchActionType),
-});
+export const BatchActionProcessingEventSchema = z.discriminatedUnion(
+ "actionId",
+ [
+ z.object({
+ actionId: z.literal("trace-delete"),
+ projectId: z.string(),
+ query: BatchActionQuerySchema,
+ tableName: z.nativeEnum(BatchExportTableName),
+ cutoffCreatedAt: z.date(),
+ targetId: z.string().optional(),
+ type: z.nativeEnum(BatchActionType),
+ }),
+ z.object({
+ actionId: z.literal("trace-add-to-annotation-queue"),
+ projectId: z.string(),
+ query: BatchActionQuerySchema,
+ tableName: z.nativeEnum(BatchExportTableName),
+ cutoffCreatedAt: z.date(),
+ targetId: z.string().optional(),
+ type: z.nativeEnum(BatchActionType),
+ }),
+ z.object({
+ actionId: z.literal("eval-create"),
+ targetObject: z.enum(["trace", "dataset"]),
+ configId: z.string(),
+ projectId: z.string(),
+ cutoffCreatedAt: z.date(),
+ query: BatchActionQuerySchema,
+ }),
+ ],
+);
+export const CreateEvalQueueEventSchema = DatasetRunItemUpsertEventSchema.and(
+ z.object({
+ configId: z.string(),
+ timestamp: z.date(),
+ }),
+).or(
+ TraceQueueEventSchema.and(
+ z.object({
+ timestamp: z.date(),
+ configId: z.string(),
+ }),
+ ),
+);
+
+export type CreateEvalQueueEventType = z.infer<
+ typeof CreateEvalQueueEventSchema
+>;
export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;
export type TraceQueueEventType = z.infer<typeof TraceQueueEventSchema>;
export type TracesQueueEventType = z.infer<typeof TracesQueueEventSchema>;
@@ -111,6 +151,7 @@ export enum QueueName {
DataRetentionQueue = "data-retention-queue",
DataRetentionProcessingQueue = "data-retention-processing-queue",
BatchActionQueue = "batch-action-queue",
+ CreateEvalQueue = "create-eval-queue",
}
export enum QueueJobs {
@@ -131,6 +172,7 @@ export enum QueueJobs {
DataRetentionJob = "data-retention-job",
DataRetentionProcessingJob = "data-retention-processing-job",
BatchActionProcessingJob = "batch-action-processing-job",
+ CreateEvalJob = "create-eval-job",
}
export type TQueueJobTypes = {
@@ -206,4 +248,10 @@ export type TQueueJobTypes = {
payload: BatchActionProcessingEventType;
name: QueueJobs.BatchActionProcessingJob;
};
+ [QueueName.CreateEvalQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: CreateEvalQueueEventType;
+ name: QueueJobs.CreateEvalJob;
+ };
};
diff --git a/packages/shared/src/server/redis/createEvalQueue.ts b/packages/shared/src/server/redis/createEvalQueue.ts
new file mode 100644
index 0000000000..f187b9db76
--- /dev/null
+++ b/packages/shared/src/server/redis/createEvalQueue.ts
@@ -0,0 +1,45 @@
+import { QueueName, TQueueJobTypes } from "../queues";
+import { Queue } from "bullmq";
+import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
+import { logger } from "../logger";
+
+export class CreateEvalQueue {
+ private static instance: Queue<
+ TQueueJobTypes[QueueName.CreateEvalQueue]
+ > | null = null;
+
+ public static getInstance(): Queue<
+ TQueueJobTypes[QueueName.CreateEvalQueue]
+ > | null {
+ if (CreateEvalQueue.instance) return CreateEvalQueue.instance;
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ CreateEvalQueue.instance = newRedis
+ ? new Queue<TQueueJobTypes[QueueName.CreateEvalQueue]>(
+ QueueName.CreateEvalQueue,
+ {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: 100, // Important: If not true, new jobs for that ID would be ignored as jobs in the complete set are still considered as part of the queue
+ removeOnFail: 100_000,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ },
+ )
+ : null;
+
+ CreateEvalQueue.instance?.on("error", (err) => {
+ logger.error("CreateEvalQueue error", err);
+ });
+
+ return CreateEvalQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 159795194f..a3d98c5705 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -16,6 +16,7 @@ import { MeteringDataPostgresExportQueue } from "./meteringDataPostgresExportQue
import { DataRetentionQueue } from "./dataRetentionQueue";
import { DataRetentionProcessingQueue } from "./dataRetentionProcessingQueue";
import { BatchActionQueue } from "./batchActionQueue";
+import { CreateEvalQueue } from "./createEvalQueue";
export function getQueue(queueName: QueueName): Queue | null {
switch (queueName) {
@@ -53,6 +54,8 @@ export function getQueue(queueName: QueueName): Queue | null {
return DataRetentionProcessingQueue.getInstance();
case QueueName.BatchActionQueue:
return BatchActionQueue.getInstance();
+ case QueueName.CreateEvalQueue:
+ return CreateEvalQueue.getInstance();
default:
const exhaustiveCheckDefault: never = queueName;
throw new Error(`Queue ${queueName} not found`);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3acb43dc98..b001ad54a0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14414,7 +14414,7 @@ snapshots:
'@aws-sdk/client-bedrock-agent-runtime': 3.668.0
'@aws-sdk/client-bedrock-runtime': 3.668.0
'@aws-sdk/client-kendra': 3.668.0
- '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
+ '@aws-sdk/credential-provider-node': 3.675.0(@aws-sdk/[email protected](@aws-sdk/[email protected]))(@aws-sdk/[email protected])
'@langchain/core': 0.3.18([email protected]([email protected]))
zod: 3.23.8
zod-to-json-schema: 3.23.5([email protected])
diff --git a/web/src/components/level-counts-display.tsx b/web/src/components/level-counts-display.tsx
new file mode 100644
index 0000000000..554f2ab325
--- /dev/null
+++ b/web/src/components/level-counts-display.tsx
@@ -0,0 +1,47 @@
+import React from "react";
+import { Separator } from "@/src/components/ui/separator";
+import { numberFormatter } from "@/src/utils/numbers";
+import { Skeleton } from "@/src/components/ui/skeleton";
+
+export type LevelCount = {
+ level: string;
+ count: number | bigint;
+ symbol: string;
+ customNumberFormatter?: (number: number | bigint) => string;
+};
+
+interface LevelCountsDisplayProps {
+ counts: LevelCount[];
+ isLoading?: boolean;
+}
+
+export function LevelCountsDisplay({
+ counts,
+ isLoading,
+}: LevelCountsDisplayProps) {
+ if (isLoading) return <Skeleton className="h-3 w-1/2" />;
+
+ const nonZeroCounts = counts.filter((item) => item.count > 0);
+
+ return (
+ <div className="flex min-h-6 flex-row gap-2 overflow-x-auto whitespace-nowrap">
+ {nonZeroCounts.map(
+ ({ level, count, symbol, customNumberFormatter }, index) => (
+ <React.Fragment key={level}>
+ <div className="flex min-w-max flex-row gap-2">
+ <span className="text-xs">
+ {symbol}{" "}
+ {customNumberFormatter
+ ? customNumberFormatter(count)
+ : numberFormatter(count, 0)}
+ </span>
+ </div>
+ {index < nonZeroCounts.length - 1 && (
+ <Separator orientation="vertical" className="h-5" />
+ )}
+ </React.Fragment>
+ ),
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index 2f5a3a33a5..96e98200b3 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -56,7 +56,6 @@ import { BatchExportTableButton } from "@/src/components/BatchExportTableButton"
import { BreakdownTooltip } from "@/src/components/trace/BreakdownToolTip";
import { InfoIcon, MoreVertical } from "lucide-react";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
-import { Separator } from "@/src/components/ui/separator";
import React from "react";
import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";
@@ -64,6 +63,10 @@ import { LocalIsoDate } from "@/src/components/LocalIsoDate";
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { type TableAction } from "@/src/features/table/types";
+import {
+ LevelCountsDisplay,
+ type LevelCount,
+} from "@/src/components/level-counts-display";
import {
DropdownMenuContent,
DropdownMenu,
@@ -736,27 +739,15 @@ export default function TracesTable({
row.getValue("levelCounts");
if (!traceMetrics.data) return <Skeleton className="h-3 w-1/2" />;
- const nonZeroCounts = Object.entries(value).filter(
- ([_, count]) => count > 0,
+ const counts: LevelCount[] = Object.entries(value).map(
+ ([level, count]) => ({
+ level: formatAsLabel(level),
+ count,
+ symbol: LevelSymbols[formatAsLabel(level)],
+ }),
);
- return (
- <div className="flex min-h-6 flex-row gap-2 overflow-x-auto whitespace-nowrap">
- {nonZeroCounts.map(([level, count], index) => (
- <React.Fragment key={level}>
- <div className="flex min-w-6 flex-row gap-2">
- <span className="text-xs">
- {LevelSymbols[formatAsLabel(level)]}{" "}
- {numberFormatter(count, 0)}
- </span>
- </div>
- {index < nonZeroCounts.length - 1 && (
- <Separator orientation="vertical" className="h-5" />
- )}
- </React.Fragment>
- ))}
- </div>
- );
+ return <LevelCountsDisplay counts={counts} />;
},
enableHiding: true,
},
diff --git a/web/src/ee/features/evals/components/evaluator-form.tsx b/web/src/ee/features/evals/components/evaluator-form.tsx
index 82c0705bab..cf353385fa 100644
--- a/web/src/ee/features/evals/components/evaluator-form.tsx
+++ b/web/src/ee/features/evals/components/evaluator-form.tsx
@@ -29,6 +29,7 @@ import {
datasetFormFilterColsWithOptions,
availableDatasetEvalVariables,
type langfuseObjects,
+ TimeScopeSchema,
} from "@langfuse/shared";
import * as z from "zod";
import { useEffect, useMemo, useState } from "react";
@@ -65,6 +66,8 @@ import { cn } from "@/src/utils/tailwind";
import { Dialog, DialogContent, DialogTitle } from "@/src/components/ui/dialog";
import { EvalTemplateForm } from "@/src/ee/features/evals/components/template-form";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import { compactNumberFormatter } from "@/src/utils/numbers";
export const fieldHasJsonSelectorOption = (
selectedColumnId: string | undefined | null,
@@ -80,6 +83,7 @@ const formSchema = z.object({
mapping: z.array(wipVariableMapping),
sampling: z.coerce.number().gt(0).lte(1),
delay: z.coerce.number().optional().default(10),
+ timeScope: TimeScopeSchema,
});
type LangfuseObject = (typeof langfuseObjects)[number];
@@ -340,6 +344,10 @@ export const InnerEvalConfigForm = (props: {
delay: props.existingEvaluator?.delay
? props.existingEvaluator.delay / 1000
: 10,
+ timeScope: (props.existingEvaluator?.timeScope ?? ["NEW"]).filter(
+ (option): option is "NEW" | "EXISTING" =>
+ ["NEW", "EXISTING"].includes(option),
+ ),
},
});
@@ -432,6 +440,26 @@ export const InnerEvalConfigForm = (props: {
const validatedFilter = z.array(singleFilter).safeParse(values.filter);
+ if (
+ props.existingEvaluator?.timeScope.includes("EXISTING") &&
+ props.mode === "edit" &&
+ !values.timeScope.includes("EXISTING")
+ ) {
+ form.setError("timeScope", {
+ type: "manual",
+ message:
+ "The evaluator ran on existing traces already. This cannot be changed anymore.",
+ });
+ return;
+ }
+ if (form.getValues("timeScope").length === 0) {
+ form.setError("timeScope", {
+ type: "manual",
+ message: "Please select at least one.",
+ });
+ return;
+ }
+
if (validatedFilter.success === false) {
form.setError("filter", {
type: "manual",
@@ -469,6 +497,7 @@ export const InnerEvalConfigForm = (props: {
variableMapping: mapping,
sampling,
scoreName,
+ timeScope: values.timeScope,
},
})
: createJobMutation.mutateAsync({
@@ -480,6 +509,7 @@ export const InnerEvalConfigForm = (props: {
mapping,
sampling,
delay,
+ timeScope: values.timeScope,
})
)
.then(() => {
@@ -574,6 +604,75 @@ export const InnerEvalConfigForm = (props: {
)}
/>
+ <div className="flex min-w-[300px]">
+ <FormField
+ control={form.control}
+ name="timeScope"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Evaluator runs on</FormLabel>
+ <FormControl>
+ <div className="flex flex-col gap-2">
+ <div className="items-top flex space-x-2">
+ <Checkbox
+ id="newObjects"
+ checked={field.value.includes("NEW")}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...field.value, "NEW"]
+ : field.value.filter((v) => v !== "NEW");
+ field.onChange(newValue);
+ }}
+ disabled={props.disabled}
+ />
+ <div className="grid gap-1.5 leading-none">
+ <label
+ htmlFor="newObjects"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ New{" "}
+ {form.watch("target") === "trace"
+ ? "traces"
+ : "dataset items"}
+ </label>
+ </div>
+ </div>
+ <div className="items-top flex space-x-2">
+ <Checkbox
+ id="existingObjects"
+ checked={field.value.includes("EXISTING")}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...field.value, "EXISTING"]
+ : field.value.filter((v) => v !== "EXISTING");
+ field.onChange(newValue);
+ }}
+ disabled={
+ props.disabled ||
+ (props.mode === "edit" &&
+ field.value.includes("EXISTING"))
+ }
+ />
+ <div className="grid gap-1.5 leading-none">
+ <label
+ htmlFor="existingObjects"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Existing{" "}
+ {form.watch("target") === "trace"
+ ? "traces"
+ : "dataset items"}
+ </label>
+ </div>
+ </div>
+ </div>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+
<FormField
control={form.control}
name="filter"
@@ -594,8 +693,11 @@ export const InnerEvalConfigForm = (props: {
/>
</FormControl>
<FormDescription>
- This will run on all future traces that match these
- filters
+ <TimeScopeDescription
+ projectId={props.projectId}
+ timeScope={form.watch("timeScope")}
+ target="trace"
+ />
</FormDescription>
<FormMessage />
</>
@@ -613,7 +715,11 @@ export const InnerEvalConfigForm = (props: {
/>
</FormControl>
<FormDescription>
- This will run on all future dataset experiment runs
+ <TimeScopeDescription
+ projectId={props.projectId}
+ timeScope={form.watch("timeScope")}
+ target="dataset_item"
+ />
</FormDescription>
<FormMessage />
</>
@@ -938,3 +1044,32 @@ function VariableMappingDescription(p: {
</div>
);
}
+
+export const TimeScopeDescription = (props: {
+ projectId: string;
+ timeScope: ("NEW" | "EXISTING")[] | undefined;
+ target: "trace" | "dataset_item" | undefined;
+}) => {
+ if (!props.timeScope || props.timeScope.length === 0) {
+ return "Select a time scope to run this configuration on.";
+ }
+
+ const globalConfig = api.evals.globalJobConfigs.useQuery({
+ projectId: props.projectId,
+ });
+ return (
+ <div>
+ This configuration will run on{" "}
+ {props.timeScope?.includes("NEW") && props.timeScope?.includes("EXISTING")
+ ? "all future and existing"
+ : props.timeScope?.includes("NEW")
+ ? "all future"
+ : "all existing"}{" "}
+ {props.target === "trace" ? "traces" : "dataset items"} that match these
+ filters.{" "}
+ {globalConfig.data && props.timeScope?.includes("EXISTING")
+ ? `We execute the evaluation on up to ${compactNumberFormatter(globalConfig.data)} historic evaluations.`
+ : null}
+ </div>
+ );
+};
diff --git a/web/src/ee/features/evals/components/evaluator-table.tsx b/web/src/ee/features/evals/components/evaluator-table.tsx
index c3edfecc34..8542d7b6d6 100644
--- a/web/src/ee/features/evals/components/evaluator-table.tsx
+++ b/web/src/ee/features/evals/components/evaluator-table.tsx
@@ -1,4 +1,5 @@
import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { LevelCountsDisplay } from "@/src/components/level-counts-display";
import { DataTable } from "@/src/components/table/data-table";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import TableLink from "@/src/components/table/table-link";
@@ -7,6 +8,7 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColum
import { InlineFilterState } from "@/src/features/filters/components/filter-builder";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { type RouterOutputs, api } from "@/src/utils/api";
+import { compactNumberFormatter } from "@/src/utils/numbers";
import { type FilterState, singleFilter } from "@langfuse/shared";
import { createColumnHelper } from "@tanstack/react-table";
import { useEffect } from "react";
@@ -25,6 +27,11 @@ export type EvaluatorDataRow = {
scoreName: string;
target: string; // "trace" or "dataset"
filter: FilterState;
+ result: {
+ level: string;
+ count: number;
+ symbol: string;
+ }[];
};
export default function EvaluatorTable({ projectId }: { projectId: string }) {
@@ -75,7 +82,21 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
size: 80,
cell: (row) => {
const status = row.getValue();
- return <StatusBadge type={status.toLowerCase()} />;
+ return (
+ <StatusBadge
+ type={status.toLowerCase()}
+ className={row.getValue() === "FINISHED" ? "pl-3" : ""}
+ />
+ );
+ },
+ }),
+ columnHelper.accessor("result", {
+ header: "Result",
+ id: "result",
+ size: 150,
+ cell: (row) => {
+ const result = row.getValue();
+ return <LevelCountsDisplay counts={result} />;
},
}),
columnHelper.accessor("createdAt", {
@@ -148,9 +169,50 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
const convertToTableRow = (
jobConfig: RouterOutputs["evals"]["allConfigs"]["configs"][number],
): EvaluatorDataRow => {
+ const statusCounts = jobConfig.jobExecutions.reduce(
+ (acc, je) => {
+ acc[je.status.toString()] = (acc[je.status.toString()] || 0) + 1;
+ return acc;
+ },
+ {
+ PENDING: 0,
+ ERROR: 0,
+ COMPLETED: 0,
+ } as Record<string, number>,
+ );
+
+ const result = [
+ {
+ level: "pending",
+ count: statusCounts.PENDING,
+ symbol: "🕒",
+ customNumberFormatter: compactNumberFormatter,
+ },
+ {
+ level: "error",
+ count: statusCounts.ERROR,
+ symbol: "❌",
+ customNumberFormatter: compactNumberFormatter,
+ },
+ {
+ level: "succeeded",
+ count: statusCounts.COMPLETED,
+ symbol: "✅",
+ customNumberFormatter: compactNumberFormatter,
+ },
+ ];
+
+ const finalStatus =
+ jobConfig.timeScope.length === 1 &&
+ jobConfig.timeScope[0] === "EXISTING" &&
+ !jobConfig.jobExecutions.some((je) => je.status === "PENDING") &&
+ jobConfig.jobExecutions.length > 0
+ ? "FINISHED"
+ : jobConfig.status;
+
return {
id: jobConfig.id,
- status: jobConfig.status,
+ status: finalStatus,
createdAt: jobConfig.createdAt.toLocaleString(),
template: jobConfig.evalTemplate
? {
@@ -162,6 +224,7 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
scoreName: jobConfig.scoreName,
target: jobConfig.targetObject,
filter: z.array(singleFilter).parse(jobConfig.filter),
+ result: result,
};
};
diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.ts
index da1870fcb8..f985708b32 100644
--- a/web/src/ee/features/evals/server/router.ts
+++ b/web/src/ee/features/evals/server/router.ts
@@ -13,24 +13,30 @@ import {
ChatMessageRole,
paginationZod,
type JobConfiguration,
- JobConfigState,
JobType,
Prisma,
+ TimeScopeSchema,
+ JobConfigState,
} from "@langfuse/shared";
import { decrypt } from "@langfuse/shared/encryption";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
import {
decryptAndParseExtraHeaders,
fetchLLMCompletion,
+ getQueue,
getScoresByIds,
- LLMApiKeySchema,
logger,
+ QueueName,
+ QueueJobs,
+ LLMApiKeySchema,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
import { EvalReferencedEvaluators } from "@/src/ee/features/evals/types";
import { EvaluatorStatus } from "../types";
import { traceException } from "@langfuse/shared/src/server";
import { isNotNullOrUndefined } from "@/src/utils/types";
+import { v4 as uuidv4 } from "uuid";
+import { env } from "@/src/env.mjs";
const APIEvaluatorSchema = z.object({
id: z.string(),
@@ -93,11 +99,12 @@ const CreateEvalJobSchema = z.object({
projectId: z.string(),
evalTemplateId: z.string(),
scoreName: z.string().min(1),
- target: z.string(),
+ target: z.string(z.enum(["trace", "dataset-run-item"])),
filter: z.array(singleFilter).nullable(), // reusing the filter type from the tables
mapping: z.array(variableMapping),
sampling: z.number().gt(0).lte(1),
delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default
+ timeScope: TimeScopeSchema,
});
const UpdateEvalJobSchema = z.object({
@@ -107,9 +114,26 @@ const UpdateEvalJobSchema = z.object({
sampling: z.number().gt(0).lte(1).optional(),
delay: z.number().gte(0).optional(),
status: z.nativeEnum(EvaluatorStatus).optional(),
+ timeScope: TimeScopeSchema.optional(),
});
export const evalRouter = createTRPCRouter({
+ globalJobConfigs: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "model-based-evaluations",
+ projectId: input.projectId,
+ sessionUser: ctx.session.user,
+ });
+
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:read",
+ });
+ return env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT;
+ }),
allConfigs: protectedProjectProcedure
.input(
z.object({
@@ -137,6 +161,7 @@ export const evalRouter = createTRPCRouter({
},
include: {
evalTemplate: true,
+ JobExecution: true,
},
orderBy: {
status: "asc",
@@ -152,7 +177,10 @@ export const evalRouter = createTRPCRouter({
},
});
return {
- configs: configs,
+ configs: configs.map((config) => ({
+ ...config,
+ jobExecutions: config.JobExecution,
+ })),
totalCount: count,
};
}),
@@ -479,8 +507,17 @@ export const evalRouter = createTRPCRouter({
throw new Error("Template not found");
}
+ const jobId = uuidv4();
+ await auditLog({
+ session: ctx.session,
+ resourceType: "job",
+ resourceId: jobId,
+ action: "create",
+ });
+
const job = await ctx.prisma.jobConfiguration.create({
data: {
+ id: jobId,
projectId: input.projectId,
jobType: "EVAL",
evalTemplateId: input.evalTemplateId,
@@ -491,14 +528,42 @@ export const evalRouter = createTRPCRouter({
sampling: input.sampling,
delay: input.delay,
status: "ACTIVE",
+ timeScope: input.timeScope,
},
});
- await auditLog({
- session: ctx.session,
- resourceType: "job",
- resourceId: job.id,
- action: "create",
- });
+
+ if (input.timeScope.includes("EXISTING")) {
+ logger.info(
+ `Applying to historical traces for job ${job.id} and project ${input.projectId}`,
+ );
+ const batchJobQueue = getQueue(QueueName.BatchActionQueue);
+ if (!batchJobQueue) {
+ throw new Error("Batch job queue not found");
+ }
+ await batchJobQueue.add(
+ QueueJobs.BatchActionProcessingJob,
+ {
+ name: QueueJobs.BatchActionProcessingJob,
+ timestamp: new Date(),
+ id: uuidv4(),
+ payload: {
+ projectId: input.projectId,
+ actionId: "eval-create",
+ configId: job.id,
+ cutoffCreatedAt: new Date(),
+ targetObject: input.target,
+ query: {
+ where: input.filter ?? [],
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ },
+ },
+ },
+ { delay: input.delay },
+ );
+ }
} catch (e) {
logger.error(e);
throw e;
@@ -625,32 +690,81 @@ export const evalRouter = createTRPCRouter({
config: UpdateEvalJobSchema,
}),
)
- .mutation(async ({ input, ctx }) => {
+ .mutation(async ({ ctx, input: { config, projectId, evalConfigId } }) => {
throwIfNoEntitlement({
entitlement: "model-based-evaluations",
- projectId: input.projectId,
+ projectId: projectId,
sessionUser: ctx.session.user,
});
throwIfNoProjectAccess({
session: ctx.session,
- projectId: input.projectId,
+ projectId: projectId,
scope: "evalJob:CUD",
});
- await ctx.prisma.jobConfiguration.update({
+ const existingJob = await ctx.prisma.jobConfiguration.findUnique({
where: {
- id: input.evalConfigId,
- projectId: input.projectId,
+ id: evalConfigId,
+ projectId: projectId,
},
- data: input.config,
});
+ if (
+ existingJob?.timeScope.includes("EXISTING") &&
+ !config.timeScope?.includes("EXISTING")
+ ) {
+ throw new Error(
+ "The evaluator ran on existing traces already. This cannot be changed anymore.",
+ );
+ }
+
await auditLog({
session: ctx.session,
resourceType: "job",
- resourceId: input.evalConfigId,
+ resourceId: evalConfigId,
action: "update",
});
+
+ await ctx.prisma.jobConfiguration.update({
+ where: {
+ id: evalConfigId,
+ projectId: projectId,
+ },
+ data: config,
+ });
+
+ if (config.timeScope?.includes("EXISTING")) {
+ logger.info(
+ `Applying to historical traces for job ${evalConfigId} and project ${projectId}`,
+ );
+ const batchJobQueue = getQueue(QueueName.BatchActionQueue);
+ if (!batchJobQueue) {
+ throw new Error("Batch job queue not found");
+ }
+ await batchJobQueue.add(
+ QueueJobs.BatchActionProcessingJob,
+ {
+ name: QueueJobs.BatchActionProcessingJob,
+ timestamp: new Date(),
+ id: uuidv4(),
+ payload: {
+ projectId: projectId,
+ actionId: "eval-create",
+ configId: evalConfigId,
+ cutoffCreatedAt: new Date(),
+ targetObject: existingJob?.targetObject,
+ query: {
+ where: config.filter ?? [],
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ },
+ },
+ },
+ { delay: config.delay },
+ );
+ }
}),
getLogs: protectedProjectProcedure
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 9c99bf8b29..605615539a 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -281,6 +281,10 @@ export const env = createEnv({
.optional(),
LANGFUSE_INIT_USER_NAME: z.string().optional(),
LANGFUSE_INIT_USER_PASSWORD: z.string().optional(),
+ LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT: z
+ .number()
+ .positive()
+ .default(50_000),
},
/**
@@ -377,9 +381,11 @@ export const env = createEnv({
AUTH_AZURE_AD_CLIENT_SECRET: process.env.AUTH_AZURE_AD_CLIENT_SECRET,
AUTH_AZURE_AD_TENANT_ID: process.env.AUTH_AZURE_AD_TENANT_ID,
AUTH_AZURE_AD_ALLOW_ACCOUNT_LINKING:
- process.env.AUTH_AZURE_AD_ALLOW_ACCOUNT_LINKING ?? process.env.AUTH_AZURE_ALLOW_ACCOUNT_LINKING, // fallback on old env var
+ process.env.AUTH_AZURE_AD_ALLOW_ACCOUNT_LINKING ??
+ process.env.AUTH_AZURE_ALLOW_ACCOUNT_LINKING, // fallback on old env var
AUTH_AZURE_AD_CLIENT_AUTH_METHOD:
- process.env.AUTH_AZURE_AD_CLIENT_AUTH_METHOD ?? process.env.AUTH_AZURE_CLIENT_AUTH_METHOD, // fallback on old env var
+ process.env.AUTH_AZURE_AD_CLIENT_AUTH_METHOD ??
+ process.env.AUTH_AZURE_CLIENT_AUTH_METHOD, // fallback on old env var
AUTH_AZURE_AD_CHECKS:
process.env.AUTH_AZURE_AD_CHECKS ?? process.env.AUTH_AZURE_CHECKS, // fallback on old env var
AUTH_OKTA_CLIENT_ID: process.env.AUTH_OKTA_CLIENT_ID,
@@ -543,6 +549,8 @@ export const env = createEnv({
LANGFUSE_INIT_USER_NAME: process.env.LANGFUSE_INIT_USER_NAME,
LANGFUSE_INIT_USER_PASSWORD: process.env.LANGFUSE_INIT_USER_PASSWORD,
NEXT_PUBLIC_BASE_PATH: process.env.NEXT_PUBLIC_BASE_PATH,
+ LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT:
+ process.env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
},
// Skip validation in Docker builds
// DOCKER_BUILD is set in Dockerfile
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index df5ccb72c2..170f4f7954 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -7,7 +7,14 @@ import {
createOrgProjectAndApiKey,
createTrace,
createTracesCh,
+ getQueue,
+ logger,
+ QueueJobs,
+ QueueName,
} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { Decimal } from "decimal.js";
+import waitForExpect from "wait-for-expect";
describe("select all test suite", () => {
it("should process items in chunks", async () => {
@@ -25,17 +32,15 @@ describe("select all test suite", () => {
await createTracesCh(traces);
const selectAllJob = {
- data: {
- payload: {
- projectId,
- actionId: "trace-delete",
- tableName: BatchExportTableName.Traces,
- query: {
- filter: [],
- orderBy: { column: "timestamp", order: "DESC" },
- },
- cutoffCreatedAt: new Date("2024-01-02"),
+ payload: {
+ projectId,
+ actionId: "trace-delete",
+ tableName: BatchExportTableName.Traces,
+ query: {
+ filter: [],
+ orderBy: { column: "timestamp", order: "DESC" },
},
+ cutoffCreatedAt: new Date("2024-01-02"),
},
} as any;
@@ -78,24 +83,22 @@ describe("select all test suite", () => {
await createTracesCh(traces);
const selectAllJob = {
- data: {
- payload: {
- projectId,
- actionId: "trace-delete",
- tableName: BatchExportTableName.Traces,
- query: {
- filter: [
- {
- type: "string",
- operator: "=",
- column: "User ID",
- value: "user1",
- },
- ],
- orderBy: { column: "timestamp", order: "DESC" },
- },
- cutoffCreatedAt: new Date("2024-01-02"),
+ payload: {
+ projectId,
+ actionId: "trace-delete",
+ tableName: BatchExportTableName.Traces,
+ query: {
+ filter: [
+ {
+ type: "string",
+ operator: "=",
+ column: "User ID",
+ value: "user1",
+ },
+ ],
+ orderBy: { column: "timestamp", order: "DESC" },
},
+ cutoffCreatedAt: new Date("2024-01-02"),
},
} as any;
@@ -117,4 +120,302 @@ describe("select all test suite", () => {
expect(remainingRows).toHaveLength(1);
expect(remainingRows[0].userId).toBe("user2");
});
+
+ it("should create eval jobs for historic traces", async () => {
+ // remove all jobs from the evaluation execution queue
+ const queue = getQueue(QueueName.CreateEvalQueue);
+ await queue?.obliterate({ force: true });
+
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId1 = randomUUID();
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: traceId1,
+ user_id: "user1",
+ timestamp: new Date().getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ user_id: "user2",
+ timestamp: new Date().getTime(),
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ const templateId = randomUUID();
+
+ await prisma.evalTemplate.create({
+ data: {
+ id: templateId,
+ projectId,
+ name: "test-template",
+ version: 1,
+ prompt: "Please evaluate toxicity {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: {
+ reasoning: "Please explain your reasoning",
+ score: "Please provide a score between 0 and 1",
+ },
+ },
+ });
+
+ const configId = randomUUID();
+ await prisma.jobConfiguration.create({
+ data: {
+ id: configId,
+ projectId,
+ filter: [
+ {
+ type: "string",
+ value: "1",
+ column: "User ID",
+ operator: "contains",
+ },
+ ],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ evalTemplateId: templateId,
+ },
+ });
+
+ const payload = {
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.BatchActionProcessingJob as const,
+ payload: {
+ projectId,
+ actionId: "eval-create" as const,
+ targetObject: "trace" as const,
+ configId,
+ cutoffCreatedAt: new Date(),
+ query: {
+ filter: [
+ {
+ type: "string" as const,
+ value: "1",
+ column: "User ID",
+ operator: "contains" as const,
+ },
+ ],
+ orderBy: {
+ column: "timestamp",
+ order: "DESC" as const,
+ },
+ },
+ },
+ };
+
+ await handleBatchActionJob(payload);
+
+ await waitForExpect(async () => {
+ try {
+ const queue = getQueue(QueueName.CreateEvalQueue);
+
+ const jobs = await queue?.getJobs();
+
+ expect(jobs).toHaveLength(1);
+
+ if (!jobs) {
+ throw new Error("No jobs found");
+ }
+
+ const job = jobs[0];
+
+ expect(job.name).toBe("create-eval-job");
+ expect(job.data.payload.projectId).toBe(projectId);
+ expect(job.data.payload.traceId).toBe(traceId1);
+ expect(job.data.payload.configId).toBe(configId);
+ } catch (e) {
+ logger.error(e);
+ throw e;
+ }
+ });
+ });
+
+ it("should create eval jobs for historic datasets", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traceId1 = randomUUID();
+ const traceId2 = randomUUID();
+
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: traceId1,
+ user_id: "user1",
+ timestamp: new Date().getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ id: traceId2,
+ user_id: "user2",
+ timestamp: new Date().getTime(),
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ const datasetName = randomUUID();
+ const dataset = await prisma.dataset.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ name: datasetName,
+ },
+ });
+
+ const datasetItem1 = await prisma.datasetItem.create({
+ data: {
+ id: randomUUID(),
+ datasetId: dataset.id,
+ input: "Hello, world!",
+ projectId,
+ },
+ });
+
+ const datasetItem2 = await prisma.datasetItem.create({
+ data: {
+ id: randomUUID(),
+ datasetId: dataset.id,
+ input: "Hello, world!",
+ projectId,
+ },
+ });
+
+ const runId = randomUUID();
+
+ const datasetRun = await prisma.datasetRuns.create({
+ data: {
+ id: runId,
+ datasetId: dataset.id,
+ projectId,
+ name: "test-run",
+ },
+ });
+
+ await prisma.datasetRunItems.create({
+ data: {
+ id: randomUUID(),
+ datasetItemId: datasetItem1.id,
+ projectId,
+ traceId: traceId1,
+ datasetRunId: runId,
+ },
+ });
+
+ await prisma.datasetRunItems.create({
+ data: {
+ id: randomUUID(),
+ datasetItemId: datasetItem2.id,
+ projectId,
+ traceId: traceId2,
+ datasetRunId: runId,
+ },
+ });
+
+ const templateId = randomUUID();
+
+ await prisma.evalTemplate.create({
+ data: {
+ id: templateId,
+ projectId,
+ name: "test-template",
+ version: 1,
+ prompt: "Please evaluate toxicity {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ provider: "openai",
+ modelParams: {},
+ outputSchema: {
+ reasoning: "Please explain your reasoning",
+ score: "Please provide a score between 0 and 1",
+ },
+ },
+ });
+
+ const configId = randomUUID();
+ await prisma.jobConfiguration.create({
+ data: {
+ id: configId,
+ projectId,
+ filter: [
+ {
+ type: "stringOptions" as const,
+ value: [dataset.id],
+ column: "Dataset",
+ operator: "any of" as const,
+ },
+ ],
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "dataset",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ evalTemplateId: templateId,
+ },
+ });
+
+ const queue = getQueue(QueueName.CreateEvalQueue);
+ await queue?.obliterate({ force: true });
+
+ const payload = {
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.BatchActionProcessingJob as const,
+ payload: {
+ projectId,
+ actionId: "eval-create" as const,
+ targetObject: "dataset" as const,
+ configId,
+ cutoffCreatedAt: new Date(),
+ query: {
+ filter: [
+ {
+ type: "stringOptions" as const,
+ value: [dataset.id],
+ column: "Dataset",
+ operator: "any of" as const,
+ },
+ ],
+ orderBy: {
+ column: "timestamp",
+ order: "DESC" as const,
+ },
+ },
+ },
+ };
+
+ await handleBatchActionJob(payload);
+
+ await waitForExpect(async () => {
+ try {
+ const jobs = await queue?.getJobs();
+ expect(jobs).toHaveLength(2);
+ const jobTraceIds = jobs?.map((job) => job.data.payload.traceId);
+ expect(jobTraceIds).toContain(traceId1);
+ expect(jobTraceIds).toContain(traceId2);
+
+ const jobDatasetIds = jobs?.map(
+ (job) => job.data.payload.datasetItemId,
+ );
+ expect(jobDatasetIds).toContain(datasetItem1.id);
+ expect(jobDatasetIds).toContain(datasetItem2.id);
+ const configIds = jobs?.map((job) => job.data.payload.configId);
+ expect(configIds).toContain(configId);
+ } catch (e) {
+ logger.error(e);
+ throw e;
+ }
+ });
+ });
});
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 0c453adad1..8ad89d42ad 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -27,6 +27,8 @@ import { OpenAIServer } from "./network";
import { afterEach } from "node:test";
import {
convertDateToClickhouseDateTime,
+ createTrace,
+ createTracesCh,
upsertObservation,
upsertTrace,
} from "@langfuse/shared/src/server";
@@ -753,8 +755,166 @@ describe("eval service tests", () => {
expect(jobs[0].start_time).not.toBeNull();
expect(jobs[0].end_time).not.toBeNull();
}, 10_000);
+
+ test("does not create eval job for existing traces if time scope is EXISTING but handler enforces NEW only", async () => {
+ const traceId = randomUUID();
+
+ const trace = createTrace({
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ id: traceId,
+ });
+
+ await createTracesCh([trace]);
+
+ const jobConfiguration = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ timeScope: ["EXISTING"],
+ },
+ });
+
+ // this one should not be selected for eval as it was not provided via the event.
+ const jobConfiguration2 = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ timeScope: ["NEW"],
+ },
+ });
+
+ const payload = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ configId: jobConfiguration.id,
+ };
+
+ await createEvalJobs({
+ event: payload,
+ enforcedJobTimeScope: "NEW", // the config must contain NEW
+ });
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("job_configuration_id", "in", [
+ jobConfiguration.id,
+ jobConfiguration2.id,
+ ])
+ .where("job_input_trace_id", "=", traceId)
+ .execute();
+
+ expect(jobs.length).toBe(0);
+ }, 10_000);
});
+ test("does create eval for trace which is way in the past if timestamp is provided", async () => {
+ const traceId = randomUUID();
+
+ const timestamp = new Date(Date.now() - 1000 * 60 * 60 * 24 * 365 * 1);
+ const trace = createTrace({
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ id: traceId,
+ timestamp: timestamp.getTime(),
+ });
+
+ await createTracesCh([trace]);
+
+ const jobConfiguration = await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ timeScope: ["NEW"],
+ },
+ });
+
+ const payload = {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ configId: jobConfiguration.id,
+ timestamp: timestamp,
+ };
+
+ await createEvalJobs({
+ event: payload,
+ enforcedJobTimeScope: "NEW", // the config must contain NEW
+ });
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .where("job_configuration_id", "in", [jobConfiguration.id])
+ .where("job_input_trace_id", "=", traceId)
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ }, 10_000);
+
+ test("creates eval for trace with timestamp in the future", async () => {
+ const traceId = randomUUID();
+
+ await prisma.jobConfiguration.create({
+ data: {
+ id: randomUUID(),
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ filter: JSON.parse("[]"),
+ jobType: "EVAL",
+ delay: 0,
+ sampling: new Decimal("1"),
+ targetObject: "trace",
+ scoreName: "score",
+ variableMapping: JSON.parse("[]"),
+ timeScope: ["NEW"],
+ },
+ });
+
+ const trace = createTrace({
+ project_id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ id: traceId,
+ timestamp: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 1).getTime(),
+ });
+
+ await createTracesCh([trace]);
+
+ await createEvalJobs({
+ event: {
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ traceId: traceId,
+ },
+ });
+
+ const jobs = await kyselyPrisma.$kysely
+ .selectFrom("job_executions")
+ .selectAll()
+ .where("project_id", "=", "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a")
+ .execute();
+
+ expect(jobs.length).toBe(1);
+ }, 10_000);
+
describe("execute evals", () => {
test("evals a valid 'trace' event", async () => {
openAIServer.respondWithDefault();
diff --git a/worker/src/__tests__/network.ts b/worker/src/__tests__/network.ts
index dd0d2fb7fe..5bda2da5e1 100644
--- a/worker/src/__tests__/network.ts
+++ b/worker/src/__tests__/network.ts
@@ -62,14 +62,14 @@ function MinioCompletionHandler() {
}
function ClickHouseCompletionHandler() {
- return http.all("http://localhost:8123*", async (request) => {
+ return http.all("http://localhost:8123*", async () => {
logger.info("clickhouse handler");
return passthrough();
});
}
function AzuriteCompletionHandler() {
- return http.all("http://localhost:10000*", async (request) => {
+ return http.all("http://localhost:10000*", async () => {
logger.info("handle azurite");
return passthrough();
});
diff --git a/worker/src/app.ts b/worker/src/app.ts
index d959c13cd8..55efcb0411 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -9,6 +9,7 @@ import MessageResponse from "./interfaces/MessageResponse";
require("dotenv").config();
import {
+ evalJobCreatorQueueProcessor,
evalJobDatasetCreatorQueueProcessor,
evalJobExecutorQueueProcessor,
evalJobTraceCreatorQueueProcessor,
@@ -78,6 +79,16 @@ if (env.QUEUE_CONSUMER_TRACE_UPSERT_QUEUE_IS_ENABLED === "true") {
);
}
+if (env.QUEUE_CONSUMER_CREATE_EVAL_QUEUE_IS_ENABLED === "true") {
+ WorkerManager.register(
+ QueueName.CreateEvalQueue,
+ evalJobCreatorQueueProcessor,
+ {
+ concurrency: env.LANGFUSE_EVAL_CREATOR_WORKER_CONCURRENCY,
+ },
+ );
+}
+
if (env.LANGFUSE_S3_CORE_DATA_EXPORT_IS_ENABLED === "true") {
// Instantiate the queue to trigger scheduled jobs
CoreDataS3ExportQueue.getInstance();
diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.ts
index 19a0b73bb8..a4cc670d18 100644
--- a/worker/src/ee/evaluation/evalService.ts
+++ b/worker/src/ee/evaluation/evalService.ts
@@ -21,6 +21,7 @@ import {
TraceQueueEventType,
StorageService,
StorageServiceFactory,
+ CreateEvalQueueEventType,
} from "@langfuse/shared/src/server";
import {
availableTraceEvalVariables,
@@ -36,6 +37,7 @@ import {
evalDatasetFormFilterCols,
availableDatasetEvalVariables,
variableMapping,
+ JobTimeScope,
} from "@langfuse/shared";
import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";
import { backOff } from "exponential-backoff";
@@ -66,16 +68,37 @@ const getS3StorageServiceClient = (bucketName: string): StorageService => {
// there might be multiple eval jobs to create for a single trace
export const createEvalJobs = async ({
event,
+ enforcedJobTimeScope,
}: {
- event: TraceQueueEventType | DatasetRunItemUpsertEventType;
+ event:
+ | TraceQueueEventType
+ | DatasetRunItemUpsertEventType
+ | CreateEvalQueueEventType;
+ enforcedJobTimeScope?: JobTimeScope;
}) => {
// Fetch all configs for a given project. Those may be dataset or trace configs.
- const configs = await kyselyPrisma.$kysely
+ let configsQuery = kyselyPrisma.$kysely
.selectFrom("job_configurations")
.selectAll()
.where(sql.raw("job_type::text"), "=", "EVAL")
- .where("project_id", "=", event.projectId)
- .execute();
+ .where("project_id", "=", event.projectId);
+
+ if ("configId" in event) {
+ // if configid is set in the event, we only want to fetch the one config
+ configsQuery = configsQuery.where("id", "=", event.configId);
+ }
+
+ // for dataset_run_item_upsert queue + trace queue, we do not want to execute evals on configs,
+ // which were only allowed to run on historic data. Hence, we need to filter all configs which have "NEW" in the time_scope column.
+ if (enforcedJobTimeScope) {
+ configsQuery = configsQuery.where(
+ "time_scope",
+ "@>",
+ sql<string[]>`ARRAY[${enforcedJobTimeScope}]`,
+ );
+ }
+
+ const configs = await configsQuery.execute();
if (configs.length === 0) {
logger.debug("No evaluation jobs found for project", event.projectId);
@@ -99,7 +122,7 @@ export const createEvalJobs = async ({
const traceExists = await checkTraceExists(
event.projectId,
event.traceId,
- new Date(),
+ "timestamp" in event ? new Date(event.timestamp) : new Date(),
config.target_object === "trace" ? validatedFilter : [],
);
@@ -137,7 +160,6 @@ export const createEvalJobs = async ({
AND dri.trace_id = ${event.traceId}
${condition}
`);
-
datasetItem = datasetItems.shift();
}
}
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 6f1fce59d7..6515686009 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -45,6 +45,10 @@ const EnvSchema = z.object({
.positive()
.default(24),
BATCH_ACTION_EXPORT_ROW_LIMIT: z.coerce.number().positive().default(50_000),
+ LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT: z.coerce
+ .number()
+ .positive()
+ .default(50_000),
EMAIL_FROM_ADDRESS: z.string().optional(),
SMTP_CONNECTION_URL: z.string().optional(),
LANGFUSE_INGESTION_QUEUE_PROCESSING_CONCURRENCY: z.coerce
@@ -146,6 +150,9 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_TRACE_UPSERT_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ QUEUE_CONSUMER_CREATE_EVAL_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("true"),
QUEUE_CONSUMER_TRACE_DELETE_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 2dfb6b7a91..cdf5e4d58e 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -1,6 +1,8 @@
import {
BatchActionProcessingEventType,
+ CreateEvalQueue,
logger,
+ QueueJobs,
QueueName,
TQueueJobTypes,
} from "@langfuse/shared/src/server";
@@ -16,6 +18,8 @@ import { env } from "../../env";
import { Job } from "bullmq";
import { processAddToQueue } from "./processAddToQueue";
import { processPostgresTraceDelete } from "../traces/processPostgresTraceDelete";
+import { prisma } from "@langfuse/shared/src/db";
+import { randomUUID } from "node:crypto";
const CHUNK_SIZE = 1000;
const convertDatesInQuery = (query: BatchActionQuery) => {
@@ -61,57 +65,181 @@ async function processActionChunk(
}
}
+export type TraceRowForEval = {
+ id: string;
+ projectId: string;
+ timestamp: Date;
+};
+
+export type DatasetRunItemRowForEval = {
+ id: string;
+ projectId: string;
+ datasetItemId: string;
+ traceId: string;
+ observationId: string | null;
+};
+const assertIsTracesTableRecord = (
+ element: unknown,
+): element is TraceRowForEval => {
+ return (
+ typeof element === "object" &&
+ element !== null &&
+ "id" in element &&
+ "projectId" in element &&
+ "timestamp" in element
+ );
+};
+
+const assertIsDatasetRunItemTableRecord = (
+ element: unknown,
+): element is DatasetRunItemRowForEval => {
+ return (
+ typeof element === "object" &&
+ element !== null &&
+ "id" in element &&
+ "projectId" in element &&
+ "datasetItemId" in element &&
+ "traceId" in element &&
+ "observationId" in element
+ );
+};
+
export const handleBatchActionJob = async (
- batchActionJob: Job<TQueueJobTypes[QueueName.BatchActionQueue]>,
+ batchActionJob: Job<TQueueJobTypes[QueueName.BatchActionQueue]>["data"],
) => {
const batchActionEvent: BatchActionProcessingEventType =
- batchActionJob.data.payload;
- const {
- projectId,
- actionId,
- tableName,
- query,
- cutoffCreatedAt,
- targetId,
- type,
- } = batchActionEvent;
-
- if (type === BatchActionType.Create && !targetId) {
- throw new Error(`Target ID is required for create action`);
- }
+ batchActionJob.payload;
+
+ const { actionId } = batchActionEvent;
+
+ if (
+ actionId === "trace-delete" ||
+ actionId === "trace-add-to-annotation-queue"
+ ) {
+ const { projectId, tableName, query, cutoffCreatedAt, targetId, type } =
+ batchActionEvent;
- const dbReadStream = await getDatabaseReadStream({
- projectId: projectId,
- cutoffCreatedAt: new Date(cutoffCreatedAt),
- ...convertDatesInQuery(query),
- tableName: tableName as unknown as BatchExportTableName,
- exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,
- });
-
- // Process stream in database-sized batches
- // 1. Read all records
- const records: any[] = [];
- for await (const record of dbReadStream) {
- if (record?.id) {
- records.push(record);
+ if (type === BatchActionType.Create && !targetId) {
+ throw new Error(`Target ID is required for create action`);
}
- }
- // 2. Process in chunks
- for (let i = 0; i < records.length; i += CHUNK_SIZE) {
- const batch = records.slice(i, i + CHUNK_SIZE);
+ const dbReadStream = await getDatabaseReadStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(cutoffCreatedAt),
+ ...convertDatesInQuery(query),
+ tableName: tableName as unknown as BatchExportTableName,
+ exportLimit: env.BATCH_ACTION_EXPORT_ROW_LIMIT,
+ });
+
+ // Process stream in database-sized batches
+ // 1. Read all records
+ const records: any[] = [];
+ for await (const record of dbReadStream) {
+ if (record?.id) {
+ records.push(record);
+ }
+ }
- await processActionChunk(
- actionId,
- batch.map((r) => r.id),
- projectId,
- targetId,
+ // 2. Process in chunks
+ for (let i = 0; i < records.length; i += CHUNK_SIZE) {
+ const batch = records.slice(i, i + CHUNK_SIZE);
+
+ await processActionChunk(
+ actionId,
+ batch.map((r) => r.id),
+ projectId,
+ targetId,
+ );
+ }
+ } else if (actionId === "eval-create") {
+ // if a user wants to apply evals for historic traces or dataset runs, we do this here.
+ // 1) we fetch data from the database, 2) we create eval executions in batches, 3) we create eval execution jobs for each batch
+ const { projectId, query, targetObject, configId, cutoffCreatedAt } =
+ batchActionEvent;
+
+ const config = await prisma.jobConfiguration.findUnique({
+ where: {
+ id: configId,
+ projectId: projectId,
+ },
+ });
+
+ if (!config) {
+ throw new Error("Eval config not found");
+ }
+
+ const dbReadStream = await getDatabaseReadStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(cutoffCreatedAt),
+ ...convertDatesInQuery(query),
+ tableName:
+ targetObject === "trace"
+ ? BatchExportTableName.Traces
+ : BatchExportTableName.DatasetRunItems,
+ exportLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
+ });
+
+ const evalCreatorQueue = CreateEvalQueue.getInstance();
+ if (!evalCreatorQueue) {
+ logger.error("CreateEvalQueue is not initialized");
+ return;
+ }
+
+ let count = 0;
+ for await (const record of dbReadStream) {
+ if (targetObject === "trace" && assertIsTracesTableRecord(record)) {
+ const payload = {
+ projectId: record.projectId,
+ traceId: record.id,
+ configId: configId,
+ timestamp: new Date(record.timestamp),
+ };
+
+ await evalCreatorQueue.add(QueueJobs.CreateEvalJob, {
+ payload,
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.CreateEvalJob as const,
+ });
+ count++;
+ } else if (
+ targetObject === "dataset" &&
+ assertIsDatasetRunItemTableRecord(record)
+ ) {
+ const payload = {
+ projectId: record.projectId,
+ datasetItemId: record.datasetItemId,
+ traceId: record.traceId,
+ observationId: record.observationId ?? undefined,
+ configId: configId,
+ //We need to set this to be able to fetch traces from the past. We cannot infer from the dataset run when the trace was created.
+ timestamp: new Date("2020-01-01"),
+ };
+
+ await evalCreatorQueue.add(
+ QueueJobs.CreateEvalJob,
+ {
+ payload,
+ id: randomUUID(),
+ timestamp: new Date(),
+ name: QueueJobs.CreateEvalJob as const,
+ },
+ { delay: config.delay },
+ );
+ count++;
+ } else {
+ logger.error(
+ "Record is not a valid traces table or dataset record",
+ record,
+ );
+ }
+ }
+ logger.info(
+ `Batch action job {${count} elements} completed, projectId: ${batchActionJob.payload.projectId}, actionId: ${actionId}`,
);
}
- logger.info("Batch action job completed", {
- projectId,
- actionId,
- tableName,
- });
+ logger.info(
+ `Batch action job completed, projectId: ${batchActionJob.payload.projectId}, actionId: ${actionId}`,
+ );
};
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index 5f04c6914a..69072dba87 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -36,12 +36,14 @@ const tableNameToTimeFilterColumn = {
sessions: "createdAt",
traces: "timestamp",
generations: "startTime",
+ dataset_run_items: "createdAt",
};
const tableNameToTimeFilterColumnCh = {
sessions: "createdAt",
traces: "timestamp",
generations: "startTime",
+ dataset_run_items: "createdAt",
};
const isGenerationTimestampFilter = (
@@ -325,8 +327,52 @@ export const getDatabaseReadStream = async ({
exportLimit,
);
}
+
+ case "dataset_run_items": {
+ return new DatabaseReadStream<unknown>(
+ async (pageSize: number, offset: number) => {
+ const items = await prisma.$queryRaw<
+ Array<{
+ id: string;
+ project_id: string;
+ dataset_item_id: string;
+ trace_id: string;
+ observation_id: string | null;
+ created_at: Date;
+ updated_at: Date;
+ dataset_name: string;
+ }>
+ >`
+ SELECT dri.*, d.name as dataset_name
+
+ FROM dataset_run_items dri
+ JOIN dataset_items di ON dri.dataset_item_id = di.id AND dri.project_id = di.project_id
+ JOIN datasets d ON di.dataset_id = d.id AND d.project_id = dri.project_id
+ WHERE dri.project_id = ${projectId}
+ AND dri.created_at < ${cutoffCreatedAt}
+
+ ORDER BY dri.created_at DESC
+ LIMIT ${pageSize}
+ OFFSET ${offset}
+ `;
+
+ return items.map((item) => ({
+ id: item.id,
+ projectId: item.project_id,
+ datasetItemId: item.dataset_item_id,
+ traceId: item.trace_id,
+ observationId: item.observation_id,
+ createdAt: item.created_at,
+ updatedAt: item.updated_at,
+ datasetName: item.dataset_name,
+ }));
+ },
+ 1000,
+ exportLimit,
+ );
+ }
default:
- throw new Error("Invalid table name: " + tableName);
+ throw new Error(`Unhandled table case: ${tableName}`);
}
};
diff --git a/worker/src/queues/batchActionQueue.ts b/worker/src/queues/batchActionQueue.ts
index 7070537ec7..a1e652abb6 100644
--- a/worker/src/queues/batchActionQueue.ts
+++ b/worker/src/queues/batchActionQueue.ts
@@ -7,9 +7,13 @@ export const batchActionQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.BatchActionQueue]>,
) => {
try {
- logger.info("Executing Batch Action Job", job.data.payload);
- await handleBatchActionJob(job);
- logger.info("Finished Batch Action Job", job.data.payload);
+ logger.info(
+ `Executing Batch Action job ${JSON.stringify(job.data.payload.actionId)}`,
+ );
+ await handleBatchActionJob(job.data);
+ logger.info(
+ `Finished Batch Action Job ${JSON.stringify(job.data.payload.actionId)}`,
+ );
return true;
} catch (e) {
diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.ts
index 6676c429e8..77f926e119 100644
--- a/worker/src/queues/evalQueue.ts
+++ b/worker/src/queues/evalQueue.ts
@@ -17,7 +17,10 @@ export const evalJobTraceCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.TraceUpsert]>,
) => {
try {
- await createEvalJobs({ event: job.data.payload });
+ await createEvalJobs({
+ event: job.data.payload,
+ enforcedJobTimeScope: "NEW", // we must not execute evals which are intended for existing data only.
+ });
return true;
} catch (e) {
logger.error(
@@ -33,7 +36,10 @@ export const evalJobDatasetCreatorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.DatasetRunItemUpsert]>,
) => {
try {
- await createEvalJobs({ event: job.data.payload });
+ await createEvalJobs({
+ event: job.data.payload,
+ enforcedJobTimeScope: "NEW", // we must not execute evals which are intended for existing data only.
+ });
return true;
} catch (e) {
logger.error(
@@ -45,6 +51,24 @@ export const evalJobDatasetCreatorQueueProcessor = async (
}
};
+export const evalJobCreatorQueueProcessor = async (
+ job: Job<TQueueJobTypes[QueueName.CreateEvalQueue]>,
+) => {
+ try {
+ await createEvalJobs({
+ event: job.data.payload,
+ });
+ return true;
+ } catch (e) {
+ logger.error(
+ `Failed to create evaluation jobs: ${JSON.stringify(job.data.payload)}`,
+ e,
+ );
+ traceException(e);
+ throw e;
+ }
+};
+
export const evalJobExecutorQueueProcessor = async (
job: Job<TQueueJobTypes[QueueName.EvaluationExecution]>,
) => {