Skip to content

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

feat(experiments): add support to trigger evals (#13240)

marliessophie4c2be93bd199
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.ts
index c9540805ef..030b260548 100644
--- a/packages/shared/src/eventsTable.ts
+++ b/packages/shared/src/eventsTable.ts
@@ -324,4 +324,10 @@ export const eventsTableCols: ColumnDefinition[] = [
internal: "length(e.tool_calls)",
nullable: true,
},
+ {
+ name: "Is Experiment Item Root Span",
+ id: "isExperimentItemRootSpan",
+ type: "boolean",
+ internal: "e.experiment_item_root_span_id = e.span_id",
+ },
];
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.ts
index 4d91c90797..2be4a011f3 100644
--- a/packages/shared/src/features/batchAction/types.ts
+++ b/packages/shared/src/features/batchAction/types.ts
@@ -25,6 +25,7 @@ export enum ActionId {
ObservationAddToAnnotationQueue = "observation-add-to-annotation-queue",
ObservationAddToDataset = "observation-add-to-dataset",
ObservationBatchEvaluation = "observation-run-batched-evaluation",
+ ExperimentCompare = "experiment-compare",
}
const ActionIdSchema = z.nativeEnum(ActionId);
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index fc8397bf9e..4c2bc32028 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -12,6 +12,35 @@ export type EvalTargetObject =
export const EvalTargetObjectSchema = z.enum(Object.values(EvalTargetObject));
+// Batch action source tables that support evaluation
+export const BatchEvalSourceTable = {
+ EVENTS: "events",
+ EXPERIMENT_ITEMS: "experiment-items",
+ EXPERIMENTS: "experiments",
+} as const;
+
+export type BatchEvalSourceTable =
+ (typeof BatchEvalSourceTable)[keyof typeof BatchEvalSourceTable];
+
+export const BatchEvalSourceTableSchema = z.enum([
+ BatchEvalSourceTable.EVENTS,
+ BatchEvalSourceTable.EXPERIMENT_ITEMS,
+ BatchEvalSourceTable.EXPERIMENTS,
+]);
+
+/**
+ * Maps a batch evaluation source table to its corresponding eval target object.
+ * - "events" → EvalTargetObject.EVENT (observation-scoped evaluators)
+ * - "experiment-items" / "experiments" → EvalTargetObject.EXPERIMENT (experiment-scoped evaluators)
+ */
+export function getEvalTargetObjectFromSourceTable(
+ sourceTable: BatchEvalSourceTable,
+): EvalTargetObject {
+ return sourceTable === BatchEvalSourceTable.EVENTS
+ ? EvalTargetObject.EVENT
+ : EvalTargetObject.EXPERIMENT;
+}
+
export const langfuseObjects = [
"trace",
"span",
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 3044402602..3a84e6c096 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
@@ -361,6 +361,9 @@ const FIELD_SETS = {
"toolDefinitions",
"toolCalls",
"toolCallNames",
+ "experimentId",
+ "experimentItemRootSpanId",
+ "experimentItemExpectedOutput",
],
// Experiment items field set
diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.ts
index 149ff2baac..0203f4dd98 100644
--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts
@@ -259,6 +259,12 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "events_proto",
clickhouseSelect: 'e."experiment_name"',
},
+ {
+ uiTableName: "Is Experiment Item Root Span",
+ uiTableId: "isExperimentItemRootSpan",
+ clickhouseTableName: "events_proto",
+ clickhouseSelect: "e.experiment_item_root_span_id = e.span_id",
+ },
{
uiTableName: "Available Tools",
uiTableId: "toolDefinitions",
diff --git a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
index 133e436e0b..bba93d257e 100644
--- a/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
+++ b/web/src/features/annotation-queues/server/annotationQueueItemsRouter.ts
@@ -40,7 +40,9 @@ const MAP_OBJECT_TYPE_TO_ACTION_PROPS: Record<
{
actionId: Exclude<
ActionId,
- ActionId.ObservationAddToDataset | ActionId.ObservationBatchEvaluation
+ | ActionId.ObservationAddToDataset
+ | ActionId.ObservationBatchEvaluation
+ | ActionId.ExperimentCompare
>;
tableName: BatchTableNames;
}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx
index 9cb5c54197..03cd86da81 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/ConfirmationStep.tsx
@@ -2,24 +2,72 @@ 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";
+import { BatchEvalSourceTable } from "@langfuse/shared";
type ConfirmationStepProps = {
projectId: string;
displayCount: number;
evaluators: Array<{ id: string; name: string }>;
+ hideCount: boolean;
+ sourceTable: BatchEvalSourceTable;
+ experimentCount?: number;
};
+/**
+ * Determines whether to show a cost disclaimer instead of the actual cost estimate.
+ * For experiments source, we can't accurately estimate cost because displayCount
+ * is the experiment count, not the actual observation count.
+ */
+function shouldShowCostDisclaimer(sourceTable: BatchEvalSourceTable): boolean {
+ return sourceTable === BatchEvalSourceTable.EXPERIMENTS;
+}
+
+/**
+ * Calculates the effective observation count for cost estimation.
+ * For experiment-items source, multiplies by experiment count since each item
+ * is evaluated once per experiment.
+ */
+function getEffectiveObservationCount(
+ displayCount: number,
+ sourceTable: BatchEvalSourceTable,
+ experimentCount?: number,
+): number {
+ if (
+ sourceTable === BatchEvalSourceTable.EXPERIMENT_ITEMS &&
+ experimentCount
+ ) {
+ return displayCount * experimentCount;
+ }
+ return displayCount;
+}
+
export function ConfirmationStep(props: ConfirmationStepProps) {
- const { projectId, displayCount, evaluators } = props;
+ const {
+ projectId,
+ displayCount,
+ evaluators,
+ hideCount,
+ sourceTable,
+ experimentCount,
+ } = props;
+
+ const showCostDisclaimer = shouldShowCostDisclaimer(sourceTable);
+ const effectiveObservationCount = getEffectiveObservationCount(
+ displayCount,
+ sourceTable,
+ experimentCount,
+ );
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>
+ {!hideCount && (
+ <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">
@@ -38,11 +86,22 @@ export function ConfirmationStep(props: ConfirmationStepProps) {
<Separator />
- <EstimatedCostRow
- projectId={projectId}
- evaluators={evaluators}
- observationCount={displayCount}
- />
+ {showCostDisclaimer ? (
+ <div className="flex gap-2">
+ <span className="text-muted-foreground shrink-0">
+ Est. LLM API Key Cost:
+ </span>
+ <span className="text-muted-foreground text-xs">
+ Cost estimate unavailable for experiment-scoped evaluations
+ </span>
+ </div>
+ ) : (
+ <EstimatedCostRow
+ projectId={projectId}
+ evaluators={evaluators}
+ observationCount={effectiveObservationCount}
+ />
+ )}
</CardContent>
</Card>
<p className="text-muted-foreground text-xs">
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx
index 2e2367aa85..d27fbb9a65 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/CreateEvaluatorDialog.tsx
@@ -1,5 +1,8 @@
import { useState } from "react";
-import { EvalTargetObject } from "@langfuse/shared";
+import {
+ EvalTargetObject,
+ type EvalTargetObject as EvalTargetObjectType,
+} from "@langfuse/shared";
import { api } from "@/src/utils/api";
import {
Dialog,
@@ -19,10 +22,16 @@ type CreateEvaluatorDialogProps = {
projectId: string;
open: boolean;
onOpenChange: (open: boolean) => void;
+ targetObject?: EvalTargetObjectType;
};
export function CreateEvaluatorDialog(props: CreateEvaluatorDialogProps) {
- const { projectId, open, onOpenChange } = props;
+ const {
+ projectId,
+ open,
+ onOpenChange,
+ targetObject = EvalTargetObject.EVENT,
+ } = props;
const [templateId, setTemplateId] = useState<string | null>(null);
const utils = api.useUtils();
@@ -49,10 +58,18 @@ export function CreateEvaluatorDialog(props: CreateEvaluatorDialogProps) {
<DialogContent className="max-h-[90vh] max-w-(--breakpoint-md) pb-0">
<DialogHeader>
<DialogTitle>
- Create Evaluator for batched observation runs
+ Create Evaluator for batched{" "}
+ {targetObject === EvalTargetObject.EVENT
+ ? "observation"
+ : "experiment"}{" "}
+ runs
</DialogTitle>
<DialogDescription>
- This form creates an evaluator for batched observation runs.
+ This form creates an evaluator for batched{" "}
+ {targetObject === EvalTargetObject.EVENT
+ ? "observation"
+ : "experiment"}{" "}
+ runs.
</DialogDescription>
</DialogHeader>
@@ -99,21 +116,22 @@ export function CreateEvaluatorDialog(props: CreateEvaluatorDialogProps) {
hideTargetSelection
hidePreviewTable
defaultRunOnLive={false}
+ defaultTarget={targetObject}
onFormSuccess={() => {
handleClose(false);
void utils.evals.jobConfigsByTarget.invalidate({
projectId,
- targetObject: EvalTargetObject.EVENT,
+ targetObject,
});
showSuccessToast({
title: "Evaluator created",
description:
- "Select it in the previous step to run it on selected observations.",
+ "Select it in the previous step to run it on selected items.",
});
}}
preprocessFormValues={(values) => ({
...values,
- target: EvalTargetObject.EVENT,
+ target: targetObject,
timeScope: ["NEW"],
...(values.runOnLive
? {}
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx
index ba4289c67d..19342b17bd 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/EvaluatorSelectionStep.tsx
@@ -12,6 +12,7 @@ import { Eye, Plus, X } from "lucide-react";
type Evaluator = RouterOutputs["evals"]["jobConfigsByTarget"][number];
type ObservationPreview = RouterOutputs["observations"]["byId"];
+type EventPreview = RouterOutputs["events"]["batchIO"][number];
type EvaluatorSelectionStepProps = {
eligibleEvaluators: Evaluator[];
@@ -19,8 +20,9 @@ type EvaluatorSelectionStepProps = {
isQueryLoading: boolean;
isQueryError: boolean;
queryErrorMessage: string | undefined;
- previewObservation: ObservationPreview | undefined;
+ previewObservation: ObservationPreview | EventPreview | undefined;
isPreviewLoading: boolean;
+ evaluatorScopeLabel: "observation" | "experiment";
selectedEvaluatorIds: string[];
evaluatorSearchQuery: string;
onSearchQueryChange: (query: string) => void;
@@ -37,6 +39,7 @@ export function EvaluatorSelectionStep(props: EvaluatorSelectionStepProps) {
queryErrorMessage,
previewObservation,
isPreviewLoading,
+ evaluatorScopeLabel,
selectedEvaluatorIds,
evaluatorSearchQuery,
onSearchQueryChange,
@@ -102,8 +105,8 @@ export function EvaluatorSelectionStep(props: EvaluatorSelectionStepProps) {
) : eligibleEvaluators.length === 0 ? (
<Card>
<CardContent className="text-muted-foreground p-4 text-sm">
- No observation-scoped evaluators found. Create a new
- observation-scoped evaluator and it will appear here.
+ No {evaluatorScopeLabel}-scoped evaluators found. Create a new{" "}
+ {evaluatorScopeLabel}-scoped evaluator and it will appear here.
</CardContent>
</Card>
) : (
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
index 1a5b5fda4c..71799b3f44 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx
@@ -1,5 +1,11 @@
import { useMemo, useState } from "react";
-import { EvalTargetObject, type BatchActionQuery } from "@langfuse/shared";
+import {
+ type BatchActionQuery,
+ type BatchEvalSourceTable,
+ EvalTargetObject,
+ BatchEvalSourceTable as SourceTable,
+ getEvalTargetObjectFromSourceTable,
+} from "@langfuse/shared";
import { api } from "@/src/utils/api";
import {
Dialog,
@@ -18,6 +24,7 @@ import { EvaluatorSelectionStep } from "./EvaluatorSelectionStep";
import { ConfirmationStep } from "./ConfirmationStep";
import { CreateEvaluatorDialog } from "./CreateEvaluatorDialog";
import { buildQueryWithSelectedIds } from "./utils";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
type RunEvaluationDialogProps = {
projectId: string;
@@ -26,18 +33,27 @@ type RunEvaluationDialogProps = {
selectAll: boolean;
totalCount: number;
onClose: () => void;
- exampleObservation: {
+ experimentCount?: number;
+ exampleObservation?: {
id: string;
traceId: string;
startTime?: Date;
};
+ sourceTable?: BatchEvalSourceTable;
};
type DialogStep = "select-evaluator" | "confirm";
export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
- const { projectId, selectedObservationIds, query, selectAll, totalCount } =
- props;
+ const { isBetaEnabled } = useV4Beta();
+ const {
+ projectId,
+ selectedObservationIds,
+ query,
+ selectAll,
+ totalCount,
+ sourceTable = SourceTable.EVENTS,
+ } = props;
const [step, setStep] = useState<DialogStep>("select-evaluator");
const [selectedEvaluatorIds, setSelectedEvaluatorIds] = useState<string[]>(
@@ -46,9 +62,12 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
const [evaluatorSearchQuery, setEvaluatorSearchQuery] = useState("");
const [showCreateDialog, setShowCreateDialog] = useState(false);
+ // Derive targetObject from sourceTable
+ const targetObject = getEvalTargetObjectFromSourceTable(sourceTable);
+
const evaluatorsQuery = api.evals.jobConfigsByTarget.useQuery({
projectId,
- targetObject: EvalTargetObject.EVENT,
+ targetObject,
});
const runEvaluationMutation =
@@ -59,26 +78,62 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
});
const displayCount = selectAll ? totalCount : selectedObservationIds.length;
+ // For experiments source, displayCount is experiment count, not item count
+ const isExperimentsSource = sourceTable === SourceTable.EXPERIMENTS;
+ const scopeLabel =
+ sourceTable === SourceTable.EVENTS ? "observation" : "experiment item";
+ const evaluatorScopeLabel =
+ targetObject === EvalTargetObject.EVENT ? "observation" : "experiment";
+ const experimentItemsExperimentCount =
+ sourceTable === SourceTable.EXPERIMENT_ITEMS
+ ? (props.experimentCount ?? 0)
+ : 0;
const previewObservationQuery = api.observations.byId.useQuery(
{
projectId,
- observationId: props.exampleObservation.id,
- traceId: props.exampleObservation.traceId,
- startTime: props.exampleObservation.startTime ?? null,
+ observationId: props.exampleObservation?.id as string,
+ traceId: props.exampleObservation?.traceId as string,
+ startTime: props.exampleObservation?.startTime ?? null,
},
{
- enabled: Boolean(
- props.exampleObservation.id && props.exampleObservation.traceId,
- ),
+ enabled:
+ !isBetaEnabled &&
+ Boolean(
+ props.exampleObservation?.id && props.exampleObservation?.traceId,
+ ),
+ },
+ );
+
+ const previewEventQuery = api.events.batchIO.useQuery(
+ {
+ projectId,
+ observations: [
+ {
+ id: props.exampleObservation?.id as string,
+ traceId: props.exampleObservation?.traceId as string,
+ },
+ ],
+ minStartTime: props.exampleObservation?.startTime as Date,
+ maxStartTime: props.exampleObservation?.startTime as Date,
+ truncated: false,
+ },
+ {
+ enabled:
+ isBetaEnabled &&
+ Boolean(
+ props.exampleObservation?.id &&
+ props.exampleObservation?.traceId &&
+ props.exampleObservation?.startTime,
+ ),
},
);
const eligibleEvaluators = useMemo(() => {
return (evaluatorsQuery.data ?? []).filter(
- (evaluator) => evaluator.targetObject === EvalTargetObject.EVENT,
+ (evaluator) => evaluator.targetObject === targetObject,
);
- }, [evaluatorsQuery.data]);
+ }, [evaluatorsQuery.data, targetObject]);
const selectedEvaluators = useMemo(
() =>
@@ -112,6 +167,7 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
projectId,
query: finalQuery,
evaluatorIds: selectedEvaluators.map((evaluator) => evaluator.id),
+ sourceTable,
});
} catch {
return;
@@ -119,7 +175,11 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
showSuccessToast({
title: "Evaluation queued",
- description: `Scheduled evaluation for ${displayCount} selected ${displayCount === 1 ? "observation" : "observations"} and ${selectedEvaluators.length} ${selectedEvaluators.length === 1 ? "evaluator" : "evaluators"}.`,
+ description: isExperimentsSource
+ ? `Scheduled evaluation for items from ${displayCount} selected experiment${displayCount === 1 ? "" : "s"} with ${selectedEvaluators.length} ${selectedEvaluators.length === 1 ? "evaluator" : "evaluators"}.`
+ : sourceTable === SourceTable.EXPERIMENT_ITEMS
+ ? `Scheduled evaluation for up to ${displayCount} experiment item${displayCount === 1 ? "" : "s"} across ${experimentItemsExperimentCount} experiment${experimentItemsExperimentCount === 1 ? "" : "s"} with ${selectedEvaluators.length} ${selectedEvaluators.length === 1 ? "evaluator" : "evaluators"}.`
+ : `Scheduled evaluation for ${displayCount} selected ${scopeLabel}${displayCount === 1 ? "" : "s"} with ${selectedEvaluators.length} ${selectedEvaluators.length === 1 ? "evaluator" : "evaluators"}.`,
link: {
href: `/project/${projectId}/settings/batch-actions`,
text: "View batch actions",
@@ -135,13 +195,16 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
<DialogContent className="flex max-h-[62vh] min-h-[38vh] max-w-2xl flex-col">
<DialogHeader>
<DialogTitle>
- Evaluate {displayCount} observation
- {displayCount === 1 ? "" : "s"}
+ {isExperimentsSource
+ ? `Evaluate items from ${displayCount} experiment${displayCount === 1 ? "" : "s"}`
+ : sourceTable === SourceTable.EXPERIMENT_ITEMS
+ ? `Evaluate up to ${displayCount} experiment item${displayCount === 1 ? "" : "s"} across ${experimentItemsExperimentCount} experiment${experimentItemsExperimentCount === 1 ? "" : "s"}`
+ : `Evaluate ${displayCount} ${scopeLabel}${displayCount === 1 ? "" : "s"}`}
</DialogTitle>
<DialogDescription>
{step === "confirm"
? "Review your evaluation configuration before running."
- : "Select one or more observation-scoped evaluators."}
+ : `Select one or more ${evaluatorScopeLabel}-scoped evaluators.`}
</DialogDescription>
</DialogHeader>
@@ -153,8 +216,16 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
isQueryLoading={evaluatorsQuery.isLoading}
isQueryError={evaluatorsQuery.isError}
queryErrorMessage={evaluatorsQuery.error?.message}
- previewObservation={previewObservationQuery.data}
- isPreviewLoading={previewObservationQuery.isLoading}
+ previewObservation={
+ isBetaEnabled
+ ? previewEventQuery.data?.[0]
+ : previewObservationQuery.data
+ }
+ isPreviewLoading={
+ previewObservationQuery.isLoading ||
+ previewEventQuery.isLoading
+ }
+ evaluatorScopeLabel={evaluatorScopeLabel}
selectedEvaluatorIds={selectedEvaluatorIds}
evaluatorSearchQuery={evaluatorSearchQuery}
onSearchQueryChange={setEvaluatorSearchQuery}
@@ -169,6 +240,9 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
id: e.id,
name: e.scoreName,
}))}
+ hideCount={targetObject === EvalTargetObject.EXPERIMENT}
+ sourceTable={sourceTable}
+ experimentCount={experimentItemsExperimentCount}
/>
)}
</DialogBody>
@@ -213,6 +287,7 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {
projectId={projectId}
open={showCreateDialog}
onOpenChange={setShowCreateDialog}
+ targetObject={targetObject}
/>
</>
);
diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
index da3a0e9686..ed1bcf4920 100644
--- a/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/utils.ts
@@ -6,6 +6,7 @@ import {
import { type RouterOutputs } from "@/src/utils/api";
type ObservationPreview = RouterOutputs["observations"]["byId"];
+type EventPreview = RouterOutputs["events"]["batchIO"][number];
const PROMPT_PREVIEW_CHAR_LIMIT = 2000;
@@ -30,7 +31,7 @@ export function stringifyPreviewValue(value: unknown): string {
export function renderPromptPreviewFromObservation(params: {
prompt: string | null | undefined;
variableMapping: ObservationVariableMapping[];
- observation: ObservationPreview;
+ observation: ObservationPreview | EventPreview;
}): string {
const { prompt, variableMapping, observation } = params;
diff --git a/web/src/features/batch-actions/server/runEvaluationRouter.ts b/web/src/features/batch-actions/server/runEvaluationRouter.ts
index 7676cfa611..0d655774ab 100644
--- a/web/src/features/batch-actions/server/runEvaluationRouter.ts
+++ b/web/src/features/batch-actions/server/runEvaluationRouter.ts
@@ -15,7 +15,8 @@ import {
BatchTableNames,
BatchActionStatus,
ActionId,
- EvalTargetObject,
+ BatchEvalSourceTable,
+ getEvalTargetObjectFromSourceTable,
} from "@langfuse/shared";
import { env } from "@/src/env.mjs";
import { CreateObservationBatchEvaluationActionSchema } from "../validation";
@@ -31,7 +32,12 @@ export const runEvaluationRouter = createTRPCRouter({
scope: "evalJob:CUD",
});
- const { projectId, query, evaluatorIds: rawEvaluatorIds } = input;
+ const {
+ projectId,
+ query,
+ evaluatorIds: rawEvaluatorIds,
+ sourceTable = BatchEvalSourceTable.EVENTS,
+ } = input;
if (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS !== "true") {
throw new TRPCError({
@@ -40,6 +46,13 @@ export const runEvaluationRouter = createTRPCRouter({
});
}
+ // Derive targetObject from sourceTable
+ const targetObject = getEvalTargetObjectFromSourceTable(sourceTable);
+ const scopeLabel =
+ sourceTable === BatchEvalSourceTable.EVENTS
+ ? "observation"
+ : "experiment";
+
const requestedEvaluatorIds = Array.from(new Set(rawEvaluatorIds));
const evaluatorIds = (
@@ -49,7 +62,7 @@ export const runEvaluationRouter = createTRPCRouter({
in: requestedEvaluatorIds,
},
projectId,
- targetObject: EvalTargetObject.EVENT,
+ targetObject,
},
select: {
id: true,
@@ -67,8 +80,8 @@ export const runEvaluationRouter = createTRPCRouter({
code: "BAD_REQUEST",
message:
missingEvaluatorIds.length > 0
- ? `Evaluators [${missingEvaluatorIds.join(", ")}] are missing or not observation-scoped.`
- : "Selected evaluators are missing or not observation-scoped.",
+ ? `Evaluators [${missingEvaluatorIds.join(", ")}] are missing or not ${scopeLabel}-scoped.`
+ : `Selected evaluators are missing or not ${scopeLabel}-scoped.`,
});
}
diff --git a/web/src/features/batch-actions/validation.ts b/web/src/features/batch-actions/validation.ts
index 5f5abb0df3..b74c39fcd6 100644
--- a/web/src/features/batch-actions/validation.ts
+++ b/web/src/features/batch-actions/validation.ts
@@ -3,6 +3,7 @@ import {
AddToDatasetMappingSchema,
ObservationAddToDatasetConfigSchema,
BatchActionQuerySchema,
+ BatchEvalSourceTableSchema,
} from "@langfuse/shared";
export const CreateObservationAddToDatasetActionSchema = z.object({
@@ -15,6 +16,7 @@ export const CreateObservationBatchEvaluationActionSchema = z.object({
projectId: z.string(),
query: BatchActionQuerySchema,
evaluatorIds: z.array(z.string()).min(1),
+ sourceTable: BatchEvalSourceTableSchema.default("events"),
});
export const ValidateBatchAddToDatasetMappingSchema = z.object({
diff --git a/web/src/features/evals/components/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsx
index a0ca4584e2..34eb9db4dd 100644
--- a/web/src/features/evals/components/evaluator-form.tsx
+++ b/web/src/features/evals/components/evaluator-form.tsx
@@ -1,4 +1,4 @@
-import { type EvalTemplate } from "@langfuse/shared";
+import { type EvalTemplate, type EvalTargetObject } from "@langfuse/shared";
import { InnerEvaluatorForm } from "@/src/features/evals/components/inner-evaluator-form";
import { type PartialConfig } from "@/src/features/evals/types";
import { useEvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";
@@ -20,6 +20,7 @@ export const EvaluatorForm = (props: {
preprocessFormValues?: (values: any) => any;
defaultRunOnLive?: boolean;
hidePreviewTable?: boolean;
+ defaultTarget?: EvalTargetObject;
}) => {
const evalCapabilities = useEvalCapabilities(props.projectId);
@@ -54,6 +55,7 @@ export const EvaluatorForm = (props: {
evalCapabilities={evalCapabilities}
defaultRunOnLive={props.defaultRunOnLive}
hidePreviewTable={props.hidePreviewTable}
+ defaultTarget={props.defaultTarget}
/>
)}
</>
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index 642ec90509..a511cd2d9b 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -271,6 +271,7 @@ export const InnerEvaluatorForm = (props: {
hidePreviewTable?: boolean;
evalCapabilities: EvalCapabilities;
defaultRunOnLive?: boolean;
+ defaultTarget?: EvalTargetObject;
renderFooter?: (params: {
isLoading: boolean;
formError: string | null;
@@ -308,14 +309,19 @@ export const InnerEvaluatorForm = (props: {
defaultValues: {
scoreName:
props.existingEvaluator?.scoreName ?? `${props.evalTemplate.name}`,
- target: props.existingEvaluator?.targetObject ?? EvalTargetObject.EVENT,
+ target:
+ props.existingEvaluator?.targetObject ??
+ props.defaultTarget ??
+ EvalTargetObject.EVENT,
filter: props.existingEvaluator?.filter
? z.array(singleFilter).parse(props.existingEvaluator.filter)
- : (props.existingEvaluator?.targetObject ?? EvalTargetObject.EVENT) ===
- EvalTargetObject.TRACE
+ : (props.existingEvaluator?.targetObject ??
+ props.defaultTarget ??
+ EvalTargetObject.EVENT) === EvalTargetObject.TRACE
? // For new trace evaluators, exclude internal environments by default
DEFAULT_TRACE_FILTER
: (props.existingEvaluator?.targetObject ??
+ props.defaultTarget ??
EvalTargetObject.EVENT) === EvalTargetObject.EVENT
? // For new observation evaluators, default to GENERATION type
DEFAULT_OBSERVATION_FILTER
diff --git a/web/src/features/experiments/components/table/ExperimentGridView.tsx b/web/src/features/experiments/components/table/ExperimentGridView.tsx
index 797252bd04..8320e1f904 100644
--- a/web/src/features/experiments/components/table/ExperimentGridView.tsx
+++ b/web/src/features/experiments/components/table/ExperimentGridView.tsx
@@ -16,6 +16,7 @@ import {
type OnChangeFn,
type PaginationState,
type VisibilityState,
+ type RowSelectionState,
} from "@tanstack/react-table";
import { useExperimentNames } from "@/src/features/experiments/hooks/useExperimentNames";
import { cn } from "@/src/utils/tailwind";
@@ -47,6 +48,10 @@ type ExperimentGridViewProps = {
};
noResultsMessage?: ReactNode;
peekView?: DataTablePeekViewProps;
+ // Selection props
+ selectActionColumn?: LangfuseColumnDef<ExperimentItemsTableRow>;
+ rowSelection: RowSelectionState;
+ setRowSelection: OnChangeFn<RowSelectionState>;
};
/**
@@ -67,6 +72,9 @@ export const ExperimentGridView = ({
pagination,
noResultsMessage,
peekView,
+ selectActionColumn,
+ rowSelection,
+ setRowSelection,
}: ExperimentGridViewProps) => {
// Build all experiment IDs (baseline first)
const allExperimentIds = useMemo(
@@ -165,9 +173,11 @@ export const ExperimentGridView = ({
useExperimentColors,
]);
- // Build all columns: Input, Expected Output, then experiment columns
+ // Build all columns: Select, Input, Expected Output, then experiment columns
const columns: LangfuseColumnDef<ExperimentItemsTableRow>[] = useMemo(
() => [
+ // Include select column if provided
+ ...(selectActionColumn ? [selectActionColumn] : []),
{
accessorKey: "input",
id: "input",
@@ -199,7 +209,7 @@ export const ExperimentGridView = ({
},
...experimentColumns,
],
- [experimentColumns, isLoading],
+ [experimentColumns, isLoading, selectActionColumn],
);
return (
@@ -218,6 +228,8 @@ export const ExperimentGridView = ({
topAlignCells
peekView={peekView}
columnVisibility={columnVisibility}
+ rowSelection={rowSelection}
+ setRowSelection={setRowSelection}
/>
);
};
diff --git a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx b/web/src/features/experiments/components/table/ExperimentItemsTable.tsx
index 4f6b22449a..9810cd96a9 100644
--- a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx
+++ b/web/src/features/experiments/components/table/ExperimentItemsTable.tsx
@@ -6,6 +6,11 @@ import {
} from "@/src/components/table/data-table-controls";
import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";
import { useEffect, useMemo, useState, useRef, useCallback } from "react";
+import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog";
+import { LightbulbIcon } from "lucide-react";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
+import { type TableAction } from "@/src/features/table/types";
import { usePaginationState } from "@/src/hooks/usePaginationState";
import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
import {
@@ -17,6 +22,9 @@ import {
type FilterState,
type FilterCondition,
TableViewPresetTableName,
+ BatchExportTableName,
+ ActionId,
+ BatchActionType,
} from "@langfuse/shared";
import { ExperimentFilterPills } from "./ExperimentFilterPills";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
@@ -220,6 +228,11 @@ export default function ExperimentItemsTable({
}: ExperimentItemsTableProps) {
const { setDetailPageList } = useDetailPageLists();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
+ const [showRunEvaluationDialog, setShowRunEvaluationDialog] = useState(false);
+ const hasEvalAccess = useHasProjectAccess({
+ projectId,
+ scope: "evalJob:CUD",
+ });
const {
baselineId,
@@ -910,6 +923,87 @@ export default function ExperimentItemsTable({
[paginationState, setPaginationState, totalCount],
);
+ // Compute selected observation IDs for batch evaluation
+ const selectedObservationIds = useMemo(() => {
+ const selectedItemIds = Object.keys(selectedRows);
+ return (
+ rows
+ ?.filter((row) => selectedItemIds.includes(row.itemId))
+ .flatMap((row) => row.experiments.map((exp) => exp.observationId))
+ .filter((id): id is string => Boolean(id)) ?? []
+ );
+ }, [selectedRows, rows]);
+
+ // Get example observation for preview in the evaluation dialog
+ const exampleObservation = useMemo(() => {
+ // Find first experiment with a non-null observationId from selected rows
+ for (const row of rows ?? []) {
+ if (!selectedRows[row.itemId]) continue;
+ for (const exp of row.experiments) {
+ if (exp.observationId && exp.traceId) {
+ return {
+ id: exp.observationId,
+ traceId: exp.traceId,
+ startTime: exp.startTime,
+ };
+ }
+ }
+ }
+ return undefined;
+ }, [rows, selectedRows]);
+
+ // Count of selected items (not observations) for display
+ const selectedItemCount = useMemo(() => {
+ return Object.keys(selectedRows).filter((itemId) =>
+ rows?.some((row) => row.itemId === itemId),
+ ).length;
+ }, [selectedRows, rows]);
+
+ // Build query for batch actions (includes experiment context filter and root span filter)
+ const batchActionQuery = useMemo(
+ () => ({
+ filter: [
+ ...filtersByExperiment.flatMap((f) => f.filters),
+ // Include experiment context filter
+ ...(allExperimentIds.length > 0
+ ? [
+ {
+ column: "experimentId" as const,
+ operator: "any of" as const,
+ value: allExperimentIds,
+ type: "stringOptions" as const,
+ },
+ ]
+ : []),
+ // Only target root spans of experiment items
+ {
+ column: "isExperimentItemRootSpan" as const,
+ operator: "=" as const,
+ value: true,
+ type: "boolean" as const,
+ },
+ ],
+ orderBy: orderByState,
+ }),
+ [filtersByExperiment, orderByState, allExperimentIds],
+ );
+
+ const tableActions: TableAction[] = hasEvalAccess
+ ? [
+ {
+ id: ActionId.ObservationBatchEvaluation,
+ type: BatchActionType.Create,
+ label: "Evaluate",
+ description: "Run evaluators on selected items",
+ icon: <LightbulbIcon className="mr-2 h-4 w-4" />,
+ customDialog: true,
+ accessCheck: {
+ scope: "evalJob:CUD",
+ },
+ } as TableAction,
+ ]
+ : [];
+
return (
<DataTableControlsProvider
tableName={experimentItemsFilterConfig.tableName}
@@ -947,6 +1041,23 @@ export default function ExperimentItemsTable({
pageSize: paginationState.pageSize,
pageIndex: paginationState.pageIndex,
}}
+ actionButtons={
+ (selectAll || selectedItemCount > 0) && tableActions.length > 0
+ ? [
+ <TableActionMenu
+ key="experiment-items-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ onCustomAction={(actionId) => {
+ if (actionId === ActionId.ObservationBatchEvaluation) {
+ setShowRunEvaluationDialog(true);
+ }
+ }}
+ />,
+ ]
+ : undefined
+ }
/>
)}
@@ -981,6 +1092,11 @@ export default function ExperimentItemsTable({
traceScoreOrder={traceScoreOrder}
peekView={peekConfig}
columnVisibility={columnVisibility}
+ selectActionColumn={
+ hideControls ? undefined : selectActionColumn
+ }
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
/>
) : (
<div className="flex flex-1 items-center justify-center">
@@ -1021,6 +1137,29 @@ export default function ExperimentItemsTable({
{/* Peek view panel */}
{peekConfig && <TablePeekView peekView={peekConfig} />}
+
+ {/* Run Evaluation Dialog */}
+ {showRunEvaluationDialog && (
+ <RunEvaluationDialog
+ projectId={projectId}
+ selectedObservationIds={selectedObservationIds}
+ query={batchActionQuery}
+ selectAll={selectAll}
+ totalCount={
+ selectAll
+ ? (totalCount ?? 0) * allExperimentIds.length
+ : selectedItemCount
+ }
+ onClose={() => {
+ setShowRunEvaluationDialog(false);
+ setSelectedRows({});
+ setSelectAll(false);
+ }}
+ experimentCount={allExperimentIds.length}
+ exampleObservation={exampleObservation}
+ sourceTable="experiment-items"
+ />
+ )}
</div>
</DataTableControlsProvider>
);
diff --git a/web/src/features/experiments/components/table/ExperimentsTable.tsx b/web/src/features/experiments/components/table/ExperimentsTable.tsx
index 34e9845eeb..b00ea3c2dd 100644
--- a/web/src/features/experiments/components/table/ExperimentsTable.tsx
+++ b/web/src/features/experiments/components/table/ExperimentsTable.tsx
@@ -15,17 +15,24 @@ import {
isExperimentsOmittableFilterColumn,
} from "./filter-config";
import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { type FilterState, TableViewPresetTableName } from "@langfuse/shared";
+import {
+ type FilterState,
+ TableViewPresetTableName,
+ BatchExportTableName,
+ ActionId,
+ BatchActionType,
+} from "@langfuse/shared";
import { numberFormatter } from "@/src/utils/numbers";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
-import { GitCompareArrows } from "lucide-react";
+import { GitCompareArrows, LightbulbIcon } from "lucide-react";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
import Link from "next/link";
-import { Button } from "@/src/components/ui/button";
+import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
+import { type TableAction } from "@/src/features/table/types";
import { Badge } from "@/src/components/ui/badge";
import { type RowSelectionState } from "@tanstack/react-table";
import TableIdOrName from "@/src/components/table/table-id";
@@ -34,7 +41,6 @@ import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import { useRouter } from "next/router";
import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";
-import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";
import { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
@@ -45,6 +51,8 @@ import {
import { useExperimentsTableData } from "../../hooks/useExperimentsTableData";
import { type ExperimentsTableRow, type ExperimentsTableProps } from "./types";
import { useExperimentFilterOptions } from "../../hooks/useExperimentFilterOptions";
+import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
export default function ExperimentsTable({
projectId,
@@ -65,8 +73,12 @@ export default function ExperimentsTable({
const { setDetailPageList } = useDetailPageLists();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
+ const [showRunEvaluationDialog, setShowRunEvaluationDialog] = useState(false);
- const { selectAll, setSelectAll } = useSelectAll(projectId, "experiments");
+ const hasEvalAccess = useHasProjectAccess({
+ projectId,
+ scope: "evalJob:CUD",
+ });
const [paginationState, setPaginationState] = usePaginationState(1, 50);
@@ -496,6 +508,31 @@ export default function ExperimentsTable({
.map((row) => row.id);
}, [selectedRows, rows]);
+ // Build query with experiment context filter for batch actions
+ const batchActionQuery = useMemo(
+ () => ({
+ filter:
+ selectedExperimentIds.length > 0
+ ? [
+ {
+ column: "experimentId" as const,
+ operator: "any of" as const,
+ value: selectedExperimentIds,
+ type: "stringOptions" as const,
+ },
+ {
+ column: "isExperimentItemRootSpan" as const,
+ operator: "=" as const,
+ value: true,
+ type: "boolean" as const,
+ },
+ ]
+ : [],
+ orderBy: { column: "startTime" as const, order: "DESC" as const },
+ }),
+ [selectedExperimentIds],
+ );
+
// Handler for comparing selected experiments
// First selected becomes baseline, rest become comparisons
const handleCompareSelected = useCallback(() => {
@@ -513,130 +550,196 @@ export default function ExperimentsTable({
);
}, [selectedExperimentIds, projectId, router]);
+ // Build table actions - Compare is disabled (not hidden) when >5 rows selected
+ const tableActions: TableAction[] = useMemo(() => {
+ const actions: TableAction[] = [];
+
+ // Compare action: disabled when >5 experiments selected
+ const tooManySelected = selectedExperimentIds.length > 5;
+ actions.push({
+ id: ActionId.ExperimentCompare,
+ type: BatchActionType.Create,
+ label: "Compare",
+ description: "Compare selected experiments",
+ icon: <GitCompareArrows className="mr-2 h-4 w-4" />,
+ customDialog: true,
+ disabled: tooManySelected,
+ disabledReason: tooManySelected
+ ? "Select only up to 5 experiments to compare"
+ : undefined,
+ accessCheck: {
+ scope: "project:read",
+ },
+ } as TableAction);
+
+ // Run Evaluator action: only when user has eval access
+ if (hasEvalAccess) {
+ actions.push({
+ id: ActionId.ObservationBatchEvaluation,
+ type: BatchActionType.Create,
+ label: "Run Evaluator",
+ description: "Run evaluators on selected experiments",
+ icon: <LightbulbIcon className="mr-2 h-4 w-4" />,
+ customDialog: true,
+ accessCheck: {
+ scope: "evalJob:CUD",
+ },
+ } as TableAction);
+ }
+
+ return actions;
+ }, [selectedExperimentIds.length, hasEvalAccess]);
+
+ const shouldShowActions =
+ selectedExperimentIds.length > 0 && tableActions.length > 0;
+
return (
- <DataTableControlsProvider>
- <div className="flex h-full w-full flex-col">
- {/* Toolbar spanning full width */}
- <DataTableToolbar
- columns={columns}
- filterState={queryFilter.filterState}
- viewConfig={{
- tableName: TableViewPresetTableName.Experiments,
- projectId,
- controllers: viewControllers,
- }}
- columnsWithCustomSelect={["name", "datasetId"]}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibilityState}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- orderByState={orderByState}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds:
- Object.keys(selectedRows).filter((experimentId) =>
- experiments.rows?.map((e) => e.id).includes(experimentId),
- ) ?? [],
- setRowSelection: setSelectedRows,
- totalCount,
- pageSize: paginationState.limit,
- pageIndex: paginationState.page - 1,
- }}
- actionButtons={
- selectedExperimentIds.length > 0
- ? [
- <Button
- key="compare-selected"
- variant="outline"
- onClick={handleCompareSelected}
- className="gap-1"
- >
- <GitCompareArrows className="h-4 w-4" />
- Compare ({selectedExperimentIds.length})
- </Button>,
- ]
- : undefined
- }
- />
+ <>
+ <DataTableControlsProvider>
+ <div className="flex h-full w-full flex-col">
+ {/* Toolbar spanning full width */}
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Experiments,
+ projectId,
+ controllers: viewControllers,
+ }}
+ columnsWithCustomSelect={["name", "datasetId"]}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibilityState}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ orderByState={orderByState}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ multiSelect={{
+ selectAll: false,
+ setSelectAll: () => {},
+ totalCount,
+ selectedRowIds:
+ Object.keys(selectedRows).filter((experimentId) =>
+ experiments.rows?.map((e) => e.id).includes(experimentId),
+ ) ?? [],
+ setRowSelection: setSelectedRows,
+ pageSize: paginationState.limit,
+ pageIndex: paginationState.page - 1,
+ }}
+ actionButtons={
+ shouldShowActions
+ ? [
+ <TableActionMenu
+ key="experiments-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Sessions}
+ onCustomAction={(actionId) => {
+ if (actionId === ActionId.ExperimentCompare) {
+ handleCompareSelected();
+ } else if (
+ actionId === ActionId.ObservationBatchEvaluation
+ ) {
+ setShowRunEvaluationDialog(true);
+ }
+ }}
+ />,
+ ]
+ : undefined
+ }
+ />
- {/* Content area with sidebar and table */}
- <ResizableFilterLayout>
- <DataTableControls queryFilter={queryFilter} />
-
- <div className="flex flex-1 flex-col overflow-hidden">
- <DataTable
- key={`experiments-table-${dataUpdatedAt}`}
- tableName={"experiments"}
- columns={columns}
- data={
- experiments.status === "loading" || isViewLoading
- ? { isLoading: true, isError: false }
- : experiments.status === "error"
- ? {
- isLoading: false,
- isError: true,
- error: "",
- }
- : {
- isLoading: false,
- isError: false,
- data: rows,
- }
- }
- pagination={{
- totalCount,
- onChange: (updater) => {
- const newState =
- typeof updater === "function"
- ? updater({
- pageIndex: paginationState.page - 1,
- pageSize: paginationState.limit,
- })
- : updater;
- setPaginationState({
- page: newState.pageIndex + 1,
- limit: newState.pageSize,
- });
- },
- state: {
- pageIndex: paginationState.page - 1,
- pageSize: paginationState.limit,
- },
- }}
- rowSelection={selectedRows}
- setRowSelection={setSelectedRows}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibilityState}
- rowHeight={rowHeight}
- onRowClick={(row, event) => {
- // Handle Command/Ctrl+click to open experiment in new tab
- if (event && (event.metaKey || event.ctrlKey)) {
- event.preventDefault();
- const experimentId = row.id;
- const experimentUrl = `/project/${projectId}/experiments/results?baseline=${encodeURIComponent(experimentId)}`;
- const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${experimentUrl}`;
- window.open(fullUrl, "_blank");
- }
- // For normal clicks, navigate to experiment detail page
- else {
- void router.push(
- `/project/${projectId}/experiments/results?baseline=${encodeURIComponent(row.id)}`,
- );
+ {/* Content area with sidebar and table */}
+ <ResizableFilterLayout>
+ <DataTableControls queryFilter={queryFilter} />
+
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <DataTable
+ key={`experiments-table-${dataUpdatedAt}`}
+ tableName={"experiments"}
+ columns={columns}
+ data={
+ experiments.status === "loading" || isViewLoading
+ ? { isLoading: true, isError: false }
+ : experiments.status === "error"
+ ? {
+ isLoading: false,
+ isError: true,
+ error: "",
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: rows,
+ }
}
- }}
- />
- </div>
- </ResizableFilterLayout>
- </div>
- </DataTableControlsProvider>
+ pagination={{
+ totalCount,
+ onChange: (updater) => {
+ const newState =
+ typeof updater === "function"
+ ? updater({
+ pageIndex: paginationState.page - 1,
+ pageSize: paginationState.limit,
+ })
+ : updater;
+ setPaginationState({
+ page: newState.pageIndex + 1,
+ limit: newState.pageSize,
+ });
+ },
+ state: {
+ pageIndex: paginationState.page - 1,
+ pageSize: paginationState.limit,
+ },
+ }}
+ rowSelection={selectedRows}
+ setRowSelection={setSelectedRows}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibilityState}
+ rowHeight={rowHeight}
+ onRowClick={(row, event) => {
+ // Handle Command/Ctrl+click to open experiment in new tab
+ if (event && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ const experimentId = row.id;
+ const experimentUrl = `/project/${projectId}/experiments/results?baseline=${encodeURIComponent(experimentId)}`;
+ const fullUrl = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${experimentUrl}`;
+ window.open(fullUrl, "_blank");
+ }
+ // For normal clicks, navigate to experiment detail page
+ else {
+ void router.push(
+ `/project/${projectId}/experiments/results?baseline=${encodeURIComponent(row.id)}`,
+ );
+ }
+ }}
+ />
+ </div>
+ </ResizableFilterLayout>
+ </div>
+ </DataTableControlsProvider>
+
+ {showRunEvaluationDialog && selectedExperimentIds.length > 0 && (
+ <RunEvaluationDialog
+ projectId={projectId}
+ selectedObservationIds={[]}
+ query={batchActionQuery}
+ selectAll={true}
+ totalCount={selectedExperimentIds.length}
+ onClose={() => {
+ setShowRunEvaluationDialog(false);
+ setSelectedRows({});
+ }}
+ sourceTable="experiments"
+ />
+ )}
+ </>
);
}
diff --git a/web/src/features/table/components/TableActionMenu.tsx b/web/src/features/table/components/TableActionMenu.tsx
index 58d8346fd5..87b63402d9 100644
--- a/web/src/features/table/components/TableActionMenu.tsx
+++ b/web/src/features/table/components/TableActionMenu.tsx
@@ -14,6 +14,11 @@ import {
} from "@/src/features/table/types";
import { TableActionDialog } from "@/src/features/table/components/TableActionDialog";
import { type BatchExportTableName } from "@langfuse/shared";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
type TableActionMenuProps = {
projectId: string;
@@ -64,15 +69,33 @@ export function TableActionMenu({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
- {actions.map((action) => (
- <DropdownMenuItem
- key={action.id}
- onClick={() => handleActionSelect(action)}
- >
- {action.icon || getDefaultIcon(action.type)}
- <span>{action.label}</span>
- </DropdownMenuItem>
- ))}
+ {actions.map((action) => {
+ const menuItem = (
+ <DropdownMenuItem
+ key={action.id}
+ onClick={() => handleActionSelect(action)}
+ disabled={action.disabled}
+ >
+ {action.icon || getDefaultIcon(action.type)}
+ <span>{action.label}</span>
+ </DropdownMenuItem>
+ );
+
+ if (action.disabled && action.disabledReason) {
+ return (
+ <Tooltip key={action.id}>
+ <TooltipTrigger asChild>
+ <span>{menuItem}</span>
+ </TooltipTrigger>
+ <TooltipContent side="left">
+ {action.disabledReason}
+ </TooltipContent>
+ </Tooltip>
+ );
+ }
+
+ return menuItem;
+ })}
</DropdownMenuContent>
</DropdownMenu>
diff --git a/web/src/features/table/server/createBatchActionJob.ts b/web/src/features/table/server/createBatchActionJob.ts
index 8c22355fa3..fd132725dd 100644
--- a/web/src/features/table/server/createBatchActionJob.ts
+++ b/web/src/features/table/server/createBatchActionJob.ts
@@ -18,7 +18,9 @@ type CreateBatchActionJob = {
projectId: string;
actionId: Exclude<
ActionId,
- "observation-add-to-dataset" | "observation-run-batched-evaluation"
+ | "observation-add-to-dataset"
+ | "observation-run-batched-evaluation"
+ | "experiment-compare"
>;
tableName: BatchExportTableName;
actionType: BatchActionType;
diff --git a/web/src/features/table/types.ts b/web/src/features/table/types.ts
index d9e390e707..c3618ea6c7 100644
--- a/web/src/features/table/types.ts
+++ b/web/src/features/table/types.ts
@@ -8,6 +8,8 @@ type BaseTableAction = {
label: string;
description: string;
icon?: ReactElement<any>;
+ disabled?: boolean;
+ disabledReason?: string;
accessCheck: {
scope: ProjectScope;
entitlement?: Entitlement;
diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.ts
index 3571575278..5f12ffc07f 100644
--- a/worker/src/features/batchAction/handleBatchActionJob.ts
+++ b/worker/src/features/batchAction/handleBatchActionJob.ts
@@ -390,7 +390,6 @@ export const handleBatchActionJob = async (
where: {
id: { in: selectedEvaluatorIds },
projectId,
- targetObject: EvalTargetObject.EVENT,
// Preserve the selected evaluators as-is. Executability is checked
// later when each scheduling attempt runs.
},
@@ -426,7 +425,7 @@ export const handleBatchActionJob = async (
log:
error instanceof Error
? error.message
- : "Selected evaluators are missing or not observation-scoped for historical event evaluation.",
+ : "Selected evaluators are missing or invalid for historical evaluation.",
},
});
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
index f9364339a9..9676914e74 100644
--- a/worker/src/features/database-read-stream/event-stream.ts
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -451,6 +451,9 @@ export const getEventsStreamForEval = async (props: {
input: unknown;
output: unknown;
metadata: Record<string, unknown> | null;
+ experiment_id: string | null;
+ experiment_item_root_span_id: string | null;
+ experiment_item_expected_output: string | null;
};
const asyncGenerator = queryClickhouseStream<EvalEventRow>({