Skip to content

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

feat(evals): add historical / batched single observation evals (#12040)

Hassieb Pakzad3a0809287fd9
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.ts
index 27f944ffa2..26a04ee62e 100644
--- a/packages/shared/src/features/batchAction/types.ts
+++ b/packages/shared/src/features/batchAction/types.ts
@@ -24,6 +24,7 @@ export enum ActionId {
SessionAddToAnnotationQueue = "session-add-to-annotation-queue",
ObservationAddToAnnotationQueue = "observation-add-to-annotation-queue",
ObservationAddToDataset = "observation-add-to-dataset",
+ ObservationBatchEvaluation = "observation-run-batched-evaluation",
}
const ActionIdSchema = z.nativeEnum(ActionId);
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index c180bd149f..83e3f3458f 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -260,6 +260,36 @@ const FIELD_SETS = {
"traceName",
"parentObservationId",
],
+
+ eval: [
+ "id",
+ "traceId",
+ "projectId",
+ "parentObservationId",
+ "type",
+ "name",
+ "environment",
+ "version",
+ "level",
+ "statusMessage",
+ "traceName",
+ "userId",
+ "sessionId",
+ "tags",
+ "release",
+ "providedModelName",
+ "modelParameters",
+ "promptId",
+ "promptName",
+ "promptVersion",
+ "providedUsageDetails",
+ "usageDetails",
+ "providedCostDetails",
+ "costDetails",
+ "toolDefinitions",
+ "toolCalls",
+ "toolCallNames",
+ ],
} as const;
export type FieldSetName = keyof typeof FIELD_SETS;
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 0aa8c93827..d49e1be57d 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -1,6 +1,7 @@
import { z } from "zod/v4";
import { eventTypes } from "./ingestion/types";
import {
+ ActionId,
BatchActionQuerySchema,
BatchActionType,
} from "../features/batchAction/types";
@@ -189,6 +190,14 @@ export const BatchActionProcessingEventSchema = z.discriminatedUnion(
config: ObservationAddToDatasetConfigSchema,
type: z.enum(BatchActionType),
}),
+ z.object({
+ actionId: z.literal(ActionId.ObservationBatchEvaluation),
+ projectId: z.string(),
+ query: BatchActionQuerySchema,
+ cutoffCreatedAt: z.date(),
+ batchActionId: z.string(),
+ evaluatorIds: z.array(z.string()),
+ }),
],
);
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 7f7bb28be1..adb9de4961 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -2850,3 +2850,53 @@ export const hasAnySessionFromEventsTable = async (
return rows.length > 0;
};
+
+export const getAvgCostByEvaluatorIds = async (
+ projectId: string,
+ evaluatorIds: string[],
+): Promise<
+ Array<{ evaluatorId: string; avgCost: number; executionCount: number }>
+> => {
+ if (evaluatorIds.length === 0) return [];
+
+ const builder = new EventsAggQueryBuilder({
+ projectId,
+ groupByColumn:
+ "mapFromArrays(e.metadata_names, e.metadata_values)['job_configuration_id']",
+ selectExpression: [
+ "mapFromArrays(e.metadata_names, e.metadata_values)['job_configuration_id'] as evaluator_id",
+ "avg(e.total_cost) as avg_cost",
+ "count(*) as execution_count",
+ ].join(", "),
+ })
+ .whereRaw("e.type = 'GENERATION'")
+ .whereRaw("has(e.metadata_names, 'job_configuration_id')")
+ .whereRaw(
+ "mapFromArrays(e.metadata_names, e.metadata_values)['job_configuration_id'] IN ({evaluatorIds: Array(String)})",
+ { evaluatorIds },
+ )
+ .whereRaw("e.start_time > today() - 7");
+
+ const { query, params } = builder.buildWithParams();
+
+ const rows = await queryClickhouse<{
+ evaluator_id: string;
+ avg_cost: string;
+ execution_count: string;
+ }>({
+ query,
+ params,
+ tags: {
+ feature: "evals",
+ type: "events",
+ kind: "analytic",
+ projectId,
+ },
+ });
+
+ return rows.map((row) => ({
+ evaluatorId: row.evaluator_id,
+ avgCost: Number(row.avg_cost),
+ executionCount: Number(row.execution_count),
+ }));
+};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b3ca29fac5..40bf4e3aa3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -403,7 +403,7 @@ importers:
'@langchain/core':
specifier: ^1.1.17
- version: 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
+ version: 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
'@langfuse/ee':
specifier: workspace:*
version: link:../ee
@@ -586,7 +586,7 @@ importers:
ai:
specifier: ^3.4.9
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
@@ -652,7 +652,7 @@ importers:
version: 0.27.4
langchain:
specifier: ^1.2.15
langfuse:
specifier: 3.38.4
version: 3.38.4
@@ -803,7 +803,7 @@ importers:
'@testing-library/jest-dom':
specifier: ^6.4.6
'@testing-library/react':
specifier: ^15.0.7
@@ -993,6 +993,9 @@ importers:
lodash:
specifier: ^4.17.23
version: 4.17.23
+ p-limit:
+ specifier: ^7.3.0
+ version: 7.3.0
pg:
specifier: ^8.13.0
version: 8.13.0
@@ -10259,6 +10262,10 @@ packages:
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-7cIXg/Z0M5WZRblrsOla88S4wAK+zOQQWeBYfV3qJuJXMr+LnbYjaadrFaS0JILfEDPVqHyKnZ1Z/1d6J9VVUw==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
engines: {node: '>=8'}
@@ -12533,6 +12540,10 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==}
+ engines: {node: '>=12.20'}
+
resolution: {integrity: sha512-cYVsTjKl8b+FrnidjibDWskAv7UKOfcwaVZdp/it9n1s9fU3IkgDbhdIRKCW4JDsAlECJY0ytoVPT3sK6kideA==}
engines: {node: '>=18'}
@@ -15973,14 +15984,14 @@ snapshots:
transitivePeerDependencies:
- aws-crt
- '@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))':
dependencies:
'@cfworker/json-schema': 4.1.1
ansi-styles: 5.2.0
camelcase: 6.3.0
decamelize: 1.2.0
js-tiktoken: 1.0.21
- langsmith: 0.4.12(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
+ langsmith: 0.4.12(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
mustache: 4.2.0
p-queue: 6.6.2
uuid: 10.0.0
@@ -16035,9 +16046,9 @@ snapshots:
- '@langchain/core'
- supports-color
- '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))':
+ '@langchain/[email protected](@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))':
dependencies:
- '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
+ '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
uuid: 10.0.0
@@ -16045,13 +16056,13 @@ snapshots:
'@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
uuid: 10.0.0
dependencies:
p-queue: 9.1.0
p-retry: 7.1.1
uuid: 13.0.0
optionalDependencies:
- '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
+ '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
react: 19.2.3
react-dom: 19.2.3([email protected])
@@ -16065,11 +16076,11 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3([email protected])
dependencies:
- '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
- '@langchain/langgraph-checkpoint': 1.0.0(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))
- '@langchain/langgraph-sdk': 1.5.5(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))([email protected]([email protected]))([email protected])
+ '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
+ '@langchain/langgraph-checkpoint': 1.0.0(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))
+ '@langchain/langgraph-sdk': 1.5.5(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))([email protected]([email protected]))([email protected])
'@standard-schema/spec': 1.1.0
uuid: 10.0.0
zod: 3.25.76
@@ -19314,7 +19325,7 @@ snapshots:
lz-string: 1.5.0
pretty-format: 27.5.1
dependencies:
'@adobe/css-tools': 4.4.0
'@babel/runtime': 7.24.7
@@ -20174,7 +20185,7 @@ snapshots:
clean-stack: 2.2.0
indent-string: 4.0.0
dependencies:
'@ai-sdk/provider': 0.0.24
'@ai-sdk/provider-utils': 1.0.20([email protected])
@@ -20191,7 +20202,7 @@ snapshots:
secure-json-parse: 2.7.0
zod-to-json-schema: 3.23.2([email protected])
optionalDependencies:
- openai: 4.104.0([email protected])
react: 19.2.3
sswr: 2.1.0([email protected])
svelte: 4.2.19
@@ -21584,7 +21595,7 @@ snapshots:
dependencies:
eslint: 9.39.2([email protected])
eslint-plugin-n: 16.6.2([email protected]([email protected]))
eslint-plugin-promise: 6.6.0([email protected]([email protected]))
@@ -21617,22 +21628,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@nolyfill/is-core-module': 1.0.39
- debug: 4.4.3
- eslint: 9.39.2([email protected])
- get-tsconfig: 4.13.0
- is-bun-module: 2.0.0
- stable-hash: 0.0.5
- tinyglobby: 0.2.15
- unrs-resolver: 1.11.1
- optionalDependencies:
- transitivePeerDependencies:
- - supports-color
- optional: true
-
dependencies:
debug: 3.2.7
@@ -21644,17 +21639,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- debug: 3.2.7
- optionalDependencies:
- '@typescript-eslint/parser': 8.50.1([email protected]([email protected]))([email protected])
- eslint: 9.39.2([email protected])
- eslint-import-resolver-node: 0.3.9
- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))
@@ -21691,35 +21675,6 @@ snapshots:
- eslint-import-resolver-webpack
- supports-color
- dependencies:
- '@rtsao/scc': 1.1.0
- array-includes: 3.1.9
- array.prototype.findlastindex: 1.2.6
- array.prototype.flat: 1.3.3
- array.prototype.flatmap: 1.3.3
- debug: 3.2.7
- doctrine: 2.1.0
- eslint: 9.39.2([email protected])
- eslint-import-resolver-node: 0.3.9
- hasown: 2.0.2
- is-core-module: 2.16.1
- is-glob: 4.0.3
- minimatch: 3.1.2
- object.fromentries: 2.0.8
- object.groupby: 1.0.3
- object.values: 1.2.1
- semver: 6.3.1
- string.prototype.trimend: 1.0.9
- tsconfig-paths: 3.15.0
- optionalDependencies:
- '@typescript-eslint/parser': 8.50.1([email protected]([email protected]))([email protected])
- transitivePeerDependencies:
- - eslint-import-resolver-typescript
- - eslint-import-resolver-webpack
- - supports-color
-
dependencies:
aria-query: 5.3.2
@@ -23558,12 +23513,12 @@ snapshots:
dependencies:
- '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
- '@langchain/langgraph-checkpoint': 1.0.0(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])))
- langsmith: 0.4.12(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected]))
+ '@langchain/core': 1.1.18(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
+ '@langchain/langgraph-checkpoint': 1.0.0(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected])))
+ langsmith: 0.4.12(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))
uuid: 10.0.0
zod: 3.25.76
transitivePeerDependencies:
@@ -23614,7 +23569,7 @@ snapshots:
dependencies:
langfuse-core: 3.38.6
dependencies:
'@types/uuid': 10.0.0
chalk: 4.1.2
@@ -23626,7 +23581,7 @@ snapshots:
'@opentelemetry/api': 1.9.0
'@opentelemetry/exporter-trace-otlp-proto': 0.53.0(@opentelemetry/[email protected])
'@opentelemetry/sdk-trace-base': 1.26.0(@opentelemetry/[email protected])
- openai: 4.104.0([email protected])
dependencies:
@@ -24676,7 +24631,7 @@ snapshots:
is-docker: 2.2.1
is-wsl: 2.2.0
dependencies:
'@types/node': 18.19.123
'@types/node-fetch': 2.6.13
@@ -24686,6 +24641,7 @@ snapshots:
formdata-node: 4.4.1
node-fetch: 2.7.0
optionalDependencies:
+ ws: 8.18.3
zod: 3.25.62
transitivePeerDependencies:
- encoding
@@ -24761,6 +24717,10 @@ snapshots:
dependencies:
yocto-queue: 0.1.0
+ dependencies:
+ yocto-queue: 1.2.2
+
dependencies:
p-limit: 2.3.0
@@ -27262,6 +27222,8 @@ snapshots:
+
diff --git a/web/src/components/table/peek/peek-evaluator-config-detail.tsx b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
index 8807cfd07a..7945981ba3 100644
--- a/web/src/components/table/peek/peek-evaluator-config-detail.tsx
+++ b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
@@ -20,6 +20,7 @@ import { cn } from "@/src/utils/tailwind";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { api } from "@/src/utils/api";
import { LegacyEvalCallout } from "@/src/features/evals/components/legacy-eval-callout";
+import { isLegacyEvalTarget } from "@/src/features/evals/utils/typeHelpers";
export const PeekViewEvaluatorConfigDetail = ({
projectId,
@@ -53,10 +54,12 @@ export const PeekViewEvaluatorConfigDetail = ({
isLive
className="max-h-8"
/>
- <DeactivateEvalConfig
- projectId={projectId}
- evalConfig={evalConfig}
- />
+ {isLegacyEvalTarget(evalConfig.targetObject) && (
+ <DeactivateEvalConfig
+ projectId={projectId}
+ evalConfig={evalConfig}
+ />
+ )}
</div>
</div>
<div className="flex items-center gap-2">
@@ -68,7 +71,8 @@ export const PeekViewEvaluatorConfigDetail = ({
<Switch
disabled={
!hasAccess ||
- (evalConfig?.timeScope?.length === 1 &&
+ (isLegacyEvalTarget(evalConfig.targetObject) &&
+ evalConfig?.timeScope?.length === 1 &&
evalConfig.timeScope[0] === "EXISTING")
}
checked={isEditMode}
diff --git a/web/src/components/ui/multi-select-combobox.tsx b/web/src/components/ui/multi-select-combobox.tsx
index f1ecf86918..da79a71216 100644
--- a/web/src/components/ui/multi-select-combobox.tsx
+++ b/web/src/components/ui/multi-select-combobox.tsx
@@ -21,6 +21,8 @@ interface MultiSelectComboboxProps<T> {
getItemKey: (item: T) => string;
disabled?: boolean;
onOpenChange?: (open: boolean) => void;
+ showSelectedItemsInInput?: boolean;
+ dropdownClassName?: string;
}
export function MultiSelectCombobox<T>({
@@ -37,6 +39,8 @@ export function MultiSelectCombobox<T>({
getItemKey,
disabled = false,
onOpenChange,
+ showSelectedItemsInInput = true,
+ dropdownClassName,
}: MultiSelectComboboxProps<T>) {
const [isInputFocused, setIsInputFocused] = useState(false);
const [showDropdown, setShowDropdown] = useState(false);
@@ -137,16 +141,24 @@ export function MultiSelectCombobox<T>({
<Search className="absolute left-2 top-2.5 z-10 h-4 w-4 text-muted-foreground" />
<div className="flex max-h-full flex-1 flex-wrap items-center gap-1 pl-8">
{/* Selected Items Pills */}
- {selectedItems.map((item) => (
- <div key={getItemKey(item)}>
- {renderSelectedItem(item, () => handleItemRemove(item))}
- </div>
- ))}
+ {showSelectedItemsInInput
+ ? selectedItems.map((item) => (
+ <div key={getItemKey(item)}>
+ {renderSelectedItem(item, () => handleItemRemove(item))}
+ </div>
+ ))
+ : null}
{/* Search Input */}
<Input
ref={inputRef}
type="text"
- placeholder={selectedItems.length === 0 ? placeholder : ""}
+ placeholder={
+ showSelectedItemsInInput
+ ? selectedItems.length === 0
+ ? placeholder
+ : ""
+ : placeholder
+ }
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
onFocus={handleInputFocus}
@@ -174,8 +186,12 @@ export function MultiSelectCombobox<T>({
{searchResults.length > 0 ||
(isLoading && previousResults.length > 0) ? (
<div
- className="absolute top-0 z-10 max-h-48 w-full overflow-y-auto rounded-md border bg-background shadow-md"
+ className={
+ dropdownClassName ??
+ "absolute top-0 z-10 max-h-48 w-full overflow-y-auto rounded-md border bg-background shadow-md"
+ }
onMouseDown={(e) => e.preventDefault()}
+ onWheel={(e) => e.stopPropagation()}
>
{(isLoading && previousResults.length > 0
? previousResults
diff --git a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
index 6a0b27e4a4..def6268879 100644
--- a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
+++ b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
@@ -37,7 +37,10 @@ const isItemLocked = (item: AnnotationQueueItem) => {
const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<
AnnotationQueueObjectType,
{
- actionId: Exclude<ActionId, ActionId.ObservationAddToDataset>;
+ actionId: Exclude<
+ ActionId,
+ ActionId.ObservationAddToDataset | ActionId.ObservationBatchEvaluation
+ >;
tableName: BatchTableNames;
}
> = {
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx
new file mode 100644
index 0000000000..6855830eaf
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx
@@ -0,0 +1,53 @@
+import { Card, CardContent } from "@/src/components/ui/card";
+import { Badge } from "@/src/components/ui/badge";
+import { Separator } from "@/src/components/ui/separator";
+import { EstimatedCostRow } from "./EstimatedCostRow";
+
+type ConfirmationStepProps = {
+ projectId: string;
+ displayCount: number;
+ evaluators: Array<{ id: string; name: string }>;
+};
+
+export function ConfirmationStep(props: ConfirmationStepProps) {
+ const { projectId, displayCount, evaluators } = props;
+
+ return (
+ <div className="space-y-4">
+ <Card>
+ <CardContent className="space-y-3 p-4 text-sm">
+ <div className="flex gap-2">
+ <span className="text-muted-foreground">Observations:</span>
+ <span className="font-medium">{displayCount}</span>
+ </div>
+
+ {evaluators.length > 0 && (
+ <div className="flex gap-2">
+ <span className="shrink-0 text-muted-foreground">
+ Evaluators:
+ </span>
+ <div className="flex flex-wrap gap-1">
+ {evaluators.map((e) => (
+ <Badge key={e.id} variant="secondary" className="text-xs">
+ {e.name}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <Separator />
+
+ <EstimatedCostRow
+ projectId={projectId}
+ evaluators={evaluators}
+ observationCount={displayCount}
+ />
+ </CardContent>
+ </Card>
+ <p className="text-xs text-muted-foreground">
+ Evaluations will run in the background.
+ </p>
+ </div>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx
new file mode 100644
index 0000000000..00d85ea184
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx
@@ -0,0 +1,133 @@
+import { useState } from "react";
+import { EvalTargetObject } from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { Button } from "@/src/components/ui/button";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { EvaluatorSelector } from "@/src/features/evals/components/evaluator-selector";
+import { EvaluatorForm } from "@/src/features/evals/components/evaluator-form";
+import { ChevronLeft } from "lucide-react";
+
+type CreateEvaluatorDialogProps = {
+ projectId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+export function CreateEvaluatorDialog(props: CreateEvaluatorDialogProps) {
+ const { projectId, open, onOpenChange } = props;
+ const [templateId, setTemplateId] = useState<string | null>(null);
+ const utils = api.useUtils();
+
+ const templatesQuery = api.evals.allTemplates.useQuery(
+ {
+ projectId,
+ limit: 500,
+ page: 0,
+ },
+ {
+ enabled: open,
+ },
+ );
+
+ const handleClose = (isOpen: boolean) => {
+ onOpenChange(isOpen);
+ if (!isOpen) {
+ setTemplateId(null);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={handleClose}>
+ <DialogContent className="max-h-[90vh] max-w-screen-md pb-0">
+ <DialogHeader>
+ <DialogTitle>
+ Create Evaluator for batched observation runs
+ </DialogTitle>
+ <DialogDescription>
+ This form creates an evaluator for batched observation runs.
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody className="max-h-[72vh] overflow-y-auto pb-0 pr-1">
+ {!templateId ? (
+ <div className="space-y-4 px-1 pb-1">
+ <p className="text-sm text-muted-foreground">
+ Select an evaluator template to configure.
+ </p>
+ {templatesQuery.isLoading ? (
+ <p className="text-sm text-muted-foreground">
+ Loading templates...
+ </p>
+ ) : templatesQuery.isError ? (
+ <p className="text-sm text-destructive">
+ Failed to load templates: {templatesQuery.error.message}
+ </p>
+ ) : (
+ <div className="max-h-[55vh] overflow-y-auto rounded-md border p-2">
+ <EvaluatorSelector
+ projectId={projectId}
+ evalTemplates={templatesQuery.data?.templates ?? []}
+ selectedTemplateId={undefined}
+ onTemplateSelect={(id) => setTemplateId(id)}
+ />
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="pb-1">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => setTemplateId(null)}
+ >
+ <ChevronLeft className="mr-1 h-4 w-4" />
+ Back to template selection
+ </Button>
+ <EvaluatorForm
+ useDialog
+ projectId={projectId}
+ evalTemplates={templatesQuery.data?.templates ?? []}
+ templateId={templateId}
+ hideTargetSelection
+ hidePreviewTable
+ defaultRunOnLive={false}
+ onFormSuccess={() => {
+ handleClose(false);
+ void utils.evals.jobConfigsByTarget.invalidate({
+ projectId,
+ targetObject: EvalTargetObject.EVENT,
+ });
+ showSuccessToast({
+ title: "Evaluator created",
+ description:
+ "Select it in the previous step to run it on selected observations.",
+ });
+ }}
+ preprocessFormValues={(values) => ({
+ ...values,
+ target: EvalTargetObject.EVENT,
+ timeScope: ["NEW"],
+ ...(values.runOnLive
+ ? {}
+ : {
+ filter: [],
+ sampling: 1,
+ delay: 0,
+ }),
+ })}
+ />
+ </div>
+ )}
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/EstimatedCostRow.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/EstimatedCostRow.tsx
new file mode 100644
index 0000000000..c74b94bb63
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/EstimatedCostRow.tsx
@@ -0,0 +1,112 @@
+import { InfoIcon } from "lucide-react";
+import { api } from "@/src/utils/api";
+import { usdFormatter } from "@/src/utils/numbers";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+
+type EstimatedCostRowProps = {
+ projectId: string;
+ evaluators: Array<{ id: string; name: string }>;
+ observationCount: number;
+};
+
+function formatCostEstimate(cost: number): string {
+ if (cost > 0 && cost < 0.005) return "< $0.01";
+ return `~${usdFormatter(cost, 2, 2)}`;
+}
+
+export function EstimatedCostRow(props: EstimatedCostRowProps) {
+ const { projectId, evaluators, observationCount } = props;
+
+ const evaluatorIds = evaluators.map((e) => e.id);
+
+ const avgCostQuery = api.evals.avgCostByEvaluatorIds.useQuery(
+ { projectId, evaluatorIds },
+ { enabled: evaluators.length > 0 },
+ );
+
+ if (avgCostQuery.isLoading) {
+ return (
+ <div className="flex gap-2">
+ <span className="shrink-0 text-muted-foreground">
+ Est. LLM API Key Cost:
+ </span>
+ <Skeleton className="h-4 w-16" />
+ </div>
+ );
+ }
+
+ const data = avgCostQuery.data;
+ if (!data || Object.keys(data).length === 0) {
+ return (
+ <div className="flex gap-2">
+ <span className="shrink-0 text-muted-foreground">
+ Est. LLM API Key Cost:
+ </span>
+ <span className="text-muted-foreground">No data</span>
+ </div>
+ );
+ }
+
+ const evaluatorsWithData = evaluatorIds.filter((id) => id in data);
+ const evaluatorsWithoutData = evaluatorIds.filter((id) => !(id in data));
+ const isPartial = evaluatorsWithoutData.length > 0;
+
+ const totalEstimate = evaluatorsWithData.reduce(
+ (sum, id) => sum + data[id].avgCost * observationCount,
+ 0,
+ );
+
+ return (
+ <div className="flex gap-2">
+ <span className="shrink-0 text-muted-foreground">
+ Est. LLM API Key Cost:
+ </span>
+ <span className="flex items-center gap-1 font-medium">
+ {formatCostEstimate(totalEstimate)}
+ {isPartial ? "*" : ""}
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InfoIcon className="h-3 w-3 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs space-y-2 p-3">
+ <p className="text-xs">
+ Expected cost on your linked API key (not Langfuse). Estimated
+ from average evaluator execution cost over the last 7 days.
+ </p>
+ <div className="space-y-1">
+ {evaluators.map(({ id, name }) => {
+ const entry = data[id];
+ return (
+ <div
+ key={id}
+ className="flex justify-between gap-4 text-xs"
+ >
+ <span className="truncate">{name}</span>
+ <span className="shrink-0 tabular-nums">
+ {entry
+ ? formatCostEstimate(entry.avgCost * observationCount)
+ : "No data"}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ {isPartial ? (
+ <p className="text-xs text-muted-foreground">
+ *Partial estimate. Some evaluators have no execution history.
+ </p>
+ ) : null}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </span>
+ </div>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorPromptPreview.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorPromptPreview.tsx
new file mode 100644
index 0000000000..582896d4c6
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorPromptPreview.tsx
@@ -0,0 +1,35 @@
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@/src/components/ui/hover-card";
+
+type EvaluatorPromptPreviewProps = {
+ trigger: React.ReactNode;
+ previewContent: string;
+};
+
+export function EvaluatorPromptPreview(props: EvaluatorPromptPreviewProps) {
+ const { trigger, previewContent } = props;
+
+ return (
+ <HoverCard openDelay={150} closeDelay={150}>
+ <HoverCardTrigger asChild>{trigger}</HoverCardTrigger>
+ <HoverCardContent
+ className="z-50 w-[520px] max-w-[85vw]"
+ align="end"
+ onWheel={(event) => event.stopPropagation()}
+ >
+ <p className="mb-2 text-xs text-muted-foreground">
+ Prompt preview with the first selected observation
+ </p>
+ <pre
+ className="max-h-[320px] overflow-y-auto whitespace-pre-wrap break-words rounded-md border bg-muted/20 p-2 text-xs"
+ onWheel={(event) => event.stopPropagation()}
+ >
+ {previewContent}
+ </pre>
+ </HoverCardContent>
+ </HoverCard>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx
new file mode 100644
index 0000000000..6838047c4a
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx
@@ -0,0 +1,241 @@
+import { useMemo } from "react";
+import { observationVariableMappingList } from "@langfuse/shared";
+import { type RouterOutputs } from "@/src/utils/api";
+import { Button } from "@/src/components/ui/button";
+import { Card, CardContent } from "@/src/components/ui/card";
+import { Badge } from "@/src/components/ui/badge";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import { Input } from "@/src/components/ui/input";
+import { EvaluatorPromptPreview } from "./EvaluatorPromptPreview";
+import { renderPromptPreviewFromObservation } from "./utils";
+import { Eye, Plus, X } from "lucide-react";
+
+type Evaluator = RouterOutputs["evals"]["jobConfigsByTarget"][number];
+type ObservationPreview = RouterOutputs["observations"]["byId"];
+
+type EvaluatorSelectionStepProps = {
+ eligibleEvaluators: Evaluator[];
+ selectedEvaluators: Evaluator[];
+ isQueryLoading: boolean;
+ isQueryError: boolean;
+ queryErrorMessage: string | undefined;
+ previewObservation: ObservationPreview | undefined;
+ isPreviewLoading: boolean;
+ selectedEvaluatorIds: string[];
+ evaluatorSearchQuery: string;
+ onSearchQueryChange: (query: string) => void;
+ onToggleEvaluator: (evaluatorId: string) => void;
+ onCreateEvaluator: () => void;
+};
+
+export function EvaluatorSelectionStep(props: EvaluatorSelectionStepProps) {
+ const {
+ eligibleEvaluators,
+ selectedEvaluators,
+ isQueryLoading,
+ isQueryError,
+ queryErrorMessage,
+ previewObservation,
+ isPreviewLoading,
+ selectedEvaluatorIds,
+ evaluatorSearchQuery,
+ onSearchQueryChange,
+ onToggleEvaluator,
+ onCreateEvaluator,
+ } = props;
+
+ const filteredEvaluators = useMemo(() => {
+ const normalizedSearch = evaluatorSearchQuery.trim().toLowerCase();
+ const filtered = normalizedSearch
+ ? eligibleEvaluators.filter((evaluator) => {
+ const templateName = evaluator.evalTemplate?.name ?? "";
+
+ return (
+ evaluator.scoreName.toLowerCase().includes(normalizedSearch) ||
+ templateName.toLowerCase().includes(normalizedSearch)
+ );
+ })
+ : eligibleEvaluators;
+
+ return [...filtered].sort((a, b) =>
+ a.scoreName.localeCompare(b.scoreName, undefined, {
+ sensitivity: "base",
+ }),
+ );
+ }, [eligibleEvaluators, evaluatorSearchQuery]);
+
+ const getPromptPreview = (evaluator: Evaluator) => {
+ if (isPreviewLoading) {
+ return "Loading preview...";
+ }
+
+ if (!previewObservation) {
+ return "Preview unavailable for the current selection.";
+ }
+
+ const mappingResult = observationVariableMappingList.safeParse(
+ evaluator.variableMapping,
+ );
+
+ if (!mappingResult.success) {
+ return "Evaluator mapping is not valid for observation preview.";
+ }
+
+ return renderPromptPreviewFromObservation({
+ prompt: evaluator.evalTemplate?.prompt,
+ variableMapping: mappingResult.data,
+ observation: previewObservation,
+ });
+ };
+
+ return (
+ <div className="flex h-full flex-col gap-2">
+ <div className="min-h-0 flex-1">
+ {isQueryLoading ? (
+ <p className="text-sm text-muted-foreground">Loading evaluators...</p>
+ ) : isQueryError ? (
+ <Card>
+ <CardContent className="p-4 text-sm text-destructive">
+ Failed to load evaluators: {queryErrorMessage}
+ </CardContent>
+ </Card>
+ ) : eligibleEvaluators.length === 0 ? (
+ <Card>
+ <CardContent className="p-4 text-sm text-muted-foreground">
+ No observation-scoped evaluators found. Create a new
+ observation-scoped evaluator and it will appear here.
+ </CardContent>
+ </Card>
+ ) : (
+ <div className="flex h-full min-h-0 flex-col gap-2">
+ <div className="relative">
+ <Input
+ autoFocus
+ className="pr-10"
+ placeholder="Search evaluators..."
+ value={evaluatorSearchQuery}
+ onChange={(event) =>
+ onSearchQueryChange(event.currentTarget.value)
+ }
+ />
+ {evaluatorSearchQuery.length > 0 ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="absolute right-1.5 top-1/2 h-7 w-7 -translate-y-1/2"
+ onClick={() => onSearchQueryChange("")}
+ aria-label="Clear evaluator search"
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ ) : null}
+ </div>
+
+ <div className="px-1 pb-1">
+ <div className="flex min-h-6 flex-wrap items-center gap-2">
+ {selectedEvaluators.length > 0 ? (
+ selectedEvaluators.map((evaluator) => (
+ <EvaluatorPromptPreview
+ key={evaluator.id}
+ previewContent={getPromptPreview(evaluator)}
+ trigger={
+ <div>
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-1 pr-1"
+ >
+ <span>{evaluator.scoreName}</span>
+ <button
+ type="button"
+ aria-label={`Remove ${evaluator.scoreName}`}
+ className="rounded p-0.5 hover:bg-muted"
+ onClick={() => onToggleEvaluator(evaluator.id)}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </Badge>
+ </div>
+ }
+ />
+ ))
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ No evaluators selected
+ </p>
+ )}
+ </div>
+ </div>
+
+ {filteredEvaluators.length === 0 ? (
+ <div className="flex min-h-0 flex-1 items-center justify-center rounded-md border">
+ <p className="p-4 text-sm text-muted-foreground">
+ No evaluators match your search.
+ </p>
+ </div>
+ ) : (
+ <div className="min-h-0 flex-1 overflow-y-auto rounded-md border">
+ {filteredEvaluators.map((item, index, array) => (
+ <div key={item.id}>
+ <div
+ className="flex cursor-pointer items-center gap-2 px-2 py-1.5 transition-colors hover:bg-muted/50"
+ onClick={() => onToggleEvaluator(item.id)}
+ >
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">
+ {item.scoreName}
+ </p>
+ <p className="truncate text-[11px] text-muted-foreground">
+ Template:{" "}
+ {item.evalTemplate?.name ?? "Deleted template"}
+ </p>
+ </div>
+ <EvaluatorPromptPreview
+ previewContent={getPromptPreview(item)}
+ trigger={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="h-7 w-7"
+ onMouseDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onClick={(event) => event.stopPropagation()}
+ aria-label={`Preview ${item.scoreName}`}
+ >
+ <Eye className="h-4 w-4" />
+ </Button>
+ }
+ />
+ <Checkbox
+ checked={selectedEvaluatorIds.includes(item.id)}
+ aria-label={`Select ${item.scoreName}`}
+ onClick={(event) => event.stopPropagation()}
+ onCheckedChange={() => onToggleEvaluator(item.id)}
+ className="mr-1"
+ />
+ </div>
+ {index < array.length - 1 ? (
+ <div className="border-b border-border/50" />
+ ) : null}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ <Button
+ variant="outline"
+ size="default"
+ className="h-9 w-full"
+ onClick={onCreateEvaluator}
+ >
+ <Plus className="mr-1 h-4 w-4" />
+ Create new Evaluator
+ </Button>
+ </div>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
new file mode 100644
index 0000000000..3ac9dfb40f
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
@@ -0,0 +1,242 @@
+import { useMemo, useState } from "react";
+import { EvalTargetObject, type BatchActionQuery } from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { Button } from "@/src/components/ui/button";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { ChevronLeft } from "lucide-react";
+import { EvaluatorSelectionStep } from "./EvaluatorSelectionStep";
+import { ConfirmationStep } from "./ConfirmationStep";
+import { CreateEvaluatorDialog } from "./CreateEvaluatorDialog";
+import { buildQueryWithSelectedIds } from "./utils";
+
+type RunEvaluationDialogProps = {
+ projectId: string;
+ selectedObservationIds: string[];
+ query: BatchActionQuery;
+ selectAll: boolean;
+ totalCount: number;
+ onClose: () => void;
+};
+
+type DialogStep = "select-evaluator" | "confirm";
+
+export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
+ const { projectId, selectedObservationIds, query, selectAll, totalCount } =
+ props;
+
+ const [step, setStep] = useState<DialogStep>("select-evaluator");
+ const [selectedEvaluatorIds, setSelectedEvaluatorIds] = useState<string[]>(
+ [],
+ );
+ const [evaluatorSearchQuery, setEvaluatorSearchQuery] = useState("");
+ const [showCreateDialog, setShowCreateDialog] = useState(false);
+
+ const evaluatorsQuery = api.evals.jobConfigsByTarget.useQuery({
+ projectId,
+ targetObject: EvalTargetObject.EVENT,
+ });
+
+ const runEvaluationMutation =
+ api.batchAction.runEvaluation.create.useMutation({
+ onError: (error) => {
+ showErrorToast("Failed to schedule evaluation", error.message);
+ },
+ });
+
+ const displayCount = selectAll ? totalCount : selectedObservationIds.length;
+
+ const previewFilter = useMemo(
+ () =>
+ buildQueryWithSelectedIds({ query, selectAll, selectedObservationIds })
+ .filter ?? [],
+ [query, selectAll, selectedObservationIds],
+ );
+
+ const previewObservationSeedQuery = api.events.all.useQuery(
+ {
+ projectId,
+ filter: previewFilter,
+ searchQuery: selectAll ? (query.searchQuery ?? null) : null,
+ searchType: selectAll ? (query.searchType ?? ["id", "content"]) : [],
+ page: 1,
+ limit: 1,
+ orderBy: query.orderBy,
+ },
+ {
+ enabled: displayCount > 0,
+ },
+ );
+
+ const previewObservationSeed =
+ previewObservationSeedQuery.data?.observations?.[0];
+
+ const previewObservationQuery = api.observations.byId.useQuery(
+ {
+ projectId,
+ observationId: previewObservationSeed?.id ?? "",
+ traceId: previewObservationSeed?.traceId ?? "",
+ startTime: previewObservationSeed?.startTime ?? null,
+ },
+ {
+ enabled: Boolean(
+ previewObservationSeed?.id && previewObservationSeed?.traceId,
+ ),
+ },
+ );
+
+ const eligibleEvaluators = useMemo(() => {
+ return (evaluatorsQuery.data ?? []).filter(
+ (evaluator) => evaluator.targetObject === EvalTargetObject.EVENT,
+ );
+ }, [evaluatorsQuery.data]);
+
+ const selectedEvaluators = useMemo(
+ () =>
+ eligibleEvaluators.filter((evaluator) =>
+ selectedEvaluatorIds.includes(evaluator.id),
+ ),
+ [eligibleEvaluators, selectedEvaluatorIds],
+ );
+
+ const toggleEvaluatorSelection = (evaluatorId: string) => {
+ setSelectedEvaluatorIds((previous) =>
+ previous.includes(evaluatorId)
+ ? previous.filter((id) => id !== evaluatorId)
+ : [...previous, evaluatorId],
+ );
+ };
+
+ const onSubmit = async () => {
+ if (selectedEvaluators.length === 0) {
+ return;
+ }
+
+ const finalQuery = buildQueryWithSelectedIds({
+ query,
+ selectAll,
+ selectedObservationIds,
+ });
+
+ try {
+ await runEvaluationMutation.mutateAsync({
+ projectId,
+ query: finalQuery,
+ evaluatorIds: selectedEvaluators.map((evaluator) => evaluator.id),
+ });
+ } catch {
+ return;
+ }
+
+ showSuccessToast({
+ title: "Evaluation queued",
+ description: `Scheduled evaluation for ${displayCount} selected ${displayCount === 1 ? "observation" : "observations"} and ${selectedEvaluators.length} ${selectedEvaluators.length === 1 ? "evaluator" : "evaluators"}.`,
+ link: {
+ href: `/project/${projectId}/settings/batch-actions`,
+ text: "View batch actions",
+ },
+ });
+
+ props.onClose();
+ };
+
+ return (
+ <>
+ <Dialog open onOpenChange={(open) => !open && props.onClose()}>
+ <DialogContent className="flex max-h-[62vh] min-h-[38vh] max-w-2xl flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ Evaluate {displayCount} observation
+ {displayCount === 1 ? "" : "s"}
+ </DialogTitle>
+ <DialogDescription>
+ {step === "confirm"
+ ? "Review your evaluation configuration before running."
+ : "Select one or more observation-scoped evaluators."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody className="flex-1 overflow-hidden">
+ {step === "select-evaluator" ? (
+ <EvaluatorSelectionStep
+ eligibleEvaluators={eligibleEvaluators}
+ selectedEvaluators={selectedEvaluators}
+ isQueryLoading={evaluatorsQuery.isLoading}
+ isQueryError={evaluatorsQuery.isError}
+ queryErrorMessage={evaluatorsQuery.error?.message}
+ previewObservation={previewObservationQuery.data}
+ isPreviewLoading={
+ previewObservationSeedQuery.isLoading ||
+ previewObservationQuery.isLoading
+ }
+ selectedEvaluatorIds={selectedEvaluatorIds}
+ evaluatorSearchQuery={evaluatorSearchQuery}
+ onSearchQueryChange={setEvaluatorSearchQuery}
+ onToggleEvaluator={toggleEvaluatorSelection}
+ onCreateEvaluator={() => setShowCreateDialog(true)}
+ />
+ ) : (
+ <ConfirmationStep
+ projectId={projectId}
+ displayCount={displayCount}
+ evaluators={selectedEvaluators.map((e) => ({
+ id: e.id,
+ name: e.scoreName,
+ }))}
+ />
+ )}
+ </DialogBody>
+
+ <DialogFooter className="flex justify-between">
+ {step === "confirm" ? (
+ <Button
+ variant="ghost"
+ onClick={() => setStep("select-evaluator")}
+ disabled={runEvaluationMutation.isPending}
+ >
+ <ChevronLeft className="mr-1 h-4 w-4" />
+ Back
+ </Button>
+ ) : (
+ <div />
+ )}
+
+ {step === "select-evaluator" ? (
+ <Button
+ onClick={() => setStep("confirm")}
+ disabled={selectedEvaluators.length === 0}
+ >
+ Continue{" "}
+ {selectedEvaluators.length > 0
+ ? `with ${selectedEvaluators.length} evaluator(s)`
+ : null}
+ </Button>
+ ) : (
+ <Button
+ onClick={onSubmit}
+ loading={runEvaluationMutation.isPending}
+ >
+ Run Evaluation
+ </Button>
+ )}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <CreateEvaluatorDialog
+ projectId={projectId}
+ open={showCreateDialog}
+ onOpenChange={setShowCreateDialog}
+ />
+ </>
+ );
+}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
new file mode 100644
index 0000000000..da3a0e9686
--- /dev/null
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
@@ -0,0 +1,85 @@
+import {
+ extractValueFromObject,
+ type BatchActionQuery,
+ type ObservationVariableMapping,
+} from "@langfuse/shared";
+import { type RouterOutputs } from "@/src/utils/api";
+
+type ObservationPreview = RouterOutputs["observations"]["byId"];
+
+const PROMPT_PREVIEW_CHAR_LIMIT = 2000;
+
+export function stringifyPreviewValue(value: unknown): string {
+ if (value === null || value === undefined) return "";
+ if (typeof value === "string") return value;
+ if (
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ typeof value === "bigint"
+ ) {
+ return String(value);
+ }
+
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function renderPromptPreviewFromObservation(params: {
+ prompt: string | null | undefined;
+ variableMapping: ObservationVariableMapping[];
+ observation: ObservationPreview;
+}): string {
+ const { prompt, variableMapping, observation } = params;
+
+ if (!prompt) {
+ return "Template has no prompt.";
+ }
+
+ const variableValues = new Map<string, string>();
+
+ for (const mapping of variableMapping) {
+ const { value } = extractValueFromObject(
+ observation,
+ mapping.selectedColumnId,
+ mapping.jsonSelector ?? undefined,
+ );
+ variableValues.set(mapping.templateVariable, stringifyPreviewValue(value));
+ }
+
+ const renderedPrompt = prompt.replace(/{{([^{}]+)}}/g, (_match, variable) => {
+ const variableName = String(variable).trim();
+ return variableValues.get(variableName) ?? "";
+ });
+
+ return renderedPrompt.length > PROMPT_PREVIEW_CHAR_LIMIT
+ ? `${renderedPrompt.slice(0, PROMPT_PREVIEW_CHAR_LIMIT)}...`
+ : renderedPrompt;
+}
+
+export function buildQueryWithSelectedIds(params: {
+ query: BatchActionQuery;
+ selectAll: boolean;
+ selectedObservationIds: string[];
+}): BatchActionQuery {
+ const { query, selectAll, selectedObservationIds } = params;
+
+ if (selectAll) {
+ return query;
+ }
+
+ return {
+ ...query,
+ filter: [
+ ...(query.filter ?? []),
+ {
+ column: "id",
+ operator: "any of" as const,
+ value: selectedObservationIds,
+ type: "stringOptions" as const,
+ },
+ ],
+ };
+}
diff --git a/web/src/features/batch-actions/server/batchActionRouter.ts b/web/src/features/batch-actions/server/batchActionRouter.ts
index b04a81356b..cb53308f13 100644
--- a/web/src/features/batch-actions/server/batchActionRouter.ts
+++ b/web/src/features/batch-actions/server/batchActionRouter.ts
@@ -8,9 +8,11 @@ import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { GetBatchActionByIdSchema } from "../validation";
import { addToDatasetRouter } from "./addToDatasetRouter";
+import { runEvaluationRouter } from "./runEvaluationRouter";
export const batchActionRouter = createTRPCRouter({
addToDataset: addToDatasetRouter,
+ runEvaluation: runEvaluationRouter,
byId: protectedProjectProcedure
.input(GetBatchActionByIdSchema)
.query(async ({ input, ctx }) => {
diff --git a/web/src/features/batch-actions/server/runEvaluationRouter.ts b/web/src/features/batch-actions/server/runEvaluationRouter.ts
new file mode 100644
index 0000000000..7676cfa611
--- /dev/null
+++ b/web/src/features/batch-actions/server/runEvaluationRouter.ts
@@ -0,0 +1,157 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ BatchActionQueue,
+ logger,
+ QueueJobs,
+ getObservationsCountFromEventsTable,
+} from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+import {
+ BatchTableNames,
+ BatchActionStatus,
+ ActionId,
+ EvalTargetObject,
+} from "@langfuse/shared";
+import { env } from "@/src/env.mjs";
+import { CreateObservationBatchEvaluationActionSchema } from "../validation";
+
+export const runEvaluationRouter = createTRPCRouter({
+ create: protectedProjectProcedure
+ .input(CreateObservationBatchEvaluationActionSchema)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:CUD",
+ });
+
+ const { projectId, query, evaluatorIds: rawEvaluatorIds } = input;
+
+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS !== "true") {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Events table is not enabled for this instance.",
+ });
+ }
+
+ const requestedEvaluatorIds = Array.from(new Set(rawEvaluatorIds));
+
+ const evaluatorIds = (
+ await ctx.prisma.jobConfiguration.findMany({
+ where: {
+ id: {
+ in: requestedEvaluatorIds,
+ },
+ projectId,
+ targetObject: EvalTargetObject.EVENT,
+ },
+ select: {
+ id: true,
+ },
+ })
+ ).map((e) => e.id);
+
+ if (evaluatorIds.length !== requestedEvaluatorIds.length) {
+ const foundIds = new Set(evaluatorIds);
+ const missingEvaluatorIds = requestedEvaluatorIds.filter(
+ (id) => !foundIds.has(id),
+ );
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ missingEvaluatorIds.length > 0
+ ? `Evaluators [${missingEvaluatorIds.join(", ")}] are missing or not observation-scoped.`
+ : "Selected evaluators are missing or not observation-scoped.",
+ });
+ }
+
+ const countQueryOpts = {
+ projectId,
+ filter: query.filter ?? [],
+ searchQuery: query.searchQuery,
+ searchType: query.searchType,
+ };
+
+ const observationCount =
+ await getObservationsCountFromEventsTable(countQueryOpts);
+
+ if (observationCount > env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Too many observations selected. Maximum allowed is ${env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT}, but ${observationCount} observations match your filters. Please refine your filters to reduce the count.`,
+ });
+ }
+
+ const userId = ctx.session.user.id;
+ const batchConfig = { evaluatorIds };
+
+ logger.info(
+ "[TRPC] Creating observation-run-batched-evaluation action",
+ {
+ projectId,
+ evaluatorCount: evaluatorIds.length,
+ evaluatorIds,
+ },
+ );
+
+ const batchAction = await ctx.prisma.batchAction.create({
+ data: {
+ projectId,
+ userId,
+ actionType: ActionId.ObservationBatchEvaluation,
+ tableName: BatchTableNames.Events,
+ status: BatchActionStatus.Queued,
+ query,
+ config: batchConfig,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "batchAction",
+ resourceId: batchAction.id,
+ projectId,
+ action: ActionId.ObservationBatchEvaluation,
+ after: batchAction,
+ });
+
+ await BatchActionQueue.getInstance()?.add(
+ QueueJobs.BatchActionProcessingJob,
+ {
+ id: batchAction.id,
+ name: QueueJobs.BatchActionProcessingJob,
+ timestamp: new Date(),
+ payload: {
+ actionId: ActionId.ObservationBatchEvaluation,
+ batchActionId: batchAction.id,
+ projectId,
+ cutoffCreatedAt: new Date(),
+ query,
+ evaluatorIds: batchConfig.evaluatorIds,
+ },
+ },
+ {
+ jobId: batchAction.id,
+ },
+ );
+
+ return { id: batchAction.id };
+ } catch (e) {
+ logger.error(e);
+ if (e instanceof TRPCError) {
+ throw e;
+ }
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Creating run-evaluation action failed.",
+ });
+ }
+ }),
+});
diff --git a/web/src/features/batch-actions/validation.ts b/web/src/features/batch-actions/validation.ts
index 745e9d06cf..fd905481b8 100644
--- a/web/src/features/batch-actions/validation.ts
+++ b/web/src/features/batch-actions/validation.ts
@@ -11,6 +11,12 @@ export const CreateObservationAddToDatasetActionSchema = z.object({
config: ObservationAddToDatasetConfigSchema,
});
+export const CreateObservationBatchEvaluationActionSchema = z.object({
+ projectId: z.string(),
+ query: BatchActionQuerySchema,
+ evaluatorIds: z.array(z.string()).min(1),
+});
+
export const ValidateBatchAddToDatasetMappingSchema = z.object({
projectId: z.string(),
observationId: z.string(),
diff --git a/web/src/features/evals/components/eval-version-callout.tsx b/web/src/features/evals/components/eval-version-callout.tsx
index e1acf1d50a..72c54982d3 100644
--- a/web/src/features/evals/components/eval-version-callout.tsx
+++ b/web/src/features/evals/components/eval-version-callout.tsx
@@ -33,10 +33,10 @@ const getCalloutContent = (
return {
visible: true,
- title: "Please check your SDK version",
+ title: "Please verify your SDK version",
description: (
<>
- This evaluator targets live observations, which require JS SDK v4+ or
+ This evaluator targets observations, which require JS SDK v4+ or
Python SDK v3+. You can still configure this evaluator now—it will
start running once you upgrade.{" "}
<a
@@ -110,12 +110,11 @@ const getCalloutContent = (
if (isTraceTarget(targetObject)) {
return {
visible: true,
- title: "Consider upgrading to live observations evaluators",
+ title: "Consider upgrading to observation evaluators",
description: (
<>
- Live observations evaluators provide more granular control and an
- easier workflow. We strongly recommend upgrading to live observations
- evaluators.{" "}
+ Observation evaluators provide more granular control and an easier
+ workflow. We strongly recommend upgrading to observation evaluators.{" "}
<a
href="https://langfuse.com/faq/all/llm-as-a-judge-migration"
target="_blank"
@@ -144,7 +143,10 @@ export function EvalVersionCallout({
}
return (
- <Alert variant="default" className="mt-2 border-light-blue bg-light-blue">
+ <Alert
+ variant="default"
+ className="mt-2 max-w-4xl border-light-blue bg-light-blue"
+ >
<Info className="h-4 w-4 text-dark-blue dark:text-dark-blue" />
<AlertDescription>
<div className="flex flex-col gap-2">
diff --git a/web/src/features/evals/components/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsx
index df297a1dbf..a0ca4584e2 100644
--- a/web/src/features/evals/components/evaluator-form.tsx
+++ b/web/src/features/evals/components/evaluator-form.tsx
@@ -15,8 +15,11 @@ export const EvaluatorForm = (props: {
shouldWrapVariables?: boolean;
templateId?: string;
hideTargetSection?: boolean;
+ hideTargetSelection?: boolean;
preventRedirect?: boolean;
preprocessFormValues?: (values: any) => any;
+ defaultRunOnLive?: boolean;
+ hidePreviewTable?: boolean;
}) => {
const evalCapabilities = useEvalCapabilities(props.projectId);
@@ -43,11 +46,14 @@ export const EvaluatorForm = (props: {
onFormSuccess={props.onFormSuccess}
shouldWrapVariables={props.shouldWrapVariables}
hideTargetSection={props.hideTargetSection}
+ hideTargetSelection={props.hideTargetSelection}
mode={props.mode}
preventRedirect={props.preventRedirect ?? true}
preprocessFormValues={props.preprocessFormValues}
useDialog={props.useDialog}
evalCapabilities={evalCapabilities}
+ defaultRunOnLive={props.defaultRunOnLive}
+ hidePreviewTable={props.hidePreviewTable}
/>
)}
</>
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index f761bbfe67..6887c34378 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -165,14 +165,7 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
projectId,
false,
false,
- [
- {
- column: "status",
- type: "stringOptions",
- operator: "any of",
- value: ["ACTIVE"],
- },
- ],
+ [],
);
const evaluators = api.evals.allConfigs.useQuery({
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 0c278b33e1..8b598149a2 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -23,6 +23,7 @@ import {
experimentEvalFilterColsWithOptions,
type ColumnDefinition,
type availableDatasetEvalVariables,
+ JobConfigState,
} from "@langfuse/shared";
import { z } from "zod/v4";
import { useEffect, useMemo, useState, memo } from "react";
@@ -41,6 +42,7 @@ import { Slider } from "@/src/components/ui/slider";
import { Card } from "@/src/components/ui/card";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { Checkbox } from "@/src/components/ui/checkbox";
+import { Switch } from "@/src/components/ui/switch";
import {
evalConfigFormSchema,
type EvalFormType,
@@ -220,9 +222,6 @@ const ObservationsPreview = memo(
return (
<>
<div className="flex flex-col items-start gap-1">
- <span className="text-sm font-medium leading-none">
- Preview sample matched observations
- </span>
<FormDescription>
Sample over the last 24 hours that match filters
</FormDescription>
@@ -269,7 +268,9 @@ export const InnerEvaluatorForm = (props: {
preprocessFormValues?: (values: any) => any;
hideAdvancedSettings?: boolean;
hideTargetSelection?: boolean;
+ hidePreviewTable?: boolean;
evalCapabilities: EvalCapabilities;
+ defaultRunOnLive?: boolean;
renderFooter?: (params: {
isLoading: boolean;
formError: string | null;
@@ -350,6 +351,9 @@ export const InnerEvaluatorForm = (props: {
(option): option is "NEW" | "EXISTING" =>
["NEW", "EXISTING"].includes(option),
),
+ runOnLive: props.existingEvaluator
+ ? props.existingEvaluator.status === "ACTIVE"
+ : (props.defaultRunOnLive ?? true),
},
}) as UseFormReturn<EvalFormType>;
@@ -448,6 +452,14 @@ export const InnerEvaluatorForm = (props: {
const filter = validatedFilter.data;
const scoreName = values.scoreName;
+ // For modern targets, derive status from runOnLive
+ const isModern = !isLegacyEvalTarget(values.target);
+ const status = isModern
+ ? values.runOnLive
+ ? JobConfigState.ACTIVE
+ : JobConfigState.INACTIVE
+ : undefined;
+
(props.mode === "edit" && props.existingEvaluator?.id
? updateJobMutation.mutateAsync({
projectId: props.projectId,
@@ -458,7 +470,8 @@ export const InnerEvaluatorForm = (props: {
variableMapping: mapping,
sampling,
scoreName,
- timeScope: values.timeScope,
+ timeScope: isModern ? ["NEW"] : values.timeScope,
+ ...(status ? { status } : {}),
},
})
: createJobMutation.mutateAsync({
@@ -470,7 +483,8 @@ export const InnerEvaluatorForm = (props: {
mapping,
sampling,
delay,
- timeScope: values.timeScope,
+ timeScope: isModern ? ["NEW"] : values.timeScope,
+ ...(status ? { status } : {}),
})
)
.then(() => {
@@ -547,6 +561,7 @@ export const InnerEvaluatorForm = (props: {
: [],
);
form.setValue("mapping", newMapping);
+ form.setValue("runOnLive", props.defaultRunOnLive ?? true);
setAvailableVariables(targetState.getAvailableVariables(actualTarget));
return actualTarget;
}
@@ -608,7 +623,7 @@ export const InnerEvaluatorForm = (props: {
className="min-w-[100px] gap-1.5"
>
<CircleDot className="h-3.5 w-3.5" />
- Live Observations
+ Observations
<Badge
variant="secondary"
size="sm"
@@ -624,7 +639,7 @@ export const InnerEvaluatorForm = (props: {
className="min-w-[100px] gap-1.5"
>
<ListTree className="h-3.5 w-3.5" />
- Live Traces
+ Traces
{isFullyReleased && (
<Badge
variant="secondary"
@@ -833,163 +848,216 @@ export const InnerEvaluatorForm = (props: {
/>
)}
- <FormField
- control={form.control}
- name="filter"
- render={({ field }) => {
- const target = form.watch("target");
-
- // Get appropriate columns based on target type
- const getFilterColumns = () => {
- if (isEventTarget(target)) {
- // Event evaluators - use observation columns with propagation warnings
- const baseColumns = observationEvalFilterColsWithOptions(
- observationEvalFilterOptions,
- );
- return addPropagationWarnings(
- baseColumns,
- allowPropagationFilters,
- );
- } else if (isTraceTarget(target)) {
- return tracesTableColsWithOptions(traceFilterOptions);
- } else if (isExperimentTarget(target)) {
- // Experiment evaluators - only dataset filter
- return experimentEvalFilterColsWithOptions(
- experimentEvalFilterOptions,
- );
- } else {
- // dataset (legacy non-OTEL experiments)
- return datasetFormFilterColsWithOptions(
- datasetFilterOptions,
- );
- }
- };
-
- const hasFilters = field.value && field.value.length > 0;
-
- return (
- <FormItem>
- <FormLabel>Where</FormLabel>
- <FormControl>
- <div className="max-w-[500px]">
- {props.disabled && !hasFilters ? (
+ {/* Run on Live toggle for modern (non-legacy) targets */}
+ {!props.hideAdvancedSettings &&
+ !isLegacyEvalTarget(form.watch("target")) && (
+ <FormField
+ control={form.control}
+ name="runOnLive"
+ render={({ field }) => {
+ const target = form.watch("target");
+ return (
+ <div className="flex max-w-4xl flex-col gap-2">
+ <FormItem className="flex items-center justify-between rounded-lg border p-3">
+ <div className="space-y-0.5">
+ <FormLabel>
+ {isEventTarget(target)
+ ? "Run on live incoming observations"
+ : "Run on new experiments"}
+ </FormLabel>
+ <FormDescription>
+ Automatically evaluate new incoming{" "}
+ {getTargetDisplayName(target)}.
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={props.disabled}
+ />
+ </FormControl>
+ </FormItem>
+ {!field.value && isEventTarget(target) && (
<p className="text-xs text-muted-foreground">
- All {getTargetDisplayName(target)} will be evaluated
+ This evaluator can still be used for batched
+ evaluation of historic observations.
</p>
- ) : (
- <InlineFilterBuilder
- columnIdentifier={
- isDatasetTarget(target) || isTraceTarget(target)
- ? "name"
- : "id"
- }
- columns={getFilterColumns()}
- filterState={field.value ?? []}
- onChange={(
- value: z.infer<typeof singleFilter>[],
- ) => {
- field.onChange(value);
- if (router.query.traceId) {
- const { traceId, ...otherParams } =
- router.query;
- router.replace(
- {
- pathname: router.pathname,
- query: otherParams,
- },
- undefined,
- { shallow: true },
- );
- }
- }}
- disabled={props.disabled}
- columnsWithCustomSelect={
- isEventTarget(target) || isTraceTarget(target)
- ? ["tags", "name"]
- : undefined
- }
- />
)}
</div>
- </FormControl>
- {!props.disabled && !hasFilters && (
- <div className="align-center flex max-w-[500px] gap-1">
- <AlertTriangle className="h-4 w-4 text-dark-yellow" />
- <AlertDescription className="text-dark-yellow">
- No filters set. This evaluator will run on all{" "}
- {getTargetDisplayName(target)}.
- </AlertDescription>
- </div>
- )}
- <FormMessage />
- </FormItem>
- );
- }}
- />
-
- {/* Preview based on target type */}
- {!props.disabled && (
- <>
- {isTraceTarget(form.watch("target")) && (
- <TracesPreview
- projectId={props.projectId}
- filterState={form.watch("filter") ?? []}
- />
- )}
-
- {isEventTarget(form.watch("target")) && (
- <ObservationsPreview
- projectId={props.projectId}
- filterState={form.watch("filter") ?? []}
- />
- )}
- </>
- )}
+ );
+ }}
+ />
+ )}
- {!props.hideAdvancedSettings && (
+ {(isLegacyEvalTarget(form.watch("target")) ||
+ form.watch("runOnLive")) && (
<>
<FormField
control={form.control}
- name="sampling"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Sampling</FormLabel>
- <FormControl>
- <div className="max-w-[500px]">
- <Slider
- disabled={props.disabled}
- min={0}
- max={1}
- step={0.0001}
- value={[field.value]}
- onValueChange={(value) => field.onChange(value[0])}
- showInput={true}
- displayAsPercentage={true}
- />
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- {isLegacyEvalTarget(form.watch("target")) && (
- <FormField
- control={form.control}
- name="delay"
- render={({ field }) => (
+ name="filter"
+ render={({ field }) => {
+ const target = form.watch("target");
+
+ // Get appropriate columns based on target type
+ const getFilterColumns = () => {
+ if (isEventTarget(target)) {
+ // Event evaluators - use observation columns with propagation warnings
+ const baseColumns =
+ observationEvalFilterColsWithOptions(
+ observationEvalFilterOptions,
+ );
+ return addPropagationWarnings(
+ baseColumns,
+ allowPropagationFilters,
+ );
+ } else if (isTraceTarget(target)) {
+ return tracesTableColsWithOptions(traceFilterOptions);
+ } else if (isExperimentTarget(target)) {
+ // Experiment evaluators - only dataset filter
+ return experimentEvalFilterColsWithOptions(
+ experimentEvalFilterOptions,
+ );
+ } else {
+ // dataset (legacy non-OTEL experiments)
+ return datasetFormFilterColsWithOptions(
+ datasetFilterOptions,
+ );
+ }
+ };
+
+ const hasFilters = field.value && field.value.length > 0;
+
+ return (
<FormItem>
- <FormLabel>Delay (seconds)</FormLabel>
+ <FormLabel>Filter</FormLabel>
<FormControl>
- <Input {...field} type="number" min={0} />
+ <div className="max-w-[500px]">
+ {props.disabled && !hasFilters ? (
+ <p className="text-xs text-muted-foreground">
+ All {getTargetDisplayName(target)} will be
+ evaluated
+ </p>
+ ) : (
+ <InlineFilterBuilder
+ columnIdentifier={
+ isDatasetTarget(target) ||
+ isTraceTarget(target)
+ ? "name"
+ : "id"
+ }
+ columns={getFilterColumns()}
+ filterState={field.value ?? []}
+ onChange={(
+ value: z.infer<typeof singleFilter>[],
+ ) => {
+ field.onChange(value);
+ if (router.query.traceId) {
+ const { traceId, ...otherParams } =
+ router.query;
+ router.replace(
+ {
+ pathname: router.pathname,
+ query: otherParams,
+ },
+ undefined,
+ { shallow: true },
+ );
+ }
+ }}
+ disabled={props.disabled}
+ columnsWithCustomSelect={
+ isEventTarget(target) || isTraceTarget(target)
+ ? ["tags", "name"]
+ : undefined
+ }
+ />
+ )}
+ </div>
</FormControl>
- <FormDescription>
- Time between first Trace/Dataset run event and
- evaluation execution to ensure all data is available
- </FormDescription>
+ {!props.disabled && !hasFilters && (
+ <div className="align-center flex max-w-[500px] gap-1">
+ <AlertTriangle className="h-4 w-4 text-dark-yellow" />
+ <AlertDescription className="text-dark-yellow">
+ No filters set. This evaluator will run on all{" "}
+ {getTargetDisplayName(target)}.
+ </AlertDescription>
+ </div>
+ )}
<FormMessage />
</FormItem>
+ );
+ }}
+ />
+
+ {/* Preview based on target type */}
+ {!props.disabled && !props.hidePreviewTable && (
+ <>
+ {isTraceTarget(form.watch("target")) && (
+ <TracesPreview
+ projectId={props.projectId}
+ filterState={form.watch("filter") ?? []}
+ />
+ )}
+
+ {isEventTarget(form.watch("target")) && (
+ <ObservationsPreview
+ projectId={props.projectId}
+ filterState={form.watch("filter") ?? []}
+ />
+ )}
+ </>
+ )}
+
+ {!props.hideAdvancedSettings && (
+ <>
+ <FormField
+ control={form.control}
+ name="sampling"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Sampling</FormLabel>
+ <FormControl>
+ <div className="max-w-[500px]">
+ <Slider
+ disabled={props.disabled}
+ min={0}
+ max={1}
+ step={0.0001}
+ value={[field.value]}
+ onValueChange={(value) =>
+ field.onChange(value[0])
+ }
+ showInput={true}
+ displayAsPercentage={true}
+ />
+ </div>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {isLegacyEvalTarget(form.watch("target")) && (
+ <FormField
+ control={form.control}
+ name="delay"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Delay (seconds)</FormLabel>
+ <FormControl>
+ <Input {...field} type="number" min={0} />
+ </FormControl>
+ <FormDescription>
+ Time between first Trace/Dataset run event and
+ evaluation execution to ensure all data is
+ available
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
)}
- />
+ </>
)}
</>
)}
@@ -1068,9 +1136,9 @@ export const InnerEvaluatorForm = (props: {
<DialogTitle>You selected a legacy evaluator</DialogTitle>
</DialogHeader>
<DialogBody className="text-sm">
- We strongly recommend using live observations evaluators. Trace
- evaluators will be deprecated in the future. Only proceed if you are
- sure you cannot upgrade your SDK version now.
+ We strongly recommend using observation evaluators. Trace evaluators
+ will be deprecated in the future. Only proceed if you are sure you
+ cannot upgrade your SDK version now.
</DialogBody>
<DialogFooter>
<Button
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index e1728d3fdd..7dbc1e57f9 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -23,6 +23,7 @@ import {
} from "@langfuse/shared";
import {
getQueue,
+ getAvgCostByEvaluatorIds,
getCostByEvaluatorIds,
getScoresByIds,
logger,
@@ -143,6 +144,7 @@ const CreateEvalJobSchema = z.object({
sampling: z.number().gt(0).lte(1),
delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default
timeScope: TimeScopeSchema,
+ status: z.enum(EvaluatorStatus).optional().default(JobConfigState.ACTIVE),
});
const UpdateEvalJobSchema = z.object({
@@ -749,16 +751,25 @@ export const evalRouter = createTRPCRouter({
variableMapping: input.mapping,
sampling: input.sampling,
delay: input.delay,
- status: "ACTIVE",
+ status: input.status,
timeScope: input.timeScope,
},
});
- // Clear the "no job configs" caches since we just created a new job configuration
- await clearNoEvalConfigsCache(input.projectId, "traceBased");
- await clearNoEvalConfigsCache(input.projectId, "eventBased");
+ // Clear the "no job configs" caches only if the new config is ACTIVE
+ if (input.status === JobConfigState.ACTIVE) {
+ await clearNoEvalConfigsCache(input.projectId, "traceBased");
+ await clearNoEvalConfigsCache(input.projectId, "eventBased");
+ }
- if (input.timeScope.includes("EXISTING")) {
+ // EVENT targets handle historical evaluation via the dedicated batch
+ // "Run Evaluation" action (runEvaluationRouter), so we only schedule
+ // historical backfills here for TRACE and DATASET targets.
+ if (
+ input.timeScope.includes("EXISTING") &&
+ (input.target === EvalTargetObject.TRACE ||
+ input.target === EvalTargetObject.DATASET)
+ ) {
logger.info(
`Applying to historical traces for job ${job.id} and project ${input.projectId}`,
);
@@ -790,6 +801,8 @@ export const evalRouter = createTRPCRouter({
{ delay: input.delay },
);
}
+
+ return { id: job.id };
}),
createTemplate: protectedProjectProcedure
.input(CreateEvalTemplate)
@@ -1074,7 +1087,10 @@ export const evalRouter = createTRPCRouter({
});
}
+ // Only enforce EXISTING-only deactivation rule for legacy targets (TRACE/DATASET)
if (
+ (existingJob.targetObject === EvalTargetObject.TRACE ||
+ existingJob.targetObject === EvalTargetObject.DATASET) &&
existingJob.timeScope.includes("EXISTING") &&
!existingJob.timeScope.includes("NEW") &&
config.status === "INACTIVE"
@@ -1110,7 +1126,14 @@ export const evalRouter = createTRPCRouter({
await clearNoEvalConfigsCache(projectId, "eventBased");
}
- if (config.timeScope?.includes("EXISTING")) {
+ // EVENT targets handle historical evaluation via the dedicated batch
+ // "Run Evaluation" action (runEvaluationRouter), so we only schedule
+ // historical backfills here for TRACE and DATASET targets.
+ if (
+ config.timeScope?.includes("EXISTING") &&
+ (existingJob?.targetObject === EvalTargetObject.TRACE ||
+ existingJob?.targetObject === EvalTargetObject.DATASET)
+ ) {
logger.info(
`Applying to historical traces for job ${evalConfigId} and project ${projectId}`,
);
@@ -1403,6 +1426,34 @@ export const evalRouter = createTRPCRouter({
{} as Record<string, number>,
);
}),
+
+ avgCostByEvaluatorIds: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ evaluatorIds: z.array(z.string()),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalJob:read",
+ });
+
+ const costs = await getAvgCostByEvaluatorIds(
+ input.projectId,
+ input.evaluatorIds,
+ );
+
+ return costs.reduce(
+ (acc, { evaluatorId, avgCost, executionCount }) => {
+ acc[evaluatorId] = { avgCost, executionCount };
+ return acc;
+ },
+ {} as Record<string, { avgCost: number; executionCount: number }>,
+ );
+ }),
});
const generateConfigsQuery = (
diff --git a/web/src/features/evals/types.ts b/web/src/features/evals/types.ts
index 1e38bb6864..b152acc348 100644
--- a/web/src/features/evals/types.ts
+++ b/web/src/features/evals/types.ts
@@ -19,6 +19,7 @@ export type PartialConfig = Pick<
| "sampling"
| "delay"
| "timeScope"
+ | "status"
> & { id?: string };
export const RAGAS_TEMPLATE_PREFIX = "__ragas__";
diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.ts
index e8a3e588ef..bb3a6d6c7b 100644
--- a/web/src/features/evals/utils/evaluator-form-utils.ts
+++ b/web/src/features/evals/utils/evaluator-form-utils.ts
@@ -20,6 +20,7 @@ export const evalConfigFormSchema = z.object({
sampling: z.coerce.number().gt(0).lte(1),
delay: z.coerce.number().min(0).optional().default(10),
timeScope: TimeScopeSchema,
+ runOnLive: z.boolean().optional().default(true),
});
export type EvalFormType = z.infer<typeof evalConfigFormSchema>;
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 3ba5de9a67..bdd9fb18ae 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -40,7 +40,7 @@ import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { BreakdownTooltip } from "@/src/components/trace2/components/_shared/BreakdownToolTip";
-import { InfoIcon, PlusCircle } from "lucide-react";
+import { InfoIcon, LightbulbIcon, PlusCircle } from "lucide-react";
import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
import { Badge } from "@/src/components/ui/badge";
@@ -82,6 +82,7 @@ import {
} from "@/src/components/table/data-table-refresh-button";
import useSessionStorage from "@/src/components/useSessionStorage";
import { api } from "@/src/utils/api";
+import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog/index";
export type EventsTableRow = {
// Identity fields
@@ -178,6 +179,7 @@ export default function ObservationsEventsTable({
useFullTextSearch();
const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");
+ const [showRunEvaluationDialog, setShowRunEvaluationDialog] = useState(false);
const [paginationState, setPaginationState] = usePaginationState(1, 50);
@@ -467,6 +469,17 @@ export default function ObservationsEventsTable({
scope: "annotationQueues:CUD",
},
},
+ {
+ id: ActionId.ObservationBatchEvaluation,
+ type: BatchActionType.Create,
+ label: "Evaluate",
+ description: "Run evaluations on selected observations.",
+ customDialog: true,
+ icon: <LightbulbIcon className="mr-2 h-4 w-4" />,
+ accessCheck: {
+ scope: "evalJob:CUD",
+ },
+ },
];
const enableSorting = !hideControls;
@@ -1215,6 +1228,11 @@ export default function ObservationsEventsTable({
projectId={projectId}
actions={tableActions}
tableName={BatchExportTableName.Observations}
+ onCustomAction={(actionType) => {
+ if (actionType === ActionId.ObservationBatchEvaluation) {
+ setShowRunEvaluationDialog(true);
+ }
+ }}
/>
) : null,
]}
@@ -1340,6 +1358,29 @@ export default function ObservationsEventsTable({
</ResizableFilterLayout>
{peekConfig && <TablePeekView peekView={peekConfig} />}
</div>
+
+ {showRunEvaluationDialog && (
+ <RunEvaluationDialog
+ projectId={projectId}
+ selectedObservationIds={(() => {
+ const rowIds = new Set(observations.rows?.map((o) => o.id));
+ return Object.keys(selectedRows).filter((id) => rowIds.has(id));
+ })()}
+ query={{
+ filter: filterState,
+ orderBy: orderByState,
+ searchQuery: searchQuery ?? undefined,
+ searchType,
+ }}
+ selectAll={selectAll}
+ totalCount={totalCount ?? 0}
+ onClose={() => {
+ setShowRunEvaluationDialog(false);
+ setSelectedRows({});
+ setSelectAll(false);
+ }}
+ />
+ )}
</DataTableControlsProvider>
);
}
diff --git a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
index 007996c0ff..f102bc5dff 100644
--- a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
+++ b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
@@ -1,5 +1,9 @@
import { Decimal } from "decimal.js";
-import { type EvalTemplate, EvalTargetObject } from "@langfuse/shared";
+import {
+ type EvalTemplate,
+ EvalTargetObject,
+ JobConfigState,
+} from "@langfuse/shared";
import { type PartialConfig } from "@/src/features/evals/types";
import { createDefaultVariableMappings } from "@/src/features/experiments/utils/evaluatorMappingUtils";
@@ -7,6 +11,7 @@ export const CONFIG_BASE = {
sampling: new Decimal(1),
delay: 30000,
timeScope: ["NEW"],
+ status: JobConfigState.ACTIVE,
};
export function useEvaluatorDefaults() {
diff --git a/web/src/features/table/server/createBatchActionJob.ts b/web/src/features/table/server/createBatchActionJob.ts
index eae7fe381c..8c22355fa3 100644
--- a/web/src/features/table/server/createBatchActionJob.ts
+++ b/web/src/features/table/server/createBatchActionJob.ts
@@ -16,7 +16,10 @@ import { TRPCError } from "@trpc/server";
type CreateBatchActionJob = {
projectId: string;
- actionId: Exclude<ActionId, "observation-add-to-dataset">;
+ actionId: Exclude<
+ ActionId,
+ "observation-add-to-dataset" | "observation-run-batched-evaluation"
+ >;
tableName: BatchExportTableName;
actionType: BatchActionType;
session: {
diff --git a/worker/package.json b/worker/package.json
index dd48e3eb73..32a0399a47 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -56,6 +56,7 @@
"jsonpath-plus": "10.3.0",
"kysely": "^0.27.4",
"lodash": "^4.17.23",
+ "p-limit": "^7.3.0",
"pg": "^8.13.0",
"posthog-node": "^5.8.4",
"stripe": "^17.4.0",
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 541f8d9bf7..4de7db54e0 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -10,10 +10,12 @@ import {
} from "@langfuse/shared/src/server";
import {
BatchActionType,
+ BatchActionStatus,
BatchTableNames,
FilterCondition,
EvalTargetObject,
} from "@langfuse/shared";
+import Decimal from "decimal.js";
import {
getDatabaseReadStreamPaginated,
getTraceIdentifierStream,
@@ -29,8 +31,10 @@ import { prisma } from "@langfuse/shared/src/db";
import { randomUUID } from "node:crypto";
import { processClickhouseScoreDelete } from "../scores/processClickhouseScoreDelete";
import { getObservationStream } from "../database-read-stream/observation-stream";
+import { getEventsStreamForEval } from "../database-read-stream/event-stream";
import { processAddObservationsToDataset } from "./processAddObservationsToDataset";
import { ObservationAddToDatasetConfigSchema } from "@langfuse/shared";
+import { processBatchedObservationEval } from "./processBatchedObservationEval";
const CHUNK_SIZE = 1000;
const convertDatesInFiltersFromStrings = (filters: FilterCondition[]) => {
@@ -355,6 +359,79 @@ export const handleBatchActionJob = async (
config: parsedConfig,
observations,
});
+ } else if (actionId === "observation-run-batched-evaluation") {
+ const { projectId, query, cutoffCreatedAt, evaluatorIds, batchActionId } =
+ batchActionEvent;
+
+ if (!batchActionId) {
+ throw new Error(
+ "batchActionId is required for observation-run-batched-evaluation action",
+ );
+ }
+
+ const selectedEvaluatorIds = Array.from(new Set(evaluatorIds));
+
+ let evaluators;
+ try {
+ const rawEvaluators = await prisma.jobConfiguration.findMany({
+ where: {
+ id: { in: selectedEvaluatorIds },
+ projectId,
+ targetObject: EvalTargetObject.EVENT,
+ // status may be both active or inactive, no need to filter
+ },
+ select: {
+ id: true,
+ projectId: true,
+ evalTemplateId: true,
+ scoreName: true,
+ targetObject: true,
+ variableMapping: true,
+ },
+ });
+
+ // For batch evaluation the user's table-level selection determines which
+ // observations to evaluate, so we intentionally set filter=[] and
+ // sampling=1 to ensure every streamed observation is evaluated.
+ evaluators = rawEvaluators.map((e) => ({
+ ...e,
+ filter: [] as [],
+ sampling: new Decimal(1),
+ }));
+ } catch (error) {
+ await prisma.batchAction.update({
+ where: { id: batchActionId },
+ data: {
+ status: BatchActionStatus.Failed,
+ finishedAt: new Date(),
+ totalCount: 0,
+ processedCount: 0,
+ failedCount: 0,
+ log:
+ error instanceof Error
+ ? error.message
+ : "Selected evaluators are missing or not observation-scoped for historical event evaluation.",
+ },
+ });
+
+ return;
+ }
+
+ const dbReadStream = await getEventsStreamForEval({
+ projectId,
+ cutoffCreatedAt: new Date(cutoffCreatedAt),
+ filter: convertDatesInFiltersFromStrings(query.filter ?? []),
+ searchQuery: query.searchQuery ?? undefined,
+ searchType: query.searchType ?? ["id", "content"],
+ rowLimit: env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
+ });
+
+ await processBatchedObservationEval({
+ projectId,
+ batchActionId,
+ evaluators,
+ observationStream: dbReadStream,
+ });
}
logger.info(
diff --git a/worker/src/features/batchAction/processBatchedObservationEval.test.ts b/worker/src/features/batchAction/processBatchedObservationEval.test.ts
new file mode 100644
index 0000000000..7dd34c438b
--- /dev/null
+++ b/worker/src/features/batchAction/processBatchedObservationEval.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
+import { EvalTargetObject } from "@langfuse/shared";
+import { type ObservationEvalConfig } from "../evaluation/observationEval";
+
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: {
+ batchAction: {
+ update: vi.fn().mockResolvedValue(undefined),
+ },
+ },
+}));
+
+vi.mock("../evaluation/observationEval", () => ({
+ createObservationEvalSchedulerDeps: vi.fn(() => ({ deps: true })),
+ scheduleObservationEvals: vi.fn().mockResolvedValue(undefined),
+}));
+
+import { prisma } from "@langfuse/shared/src/db";
+import { scheduleObservationEvals } from "../evaluation/observationEval";
+import { processBatchedObservationEval } from "./processBatchedObservationEval";
+
+describe("processBatchedObservationEval", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("passes evaluators with match-all filter and sampling to the scheduler", async () => {
+ const projectId = "project-1";
+ const batchActionId = "batch-action-1";
+
+ // Evaluators should already have filter=[] and sampling=1 set by the
+ // caller (handleBatchActionJob), so the scheduler applies its normal
+ // targeting logic and every observation matches.
+ const evaluators: ObservationEvalConfig[] = [
+ {
+ id: "config-1",
+ projectId,
+ filter: [],
+ sampling: { toNumber: () => 1 } as ObservationEvalConfig["sampling"],
+ evalTemplateId: "template-1",
+ scoreName: "quality",
+ targetObject: EvalTargetObject.EVENT,
+ variableMapping: [],
+ },
+ ];
+
+ const remappedRow: Record<string, unknown> = {
+ span_id: "obs-1",
+ trace_id: "trace-1",
+ project_id: projectId,
+ parent_span_id: null,
+ type: "GENERATION",
+ name: "test",
+ usage_details: {},
+ cost_details: {},
+ provided_usage_details: {},
+ provided_cost_details: {},
+ tags: [],
+ input: "input",
+ output: "output",
+ metadata: {},
+ };
+
+ const observationStream = (async function* () {
+ yield remappedRow;
+ })();
+
+ await processBatchedObservationEval({
+ projectId,
+ batchActionId,
+ evaluators,
+ observationStream,
+ });
+
+ expect(scheduleObservationEvals).toHaveBeenCalledTimes(1);
+ expect(scheduleObservationEvals).toHaveBeenCalledWith(
+ expect.objectContaining({
+ configs: evaluators,
+ }),
+ );
+ expect(
+ (prisma.batchAction.update as Mock).mock.calls.length,
+ ).toBeGreaterThan(0);
+ });
+});
diff --git a/worker/src/features/batchAction/processBatchedObservationEval.ts b/worker/src/features/batchAction/processBatchedObservationEval.ts
new file mode 100644
index 0000000000..20458dbe40
--- /dev/null
+++ b/worker/src/features/batchAction/processBatchedObservationEval.ts
@@ -0,0 +1,132 @@
+import pLimit from "p-limit";
+import { prisma } from "@langfuse/shared/src/db";
+import { BatchActionStatus, observationForEvalSchema } from "@langfuse/shared";
+import { logger, traceException } from "@langfuse/shared/src/server";
+import {
+ createObservationEvalSchedulerDeps,
+ scheduleObservationEvals,
+ type ObservationEvalConfig,
+} from "../evaluation/observationEval";
+
+const BATCH_SIZE = 500;
+const CONCURRENCY_LIMIT = 50;
+const MAX_ERROR_LOG_LINES = 20;
+
+export async function processBatchedObservationEval(params: {
+ projectId: string;
+ batchActionId: string;
+ evaluators: ObservationEvalConfig[];
+ observationStream: AsyncIterable<Record<string, unknown>>;
+}): Promise<void> {
+ const { projectId, batchActionId, evaluators, observationStream } = params;
+ const limit = pLimit(CONCURRENCY_LIMIT);
+ const schedulerDeps = createObservationEvalSchedulerDeps();
+
+ await prisma.batchAction.update({
+ where: { id: batchActionId, projectId },
+ data: {
+ status: BatchActionStatus.Processing,
+ totalCount: 0,
+ processedCount: 0,
+ failedCount: 0,
+ log: null,
+ },
+ });
+
+ let totalCount = 0;
+ let processedCount = 0;
+ let failedCount = 0;
+ const errors: string[] = [];
+
+ let buffer: Record<string, unknown>[] = [];
+
+ const processBatch = async (batch: Record<string, unknown>[]) => {
+ const results = await Promise.allSettled(
+ batch.map((record) =>
+ limit(async () => {
+ const observation = observationForEvalSchema.parse(record);
+ await scheduleObservationEvals({
+ observation,
+ configs: evaluators,
+ schedulerDeps,
+ });
+ }),
+ ),
+ );
+
+ for (let i = 0; i < results.length; i++) {
+ const result = results[i];
+
+ if (result.status === "fulfilled") {
+ processedCount++;
+ } else {
+ failedCount++;
+ traceException(result.reason);
+
+ if (errors.length < MAX_ERROR_LOG_LINES) {
+ const errorMessage =
+ result.reason instanceof Error
+ ? result.reason.message
+ : "Unknown error";
+ errors.push(
+ `Row ${totalCount - batch.length + i + 1}: ${errorMessage}`,
+ );
+ }
+ }
+ }
+
+ await prisma.batchAction.update({
+ where: { id: batchActionId, projectId },
+ data: { totalCount, processedCount, failedCount },
+ });
+ };
+
+ for await (const record of observationStream) {
+ buffer.push(record);
+ totalCount++;
+
+ if (buffer.length >= BATCH_SIZE) {
+ await processBatch(buffer);
+ buffer = [];
+ }
+ }
+
+ // Process remaining records
+ if (buffer.length > 0) {
+ await processBatch(buffer);
+ }
+
+ const finalStatus =
+ failedCount === 0
+ ? BatchActionStatus.Completed
+ : processedCount === 0
+ ? BatchActionStatus.Failed
+ : BatchActionStatus.Partial;
+
+ const errorSummary =
+ errors.length > 0
+ ? `${failedCount} observations failed while scheduling ${evaluators.length} evaluator(s): ${evaluators.map((evaluator) => evaluator.scoreName).join(", ")}.\n${errors.join("\n")}`
+ : null;
+
+ await prisma.batchAction.update({
+ where: { id: batchActionId, projectId },
+ data: {
+ status: finalStatus,
+ finishedAt: new Date(),
+ totalCount,
+ processedCount,
+ failedCount,
+ log: errorSummary,
+ },
+ });
+
+ logger.info(
+ `Completed observation-run-batched-evaluation action ${batchActionId}`,
+ {
+ totalCount,
+ processedCount,
+ failedCount,
+ finalStatus,
+ },
+ );
+}
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
index 2152a7ba7b..41f2bf1667 100644
--- a/worker/src/features/database-read-stream/event-stream.ts
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -337,3 +337,145 @@ export const getEventsStream = async (props: {
})(),
);
};
+
+/**
+ * Lightweight event stream for batch observation evaluation.
+ * Unlike getEventsStream, this:
+ * - Uses the "eval" field set (no time/latency/modelId columns)
+ * - Skips scores CTE and JOIN
+ * - Skips comment fetching
+ * - Maps ClickHouse rows to ObservationForEval at the stream boundary
+ */
+export const getEventsStreamForEval = async (props: {
+ projectId: string;
+ cutoffCreatedAt: Date;
+ filter: FilterCondition[] | null;
+ searchQuery?: string;
+ searchType?: TracingSearchType[];
+ rowLimit?: number;
+}): Promise<Readable> => {
+ const {
+ projectId,
+ cutoffCreatedAt,
+ filter = [],
+ searchQuery,
+ searchType,
+ rowLimit = env.LANGFUSE_MAX_HISTORIC_EVAL_CREATION_LIMIT,
+ } = props;
+
+ // Filter out score and comment filters since they're not relevant for eval
+ const eventOnlyFilters = (filter ?? []).filter((f) => {
+ const columnDef = eventsTableUiColumnDefinitions.find(
+ (col) => col.uiTableName === f.column || col.uiTableId === f.column,
+ );
+
+ return (
+ columnDef?.clickhouseTableName !== "scores" &&
+ columnDef?.clickhouseTableName !== "comments"
+ );
+ });
+
+ const eventsFilter = new FilterList(
+ createFilterFromFilterState(
+ [
+ ...eventOnlyFilters,
+ {
+ column: "startTime",
+ operator: "<" as const,
+ value: cutoffCreatedAt,
+ type: "datetime" as const,
+ },
+ ],
+ eventsTableUiColumnDefinitions,
+ ),
+ );
+
+ const appliedEventsFilter = eventsFilter.apply();
+
+ const search = clickhouseSearchCondition(searchQuery, searchType, "e", [
+ "span_id",
+ "name",
+ "user_id",
+ "session_id",
+ "trace_id",
+ ]);
+
+ const eventsQuery = new EventsQueryBuilder({ projectId })
+ .selectFieldSet("eval")
+ .selectIO(false)
+ .selectFieldSet("metadata")
+ .where(appliedEventsFilter)
+ .where(search)
+ .whereRaw("e.is_deleted = 0")
+ .orderByDefault()
+ .limitBy("e.span_id", "e.project_id")
+ .limit(rowLimit);
+
+ const { query, params: queryParams } = eventsQuery.buildWithParams();
+
+ // Matches the aliased columns from the "eval" field set + selectIO + selectFieldSet("metadata")
+ type EvalEventRow = {
+ id: string; // aliased from span_id
+ trace_id: string;
+ project_id: string;
+ parent_observation_id: string | null; // aliased from parent_span_id
+ type: string;
+ name: string | null;
+ environment: string | null;
+ version: string | null;
+ level: string;
+ status_message: string | null;
+ trace_name: string | null;
+ user_id: string | null;
+ session_id: string | null;
+ tags: string[];
+ release: string | null;
+ provided_model_name: string | null;
+ model_parameters: unknown;
+ prompt_id: string | null;
+ prompt_name: string | null;
+ prompt_version: number | null;
+ provided_usage_details: Record<string, number>;
+ usage_details: Record<string, number>;
+ provided_cost_details: Record<string, number>;
+ cost_details: Record<string, number>;
+ tool_definitions: Record<string, unknown>;
+ tool_calls: unknown[];
+ tool_call_names: string[];
+ input: unknown;
+ output: unknown;
+ metadata: Record<string, unknown> | null;
+ };
+
+ const asyncGenerator = queryClickhouseStream<EvalEventRow>({
+ query,
+ params: queryParams,
+ clickhouseConfigs: {
+ request_timeout: 180_000,
+ clickhouse_settings: {
+ http_send_timeout: 300,
+ http_receive_timeout: 300,
+ },
+ },
+ tags: {
+ feature: "batch-eval",
+ type: "event",
+ kind: "eval",
+ projectId,
+ },
+ });
+
+ // Remap ClickHouse aliases to schema field names.
+ // Schema validation is left to the consumer so per-row errors can be handled gracefully.
+ return Readable.from(
+ (async function* () {
+ for await (const row of asyncGenerator) {
+ yield {
+ ...row,
+ span_id: row.id,
+ parent_span_id: row.parent_observation_id,
+ };
+ }
+ })(),
+ );
+};
diff --git a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts
index af23bdd249..b7b39fb133 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts
@@ -97,7 +97,6 @@ export function createTestEvalConfig(
variableMapping: [
{ templateVariable: "output", selectedColumnId: "output" },
],
- delay: 0,
...overrides,
};
}
diff --git a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts
index 108a3d76e7..cbbf149e62 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/scheduleObservationEvals.test.ts
@@ -80,7 +80,6 @@ describe("scheduleObservationEvals", () => {
scoreName: "quality",
variableMapping: [],
targetObject: EvalTargetObject.EVENT,
- delay: 0,
...overrides,
});
diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
index df35de1176..93b2f2a633 100644
--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
@@ -42,8 +42,8 @@ export async function scheduleObservationEvals(
return;
}
- // Filter configs that match this observation (filter + sampling)
- // This is done before S3 upload to avoid unnecessary uploads
+ // Filter configs that match this observation (filter + sampling).
+ // This is done before S3 upload to avoid unnecessary uploads.
const matchingConfigs = configs.filter((config) => {
// Check filter
const isTargeted = evaluateFilter(observation, config);
diff --git a/worker/src/features/evaluation/observationEval/types.ts b/worker/src/features/evaluation/observationEval/types.ts
index 249ce8d087..41877f4ba4 100644
--- a/worker/src/features/evaluation/observationEval/types.ts
+++ b/worker/src/features/evaluation/observationEval/types.ts
@@ -28,7 +28,6 @@ export type ObservationEvalConfig = Pick<
| "scoreName"
| "targetObject"
| "variableMapping"
- | "delay"
>;
/**