🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ui-events-table): add to dataset batch action (#12144)
Hassieb Pakzadcc75fb7a8f0a
diff --git a/packages/shared/src/features/batchAction/applyFieldMapping.ts b/packages/shared/src/features/batchAction/applyFieldMapping.tsindex 947cde59cb..1f9071d11d 100644--- a/packages/shared/src/features/batchAction/applyFieldMapping.ts+++ b/packages/shared/src/features/batchAction/applyFieldMapping.ts@@ -13,6 +13,15 @@ type ObservationData = {metadata: unknown;};+export type MappingError = {+ type: "json_path_miss" | "json_path_error";+ targetField: "input" | "expectedOutput" | "metadata";+ sourceField: SourceField;+ jsonPath: string;+ mappingKey: string | null;+ message: string;+};+/*** Test if a JSON path is valid against the given data*/@@ -37,18 +46,14 @@ export function testJsonPath(props: { jsonPath: string; data: unknown }): {* Evaluate a JSON path against the given data and return the result*/export function evaluateJsonPath(data: unknown, jsonPath: string): unknown {- try {- const parsed = typeof data === "string" ? parseJsonPrioritised(data) : data;- const result = JSONPath({- path: jsonPath,- json: parsed as string | object,- wrap: false,- });-- return result;- } catch {- return undefined;- }+ const parsed = typeof data === "string" ? parseJsonPrioritised(data) : data;+ const result = JSONPath({+ path: jsonPath,+ json: parsed as string | object,+ wrap: false,+ });++ return result;}/**@@ -82,8 +87,13 @@ export function applyFieldMappingConfig(props: {observation: ObservationData;config: FieldMappingConfig;defaultSourceField: SourceField;+ onJsonPathMiss?: (info: {+ sourceField: SourceField;+ jsonPath: string;+ mappingKey: string | null;+ }) => void;}): unknown {- const { observation, config, defaultSourceField } = props;+ const { observation, config, defaultSourceField, onJsonPathMiss } = props;switch (config.mode) {case "full":@@ -107,7 +117,15 @@ export function applyFieldMappingConfig(props: {}const sourceData = observation[rootConfig.sourceField];- return evaluateJsonPath(sourceData, rootConfig.jsonPath);+ const result = evaluateJsonPath(sourceData, rootConfig.jsonPath);+ if (result === undefined && onJsonPathMiss) {+ onJsonPathMiss({+ sourceField: rootConfig.sourceField,+ jsonPath: rootConfig.jsonPath,+ mappingKey: null,+ });+ }+ return result;}if (config.custom.type === "keyValueMap") {@@ -130,6 +148,13 @@ export function applyFieldMappingConfig(props: {// It's a JSON path - evaluate itconst sourceData = observation[entry.sourceField];resolvedValue = evaluateJsonPath(sourceData, entry.value);+ if (resolvedValue === undefined && onJsonPathMiss) {+ onJsonPathMiss({+ sourceField: entry.sourceField,+ jsonPath: entry.value,+ mappingKey: entry.key,+ });+ }} else {// It's a literal string (including empty string)resolvedValue = entry.value;@@ -162,25 +187,83 @@ export function applyFullMapping(props: {input: unknown;expectedOutput: unknown;metadata: unknown;+ errors: MappingError[];} {const { observation, mapping } = props;+ const errors: MappingError[] = [];- return {- input: applyFieldMappingConfig({- observation,+ const fields = [+ {+ key: "input" as const,config: mapping.input,- defaultSourceField: "input",- }),- expectedOutput: applyFieldMappingConfig({- observation,+ defaultSourceField: "input" as const,+ },+ {+ key: "expectedOutput" as const,config: mapping.expectedOutput,- defaultSourceField: "output",- }),- metadata: applyFieldMappingConfig({- observation,+ defaultSourceField: "output" as const,+ },+ {+ key: "metadata" as const,config: mapping.metadata,- defaultSourceField: "metadata",- }),+ defaultSourceField: "metadata" as const,+ },+ ];++ const results: Record<string, unknown> = {};++ for (const field of fields) {+ const onJsonPathMiss = (info: {+ sourceField: SourceField;+ jsonPath: string;+ mappingKey: string | null;+ }) => {+ errors.push({+ type: "json_path_miss",+ targetField: field.key,+ sourceField: info.sourceField,+ jsonPath: info.jsonPath,+ mappingKey: info.mappingKey,+ message: `JSON path "${info.jsonPath}" did not match any data in "${info.sourceField}"${info.mappingKey ? ` (key: "${info.mappingKey}")` : ""}`,+ });+ };++ try {+ results[field.key] = applyFieldMappingConfig({+ observation,+ config: field.config,+ defaultSourceField: field.defaultSourceField,+ onJsonPathMiss,+ });+ } catch (error) {+ // Capture rare JSONPath evaluation errors (e.g. malformed filter expressions)+ const sourceField =+ field.config.mode === "custom" && field.config.custom?.type === "root"+ ? (field.config.custom.rootConfig?.sourceField ??+ field.defaultSourceField)+ : field.defaultSourceField;+ const jsonPath =+ field.config.mode === "custom" && field.config.custom?.type === "root"+ ? (field.config.custom.rootConfig?.jsonPath ?? "")+ : "";++ errors.push({+ type: "json_path_error",+ targetField: field.key,+ sourceField,+ jsonPath,+ mappingKey: null,+ message: `JSON path evaluation error for "${field.key}": ${error instanceof Error ? error.message : "Unknown error"}`,+ });+ results[field.key] = undefined;+ }+ }++ return {+ input: results.input,+ expectedOutput: results.expectedOutput,+ metadata: results.metadata,+ errors,};}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsxindex e2565c3017..29864e6129 100644--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx@@ -1,9 +1,11 @@import { useMemo } from "react";import { Button } from "@/src/components/ui/button";-import { Pencil } from "lucide-react";+import { AlertTriangle, Pencil } from "lucide-react";import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import { cn } from "@/src/utils/tailwind";import type { FinalPreviewStepProps, DialogStep } from "./types";import { applyFullMapping } from "@langfuse/shared";+import type { MappingError } from "@langfuse/shared";export function FinalPreviewStep({dataset,@@ -26,6 +28,27 @@ export function FinalPreviewStep({});}, [observationData, mapping]);+ // Group errors by target field+ const errorsByField = useMemo(() => {+ const errors = previewResult?.errors ?? [];+ const grouped: Record<string, MappingError[]> = {};+ for (const err of errors) {+ if (!grouped[err.targetField]) {+ grouped[err.targetField] = [];+ }+ grouped[err.targetField].push(err);+ }+ return grouped;+ }, [previewResult?.errors]);++ const hasWarnings = (previewResult?.errors?.length ?? 0) > 0;++ const stepForField: Record<string, DialogStep> = {+ input: "input-mapping" as DialogStep,+ expectedOutput: "output-mapping" as DialogStep,+ metadata: "metadata-mapping" as DialogStep,+ };+return (<div className="h-[62vh] space-y-6 p-6"><div>@@ -37,6 +60,42 @@ export function FinalPreviewStep({</p></div>+ {/* Overall warning banner */}+ {hasWarnings && (+ <div className="rounded-md border border-amber-500/50 bg-amber-50 p-3 dark:bg-amber-950/30">+ <div className="flex items-start gap-2">+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />+ <div className="space-y-1">+ <p className="text-sm font-medium text-amber-600 dark:text-amber-500">+ Some JSON paths did not match the preview observation+ </p>+ <p className="text-xs text-amber-600/80 dark:text-amber-500/80">+ Observations with failed mappings will be skipped during+ processing.+ </p>+ <div className="flex flex-wrap gap-2 pt-1">+ {Object.entries(errorsByField).map(([field]) => (+ <Button+ key={field}+ variant="link"+ size="sm"+ className="h-auto p-0 text-xs text-amber-600 underline dark:text-amber-500"+ onClick={() => {+ const step = stepForField[field];+ if (step) onEditStep(step);+ }}+ >+ Edit{" "}+ {field === "expectedOutput" ? "expected output" : field}{" "}+ mapping+ </Button>+ ))}+ </div>+ </div>+ </div>+ </div>+ )}+<div className="text-sm text-muted-foreground">Sample dataset item preview (from first selected observation):</div>@@ -54,6 +113,7 @@ export function FinalPreviewStep({label="Input"data={previewResult?.input}onEdit={() => onEditStep("input-mapping" as DialogStep)}+ errors={errorsByField["input"]}/>{/* Expected Output Preview */}@@ -61,6 +121,7 @@ export function FinalPreviewStep({label="Expected Output"data={previewResult?.expectedOutput}onEdit={() => onEditStep("output-mapping" as DialogStep)}+ errors={errorsByField["expectedOutput"]}/>{/* Metadata Preview */}@@ -68,6 +129,7 @@ export function FinalPreviewStep({label="Metadata"data={previewResult?.metadata}onEdit={() => onEditStep("metadata-mapping" as DialogStep)}+ errors={errorsByField["metadata"]}/></div>)}@@ -79,13 +141,23 @@ type PreviewCardProps = {label: string;data: unknown;onEdit: () => void;+ errors?: MappingError[];};-function PreviewCard({ label, data, onEdit }: PreviewCardProps) {+function PreviewCard({ label, data, onEdit, errors }: PreviewCardProps) {+ const hasErrors = errors && errors.length > 0;+return (- <div className="rounded-lg border">+ <div+ className={cn("rounded-lg border", hasErrors && "border-amber-500/50")}+ ><div className="flex items-center justify-between border-b bg-muted/30 px-4 py-2">- <span className="text-sm font-medium">{label}</span>+ <span className="flex items-center gap-1.5 text-sm font-medium">+ {hasErrors && (+ <AlertTriangle className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500" />+ )}+ {label}+ </span><Buttonvariant="ghost"size="sm"@@ -103,6 +175,15 @@ function PreviewCard({ label, data, onEdit }: PreviewCardProps) {<JSONView json={data} className="text-xs" />)}</div>+ {hasErrors && (+ <div className="border-t border-amber-500/50 bg-amber-50 px-4 py-2 dark:bg-amber-950/30">+ <p className="text-xs text-amber-600 dark:text-amber-500">+ {errors.length} path{errors.length !== 1 ? "s" : ""} did not match+ in preview observation. These items will be skipped during+ processing.+ </p>+ </div>+ )}</div>);}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsxindex 49f5666029..7aea3cb9a1 100644--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx@@ -79,6 +79,7 @@ export function JsonPathInput({const codeMirrorTheme = resolvedTheme === "dark" ? darkTheme : lightTheme;const [resolveError, setResolveError] = useState<string | null>(null);+ const [noMatchWarning, setNoMatchWarning] = useState(false);// Parse source data onceconst parsedSourceData = useMemo(() => {@@ -103,18 +104,23 @@ export function JsonPathInput({// Try to resolve the JSON pathif (newValue && newValue.startsWith("$") && parsedSourceData) {try {- evaluateJsonPath(parsedSourceData, newValue);+ const result = evaluateJsonPath(parsedSourceData, newValue);+ setResolveError(null);+ setNoMatchWarning(result === undefined);} catch (e) {setResolveError(e instanceof Error ? e.message : "Invalid JSON path");+ setNoMatchWarning(false);}} else {setResolveError(null);+ setNoMatchWarning(false);}},[onChange, parsedSourceData],);const displayError = error || resolveError;+ const showWarning = !displayError && noMatchWarning;return (<div className="space-y-1">@@ -151,12 +157,18 @@ export function JsonPathInput({className={cn("overflow-hidden rounded-md border text-sm",displayError && "border-destructive",+ showWarning && "border-amber-500/50",className,)}/>{displayError && (<p className="text-xs text-destructive">{displayError}</p>)}+ {showWarning && (+ <p className="text-xs text-amber-600 dark:text-amber-500">+ No match found in source data+ </p>+ )}</div>);}diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsxindex 7da3420d06..1661cd1f56 100644--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx@@ -1,5 +1,10 @@import { useMemo, useEffect, useRef } from "react";-import { ArrowDown, AlertCircle, CheckCircle2 } from "lucide-react";+import {+ ArrowDown,+ AlertCircle,+ AlertTriangle,+ CheckCircle2,+} from "lucide-react";import { JSONView } from "@/src/components/ui/CodeJsonViewer";import { Skeleton } from "@/src/components/ui/skeleton";import type {@@ -55,11 +60,25 @@ export function MappingPreviewPanel({return observationData[defaultSourceField];}, [observationData, config, defaultSourceField]);- // Compute result data- const resultData = useMemo(() => {- if (!observationData) return null;+ // Compute result data and collect JSON path misses+ const { resultData, jsonPathMisses } = useMemo(() => {+ if (!observationData)+ return {+ resultData: null,+ jsonPathMisses: [] as {+ sourceField: string;+ jsonPath: string;+ mappingKey: string | null;+ }[],+ };++ const misses: {+ sourceField: string;+ jsonPath: string;+ mappingKey: string | null;+ }[] = [];- return applyFieldMappingConfig({+ const data = applyFieldMappingConfig({observation: {input: observationData.input,output: observationData.output,@@ -67,7 +86,12 @@ export function MappingPreviewPanel({},config,defaultSourceField,+ onJsonPathMiss: (info) => {+ misses.push(info);+ },});++ return { resultData: data, jsonPathMisses: misses };}, [observationData, config, defaultSourceField]);// Validate result against schema@@ -215,13 +239,15 @@ export function MappingPreviewPanel({Result: Dataset Item {fieldLabel}</p>{/* Validation status indicator */}- {hasSchema && config.mode !== "none" && (+ {config.mode !== "none" && (<div className="flex items-center gap-1">- {validationResult.isValid ? (- <CheckCircle2 className="h-3.5 w-3.5 text-green-600" />- ) : (+ {hasSchema && !validationResult.isValid ? (<AlertCircle className="h-3.5 w-3.5 text-destructive" />- )}+ ) : jsonPathMisses.length > 0 ? (+ <AlertTriangle className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500" />+ ) : hasSchema ? (+ <CheckCircle2 className="h-3.5 w-3.5 text-green-600" />+ ) : null}</div>)}</div>@@ -229,7 +255,9 @@ export function MappingPreviewPanel({className={`max-h-[21vh] overflow-auto rounded-md border bg-background ${hasSchema && !validationResult.isValid && config.mode !== "none"? "border-destructive"- : ""+ : jsonPathMisses.length > 0 && config.mode !== "none"+ ? "border-amber-500/50"+ : ""}`}>{config.mode === "none" ? (@@ -257,6 +285,27 @@ export function MappingPreviewPanel({</ul></div>)}++ {/* JSON path warnings */}+ {jsonPathMisses.length > 0 && config.mode !== "none" && (+ <div className="max-h-[5vh] overflow-y-auto rounded-md border border-amber-500/50 bg-amber-50 p-2 dark:bg-amber-950/30">+ <p className="mb-1 text-xs font-medium text-amber-600 dark:text-amber-500">+ JSON path warnings (preview observation):+ </p>+ <ul className="space-y-0.5">+ {jsonPathMisses.map((miss, idx) => (+ <li+ key={idx}+ className="text-xs text-amber-600 dark:text-amber-500"+ >+ <span className="font-mono">{miss.jsonPath}</span> did not+ match any data in {miss.sourceField}+ {miss.mappingKey ? ` (key: "${miss.mappingKey}")` : ""}+ </li>+ ))}+ </ul>+ </div>+ )}</div></div>);diff --git a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsxindex 3ac9dfb40f..1a5b5fda4c 100644--- a/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx+++ b/web/src/features/batch-actions/components/RunEvaluationDialog/index.tsx@@ -26,6 +26,11 @@ type RunEvaluationDialogProps = {selectAll: boolean;totalCount: number;onClose: () => void;+ exampleObservation: {+ id: string;+ traceId: string;+ startTime?: Date;+ };};type DialogStep = "select-evaluator" | "confirm";@@ -55,41 +60,16 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {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,+ observationId: props.exampleObservation.id,+ traceId: props.exampleObservation.traceId,+ startTime: props.exampleObservation.startTime ?? null,},{enabled: Boolean(- previewObservationSeed?.id && previewObservationSeed?.traceId,+ props.exampleObservation.id && props.exampleObservation.traceId,),},);@@ -174,10 +154,7 @@ export function RunEvaluationDialog(props: RunEvaluationDialogProps) {isQueryError={evaluatorsQuery.isError}queryErrorMessage={evaluatorsQuery.error?.message}previewObservation={previewObservationQuery.data}- isPreviewLoading={- previewObservationSeedQuery.isLoading ||- previewObservationQuery.isLoading- }+ isPreviewLoading={previewObservationQuery.isLoading}selectedEvaluatorIds={selectedEvaluatorIds}evaluatorSearchQuery={evaluatorSearchQuery}onSearchQueryChange={setEvaluatorSearchQuery}diff --git a/web/src/features/batch-actions/server/addToDatasetRouter.ts b/web/src/features/batch-actions/server/addToDatasetRouter.tsindex 9ca7801eb7..fd48c853b9 100644--- a/web/src/features/batch-actions/server/addToDatasetRouter.ts+++ b/web/src/features/batch-actions/server/addToDatasetRouter.ts@@ -37,6 +37,12 @@ export const addToDatasetRouter = createTRPCRouter({const { projectId, query, config } = input;+ const useEventsTable =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true";+ const tableName = useEventsTable+ ? BatchTableNames.Events+ : BatchTableNames.Observations;+// Check observation count doesn't exceed maximumconst queryOpts = {projectId,@@ -44,10 +50,9 @@ export const addToDatasetRouter = createTRPCRouter({limit: 1,offset: 0,};- const observationCount =- env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true"- ? await getObservationsCountFromEventsTable(queryOpts)- : await getObservationsTableCount(queryOpts);+ const observationCount = useEventsTable+ ? await getObservationsCountFromEventsTable(queryOpts)+ : await getObservationsTableCount(queryOpts);if (observationCount > MAX_BATCH_ADD_TO_DATASET_ITEMS) {throw new TRPCError({@@ -67,7 +72,7 @@ export const addToDatasetRouter = createTRPCRouter({projectId,userId,actionType: ActionId.ObservationAddToDataset,- tableName: BatchTableNames.Observations,+ tableName,status: BatchActionStatus.Queued,query,config,@@ -95,7 +100,7 @@ export const addToDatasetRouter = createTRPCRouter({batchActionId: batchAction.id,projectId,actionId: ActionId.ObservationAddToDataset,- tableName: BatchTableNames.Observations,+ tableName,cutoffCreatedAt: new Date(),query,config,diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 3f7a5e1aee..4112a84623 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -83,6 +83,7 @@ import {import useSessionStorage from "@/src/components/useSessionStorage";import { api } from "@/src/utils/api";import { RunEvaluationDialog } from "@/src/features/batch-actions/components/RunEvaluationDialog/index";+import { AddObservationsToDatasetDialog } from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/index";export type EventsTableRow = {// Identity fields@@ -184,6 +185,7 @@ export default function ObservationsEventsTable({const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");const [showRunEvaluationDialog, setShowRunEvaluationDialog] = useState(false);+ const [showAddToDatasetDialog, setShowAddToDatasetDialog] = useState(false);const [paginationState, setPaginationState] = usePaginationState(1, 50);@@ -473,6 +475,16 @@ export default function ObservationsEventsTable({scope: "annotationQueues:CUD",},},+ {+ id: ActionId.ObservationAddToDataset,+ type: BatchActionType.Create,+ label: "Add to Dataset",+ description: "Add selected observations to a dataset",+ customDialog: true,+ accessCheck: {+ scope: "datasets:CUD",+ },+ },{id: ActionId.ObservationBatchEvaluation,type: BatchActionType.Create,@@ -1199,6 +1211,21 @@ export default function ObservationsEventsTable({return result;}, [observations]);+ const selectedObservationIds = useMemo(() => {+ const rowIds = new Set(observations.rows?.map((o) => o.id));+ return Object.keys(selectedRows).filter((id) => rowIds.has(id));+ }, [observations.rows, selectedRows]);++ const exampleObservation = useMemo(() => {+ const firstId = selectedObservationIds[0];+ const firstObs = observations.rows?.find((o) => o.id === firstId);+ return {+ id: firstObs?.id ?? "",+ traceId: firstObs?.traceId ?? "",+ startTime: firstObs?.startTime ?? undefined,+ };+ }, [selectedObservationIds, observations.rows]);+return (<DataTableControlsProvider><div className="flex h-full w-full flex-col">@@ -1260,9 +1287,7 @@ export default function ObservationsEventsTable({tableName={BatchExportTableName.Events}key="batchExport"/>,- Object.keys(selectedRows).filter((observationId) =>- observations.rows?.map((o) => o.id).includes(observationId),- ).length > 0 ? (+ selectedObservationIds.length > 0 ? (<TableActionMenukey="observations-multi-select-actions"projectId={projectId}@@ -1272,6 +1297,9 @@ export default function ObservationsEventsTable({if (actionType === ActionId.ObservationBatchEvaluation) {setShowRunEvaluationDialog(true);}+ if (actionType === ActionId.ObservationAddToDataset) {+ setShowAddToDatasetDialog(true);+ }}}/>) : null,@@ -1279,10 +1307,7 @@ export default function ObservationsEventsTable({multiSelect={{selectAll,setSelectAll,- selectedRowIds:- Object.keys(selectedRows).filter((observationId) =>- observations.rows?.map((o) => o.id).includes(observationId),- ) ?? [],+ selectedRowIds: selectedObservationIds,setRowSelection: setSelectedRows,totalCount,pageSize: paginationState.limit,@@ -1402,10 +1427,7 @@ export default function ObservationsEventsTable({{showRunEvaluationDialog && (<RunEvaluationDialogprojectId={projectId}- selectedObservationIds={(() => {- const rowIds = new Set(observations.rows?.map((o) => o.id));- return Object.keys(selectedRows).filter((id) => rowIds.has(id));- })()}+ selectedObservationIds={selectedObservationIds}query={{filter: filterState,orderBy: orderByState,@@ -1419,6 +1441,28 @@ export default function ObservationsEventsTable({setSelectedRows({});setSelectAll(false);}}+ exampleObservation={exampleObservation}+ />+ )}++ {showAddToDatasetDialog && (+ <AddObservationsToDatasetDialog+ projectId={projectId}+ selectedObservationIds={selectedObservationIds}+ query={{+ filter: filterState,+ orderBy: orderByState,+ searchQuery: searchQuery ?? undefined,+ searchType,+ }}+ selectAll={selectAll}+ totalCount={totalCount ?? 0}+ onClose={() => {+ setShowAddToDatasetDialog(false);+ setSelectedRows({});+ setSelectAll(false);+ }}+ exampleObservation={exampleObservation}/>)}</DataTableControlsProvider>diff --git a/worker/src/__tests__/applyFieldMapping.test.ts b/worker/src/__tests__/applyFieldMapping.test.tsindex 650fa645b8..5f4818b9cd 100644--- a/worker/src/__tests__/applyFieldMapping.test.ts+++ b/worker/src/__tests__/applyFieldMapping.test.ts@@ -684,6 +684,7 @@ describe("applyFieldMapping", () => {input: { prompt: "What is 2+2?" },expectedOutput: "4",metadata: null,+ errors: [],});});@@ -701,6 +702,7 @@ describe("applyFieldMapping", () => {input: sampleObservation.input,expectedOutput: sampleObservation.output,metadata: sampleObservation.metadata,+ errors: [],});});@@ -762,8 +764,147 @@ describe("applyFieldMapping", () => {},expectedOutput: "4",metadata: null,+ errors: [],});});++ it("should collect json_path_miss errors for non-matching root paths", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "input",+ jsonPath: "$.nonExistent.deeply.nested",+ },+ },+ },+ expectedOutput: { mode: "full" },+ metadata: { mode: "none" },+ },+ });++ expect(result.input).toBeUndefined();+ expect(result.errors).toHaveLength(1);+ expect(result.errors[0]).toMatchObject({+ type: "json_path_miss",+ targetField: "input",+ sourceField: "input",+ jsonPath: "$.nonExistent.deeply.nested",+ mappingKey: null,+ });+ expect(result.errors[0].message).toContain("did not match");+ });++ it("should collect json_path_miss errors for non-matching keyValueMap paths", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input",+ value: "$.messages[1].content", // matches+ },+ {+ id: "2",+ key: "missing",+ sourceField: "output",+ value: "$.nonExistent", // does not match+ },+ ],+ },+ },+ },+ expectedOutput: { mode: "full" },+ metadata: { mode: "none" },+ },+ });++ expect(result.input).toEqual({+ prompt: "What is 2+2?",+ missing: undefined,+ });+ expect(result.errors).toHaveLength(1);+ expect(result.errors[0]).toMatchObject({+ type: "json_path_miss",+ targetField: "input",+ sourceField: "output",+ jsonPath: "$.nonExistent",+ mappingKey: "missing",+ });+ });++ it("should collect errors across multiple fields", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "input",+ jsonPath: "$.nope",+ },+ },+ },+ expectedOutput: {+ mode: "custom",+ custom: {+ type: "root",+ rootConfig: {+ sourceField: "output",+ jsonPath: "$.alsoNope",+ },+ },+ },+ metadata: { mode: "none" },+ },+ });++ expect(result.errors).toHaveLength(2);+ expect(result.errors[0].targetField).toBe("input");+ expect(result.errors[1].targetField).toBe("expectedOutput");+ });++ it("should not collect errors for literal string values in keyValueMap", () => {+ const result = applyFullMapping({+ observation: sampleObservation,+ mapping: {+ input: {+ mode: "custom",+ custom: {+ type: "keyValueMap",+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "type",+ sourceField: "input",+ value: "conversation", // literal, not JSON path+ },+ ],+ },+ },+ },+ expectedOutput: { mode: "full" },+ metadata: { mode: "none" },+ },+ });++ expect(result.errors).toHaveLength(0);+ expect(result.input).toEqual({ type: "conversation" });+ });});describe("generateJsonPathSuggestions", () => {diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex 58c111d3c6..5db3e6b7ee 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -1,6 +1,8 @@import {BatchExportTableName,BatchActionType,+ BatchTableNames,+ BatchActionStatus,EvalTargetObject,} from "@langfuse/shared";import { expect, describe, it, vi } from "vitest";@@ -13,6 +15,8 @@ import {createScoresCh,createTrace,createTracesCh,+ createEvent,+ createEventsCh,getQueue,getScoresByIds,QueueJobs,@@ -26,6 +30,11 @@ import { prisma } from "@langfuse/shared/src/db";import { Decimal } from "decimal.js";import waitForExpect from "wait-for-expect";+const maybeDescribe =+ process.env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ ? describe+ : describe.skip;+describe("select all test suite", () => {it("should schedule trace deletions via pending_deletions table", async () => {const { projectId } = await createOrgProjectAndApiKey();@@ -579,3 +588,263 @@ describe("select all test suite", () => {});});});++maybeDescribe("events table batch actions", () => {+ it("should add observations to dataset from events table with full mapping", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = uuidv4();+ const trace = createTrace({+ project_id: projectId,+ id: traceId,+ timestamp: new Date().getTime(),+ });+ await createTracesCh([trace]);++ const eventInput1 = { prompt: "Hello, how are you?" };+ const eventOutput1 = { response: "I'm fine, thank you!" };+ const eventInput2 = { prompt: "What is 2+2?" };+ const eventOutput2 = { response: "4" };++ const event1 = createEvent({+ project_id: projectId,+ trace_id: traceId,+ input: eventInput1,+ output: eventOutput1,+ metadata: { source: "test" },+ });+ const event2 = createEvent({+ project_id: projectId,+ trace_id: traceId,+ input: eventInput2,+ output: eventOutput2,+ metadata: { source: "test" },+ });++ await createEventsCh([event1, event2]);++ const datasetName = uuidv4();+ const dataset = await prisma.dataset.create({+ data: {+ id: uuidv4(),+ projectId,+ name: datasetName,+ },+ });++ const batchAction = await prisma.batchAction.create({+ data: {+ projectId,+ userId: "test-user",+ actionType: "observation-add-to-dataset",+ tableName: BatchTableNames.Events,+ status: BatchActionStatus.Queued,+ query: { filter: [], orderBy: null },+ },+ });++ await handleBatchActionJob({+ id: uuidv4(),+ timestamp: new Date(),+ name: QueueJobs.BatchActionProcessingJob as const,+ payload: {+ batchActionId: batchAction.id,+ projectId,+ actionId: "observation-add-to-dataset" as const,+ tableName: BatchTableNames.Events,+ cutoffCreatedAt: new Date(),+ query: { filter: [], orderBy: null },+ config: {+ datasetId: dataset.id,+ datasetName: dataset.name,+ mapping: {+ input: { mode: "full" as const },+ expectedOutput: { mode: "full" as const },+ metadata: { mode: "none" as const },+ },+ },+ type: BatchActionType.Create,+ },+ });++ const datasetItems = await prisma.datasetItem.findMany({+ where: { datasetId: dataset.id },+ });++ expect(datasetItems).toHaveLength(2);++ const eventSpanIds = [event1.span_id, event2.span_id];+ for (const item of datasetItems) {+ expect(eventSpanIds).toContain(item.sourceObservationId);+ expect(item.sourceTraceId).toBe(traceId);+ expect(item.metadata).toBeNull();+ }++ // Verify each item's input/output matches the corresponding event+ const item1 = datasetItems.find(+ (i) => i.sourceObservationId === event1.span_id,+ );+ const item2 = datasetItems.find(+ (i) => i.sourceObservationId === event2.span_id,+ );++ expect(item1?.input).toEqual(eventInput1);+ expect(item1?.expectedOutput).toEqual(eventOutput1);+ expect(item2?.input).toEqual(eventInput2);+ expect(item2?.expectedOutput).toEqual(eventOutput2);++ // Verify batch action status+ const updatedBatchAction = await prisma.batchAction.findUnique({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction?.status).toBe(BatchActionStatus.Completed);+ expect(updatedBatchAction?.processedCount).toBe(2);+ });++ it("should apply jsonSelector mapping when adding events to dataset", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const traceId = uuidv4();+ const trace = createTrace({+ project_id: projectId,+ id: traceId,+ timestamp: new Date().getTime(),+ });+ await createTracesCh([trace]);++ const eventInput = {+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: "What is 2+2?" },+ ],+ };+ const eventOutput = {+ choices: [{ message: { content: "4", role: "assistant" } }],+ };+ const eventMetadata = { user_id: "user-123", session_id: "session-456" };++ const event = createEvent({+ project_id: projectId,+ trace_id: traceId,+ input: eventInput,+ output: eventOutput,+ metadata: eventMetadata,+ });++ await createEventsCh([event]);++ const datasetName = uuidv4();+ const dataset = await prisma.dataset.create({+ data: {+ id: uuidv4(),+ projectId,+ name: datasetName,+ },+ });++ const batchAction = await prisma.batchAction.create({+ data: {+ projectId,+ userId: "test-user",+ actionType: "observation-add-to-dataset",+ tableName: BatchTableNames.Events,+ status: BatchActionStatus.Queued,+ query: { filter: [], orderBy: null },+ },+ });++ await handleBatchActionJob({+ id: uuidv4(),+ timestamp: new Date(),+ name: QueueJobs.BatchActionProcessingJob as const,+ payload: {+ batchActionId: batchAction.id,+ projectId,+ actionId: "observation-add-to-dataset" as const,+ tableName: BatchTableNames.Events,+ cutoffCreatedAt: new Date(),+ query: { filter: [], orderBy: null },+ config: {+ datasetId: dataset.id,+ datasetName: dataset.name,+ mapping: {+ input: {+ mode: "custom" as const,+ custom: {+ type: "keyValueMap" as const,+ keyValueMapConfig: {+ entries: [+ {+ id: "1",+ key: "prompt",+ sourceField: "input" as const,+ value: "$.messages[1].content",+ },+ {+ id: "2",+ key: "system",+ sourceField: "input" as const,+ value: "$.messages[0].content",+ },+ ],+ },+ },+ },+ expectedOutput: {+ mode: "custom" as const,+ custom: {+ type: "root" as const,+ rootConfig: {+ sourceField: "output" as const,+ jsonPath: "$.choices[0].message.content",+ },+ },+ },+ metadata: {+ mode: "custom" as const,+ custom: {+ type: "keyValueMap" as const,+ keyValueMapConfig: {+ entries: [+ {+ id: "3",+ key: "user",+ sourceField: "metadata" as const,+ value: "$.user_id",+ },+ ],+ },+ },+ },+ },+ },+ type: BatchActionType.Create,+ },+ });++ const datasetItems = await prisma.datasetItem.findMany({+ where: { datasetId: dataset.id },+ });++ expect(datasetItems).toHaveLength(1);++ const item = datasetItems[0];+ expect(item.sourceObservationId).toBe(event.span_id);+ expect(item.sourceTraceId).toBe(traceId);+ expect(item.input).toEqual({+ prompt: "What is 2+2?",+ system: "You are helpful.",+ });+ // The jsonPath extracts the string "4" from output, but it's stored as a+ // JSON scalar in Postgres. Prisma deserializes the JSON column as a number.+ expect(item.expectedOutput).toBe(4);+ expect(item.metadata).toEqual({ user: "user-123" });++ // Verify batch action status+ const updatedBatchAction = await prisma.batchAction.findUnique({+ where: { id: batchAction.id },+ });+ expect(updatedBatchAction?.status).toBe(BatchActionStatus.Completed);+ expect(updatedBatchAction?.processedCount).toBe(1);+ });+});diff --git a/worker/src/features/batchAction/handleBatchActionJob.ts b/worker/src/features/batchAction/handleBatchActionJob.tsindex 4de7db54e0..657b1b4d52 100644--- a/worker/src/features/batchAction/handleBatchActionJob.ts+++ b/worker/src/features/batchAction/handleBatchActionJob.ts@@ -31,7 +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 {+ getEventsStreamForEval,+ getEventsStreamForDataset,+} from "../database-read-stream/event-stream";import { processAddObservationsToDataset } from "./processAddObservationsToDataset";import { ObservationAddToDatasetConfigSchema } from "@langfuse/shared";import { processBatchedObservationEval } from "./processBatchedObservationEval";@@ -316,20 +319,30 @@ export const handleBatchActionJob = async (`Batch action job completed, projectId: ${batchActionJob.payload.projectId}, ${count} elements`,);} else if (actionId === "observation-add-to-dataset") {- const { projectId, query, cutoffCreatedAt, config, batchActionId } =- batchActionEvent;+ const {+ projectId,+ query,+ cutoffCreatedAt,+ config,+ batchActionId,+ tableName,+ } = batchActionEvent;// Parse and validate configconst parsedConfig = ObservationAddToDatasetConfigSchema.parse(config);- // Get observation stream- const dbReadStream = await getObservationStream({+ // Get observation stream — use events table when tableName indicates it+ const streamParams = {projectId,cutoffCreatedAt: new Date(cutoffCreatedAt),filter: convertDatesInFiltersFromStrings(query.filter ?? []),searchQuery: query.searchQuery ?? undefined,searchType: query.searchType ?? ["id" as const],- });+ };+ const dbReadStream =+ tableName === BatchTableNames.Events+ ? await getEventsStreamForDataset(streamParams)+ : await getObservationStream(streamParams);// Collect all observationsconst observations: Array<{diff --git a/worker/src/features/batchAction/processAddObservationsToDataset.ts b/worker/src/features/batchAction/processAddObservationsToDataset.tsindex ffab8c4de4..ac3d40d3c6 100644--- a/worker/src/features/batchAction/processAddObservationsToDataset.ts+++ b/worker/src/features/batchAction/processAddObservationsToDataset.ts@@ -5,6 +5,7 @@ import {applyFullMapping,BatchActionStatus,type ObservationAddToDatasetConfig,+ type MappingError,} from "@langfuse/shared";// Chunk size for batch processing. Smaller than the default 1000 because:@@ -21,6 +22,14 @@ type ObservationForMapping = {metadata: unknown;};+function formatMappingErrors(+ observationId: string,+ errors: MappingError[],+): string {+ const details = errors.map((e) => e.message).join("; ");+ return `Observation ${observationId}: Mapping failed - ${details}`;+}+async function processChunk(params: {projectId: string;datasetId: string;@@ -29,7 +38,18 @@ async function processChunk(params: {}): Promise<{ processed: number; failed: number; errors: string[] }> {const { projectId, datasetId, mapping, observations } = params;- const items = observations.map((obs) => {+ const items: Array<{+ datasetId: string;+ input: unknown;+ expectedOutput: unknown;+ metadata: unknown;+ sourceTraceId: string;+ sourceObservationId: string;+ }> = [];+ let mappingFailedCount = 0;+ const mappingErrors: string[] = [];++ for (const obs of observations) {const mapped = applyFullMapping({observation: {input: obs.input,@@ -39,15 +59,30 @@ async function processChunk(params: {mapping,});- return {+ if (mapped.errors.length > 0) {+ mappingFailedCount++;+ mappingErrors.push(formatMappingErrors(obs.id, mapped.errors));+ continue;+ }++ items.push({datasetId,input: mapped.input,expectedOutput: mapped.expectedOutput ?? undefined,metadata: mapped.metadata ?? undefined,sourceTraceId: obs.traceId,sourceObservationId: obs.id,+ });+ }++ // If all observations failed mapping, return early+ if (items.length === 0) {+ return {+ processed: 0,+ failed: mappingFailedCount,+ errors: mappingErrors,};- });+ }try {const result = await createManyDatasetItems({@@ -62,16 +97,19 @@ async function processChunk(params: {// All items failedreturn {processed: 0,- failed: items.length,- errors: result.validationErrors.map(- (e) =>- `Item ${e.itemIndex}: ${e.field} - ${e.errors.map((err) => err.message).join(", ")}`,- ),+ failed: items.length + mappingFailedCount,+ errors: [+ ...mappingErrors,+ ...result.validationErrors.map(+ (e) =>+ `Item ${e.itemIndex}: ${e.field} - ${e.errors.map((err) => err.message).join(", ")}`,+ ),+ ],};}// Success (possibly partial)- const errors = result.validationErrors+ const validationErrors = result.validationErrors? result.validationErrors.map((e) =>`Item ${e.itemIndex}: ${e.field} - ${e.errors.map((err) => err.message).join(", ")}`,@@ -80,16 +118,17 @@ async function processChunk(params: {return {processed: result.successCount,- failed: result.failedCount,- errors,+ failed: result.failedCount + mappingFailedCount,+ errors: [...mappingErrors, ...validationErrors],};} catch (error) {logger.error("Failed to create dataset items in chunk", error);traceException(error);return {processed: 0,- failed: items.length,+ failed: items.length + mappingFailedCount,errors: [+ ...mappingErrors,`Failed to create chunk: ${error instanceof Error ? error.message : "Unknown error"}`,],};diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex 41f2bf1667..062e43ebef 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -479,3 +479,115 @@ export const getEventsStreamForEval = async (props: {})(),);};++/**+ * Lightweight event stream for batch add-to-dataset.+ * Only fetches the fields needed for dataset item creation:+ * id, traceId, input, output, metadata.+ */+export const getEventsStreamForDataset = 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.BATCH_EXPORT_ROW_LIMIT,+ } = props;++ 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("core")+ .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();++ type DatasetEventRow = {+ id: string;+ trace_id: string;+ input: unknown;+ output: unknown;+ metadata: Record<string, unknown> | null;+ };++ const asyncGenerator = queryClickhouseStream<DatasetEventRow>({+ query,+ params: queryParams,+ clickhouseConfigs: {+ request_timeout: 180_000,+ clickhouse_settings: {+ http_send_timeout: 300,+ http_receive_timeout: 300,+ },+ },+ tags: {+ feature: "batch-add-to-dataset",+ type: "event",+ kind: "dataset",+ projectId,+ },+ });++ return Readable.from(+ (async function* () {+ for await (const row of asyncGenerator) {+ yield {+ id: row.id,+ traceId: row.trace_id,+ input: row.input,+ output: row.output,+ metadata: row.metadata,+ };+ }+ })(),+ );+};