Skip to content

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

feat(evals): add support for running llm-as-a-judge on observations (#11861)

marliessophieff4b03c0b70d
diff --git a/packages/shared/src/features/evals/observationForEval.ts b/packages/shared/src/features/evals/observationForEval.ts
index 69ba07e2ef..399c50095c 100644
--- a/packages/shared/src/features/evals/observationForEval.ts
+++ b/packages/shared/src/features/evals/observationForEval.ts
@@ -1,7 +1,10 @@
import { z } from "zod/v4";
import { DEFAULT_TRACE_ENVIRONMENT } from "../../server/ingestion/types";
import { type EventRecordBaseType } from "../../server/repositories/definitions";
-import { ObservationLevel } from "../../domain";
+import { ObservationLevel, ObservationType } from "../../domain";
+import { SingleValueOption } from "../../tableDefinitions";
+import { ColumnDefinition } from "../../tableDefinitions";
+import { formatColumnOptions } from "../../tableDefinitions/typeHelpers";
const flexibleUsageCostSchema = z.record(z.string(), z.number().nullable());
@@ -71,16 +74,15 @@ export function convertEventRecordToObservationForEval(
return observationForEvalSchema.parse(record);
}
-export interface ObservationEvalFilterColumn {
+export type ObservationEvalFilterColumnInternal =
/** Column identifier (must match an ObservationForEval field name) */
- id: keyof Pick<
+ keyof Pick<
ObservationForEval,
| "type"
| "name"
| "environment"
| "level"
| "version"
- | "release"
| "trace_name"
| "user_id"
| "session_id"
@@ -88,47 +90,22 @@ export interface ObservationEvalFilterColumn {
| "experiment_dataset_id"
| "metadata"
>;
- /** Display name for UI */
- name: string;
- /** Filter type for UI rendering */
- type: "string" | "stringOptions" | "stringObject" | "arrayOptions" | "number";
-}
-/**
- * Columns available for filtering in observation-based evals.
- * Maps to InMemoryFilterService column mapper.
- *
- * These columns can be used in filter conditions to determine
- * which observations should be evaluated.
- */
-export const observationEvalFilterColumns: ObservationEvalFilterColumn[] = [
- // Observation properties
- { id: "type", name: "Type", type: "stringOptions" },
- { id: "name", name: "Name", type: "string" },
- { id: "environment", name: "Environment", type: "stringOptions" },
- { id: "level", name: "Level", type: "stringOptions" },
- { id: "version", name: "Version", type: "string" },
- { id: "release", name: "Release", type: "string" },
- { id: "trace_name", name: "Trace Name", type: "string" },
- { id: "user_id", name: "User ID", type: "string" },
- { id: "session_id", name: "Session ID", type: "string" },
- { id: "tags", name: "Tags", type: "arrayOptions" },
- { id: "experiment_dataset_id", name: "Dataset", type: "stringOptions" },
- { id: "metadata", name: "Metadata", type: "stringObject" },
-];
+export type ObservationEvalMappingColumnInternal = keyof Pick<
+ ObservationForEval,
+ "input" | "output" | "metadata" | "experiment_item_expected_output"
+>;
export interface ObservationEvalVariableColumn {
/** Column identifier (must match an ObservationForEval field name) */
- id: keyof Pick<
- ObservationForEval,
- "input" | "output" | "metadata" | "experiment_item_expected_output"
- >;
+ id: string;
/** Display name for UI */
name: string;
/** Description for UI tooltips */
description: string;
/** Optional type hint for special handling (e.g., stringObject for metadata) */
type?: "stringObject";
+ internal: ObservationEvalMappingColumnInternal;
}
/**
@@ -143,22 +120,234 @@ export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [
id: "input",
name: "Input",
description: "Observation input data",
+ internal: "input",
},
{
id: "output",
name: "Output",
description: "Observation output data",
+ internal: "output",
},
{
id: "metadata",
name: "Metadata",
description: "Observation metadata",
type: "stringObject",
+ internal: "metadata",
},
-
{
- id: "experiment_item_expected_output",
- name: "Experiment Item Expected Output",
+ id: "experimentItemExpectedOutput",
+ name: "Expected Output",
description: "Expected output from experiment item",
+ internal: "experiment_item_expected_output",
+ },
+];
+
+export const availableObservationEvalVariableColumns = [
+ ...observationEvalVariableColumns,
+ {
+ id: "toolCalls",
+ name: "Tool Calls",
+ description: "Tool calls",
+ internal: "tool_calls",
+ },
+ {
+ id: "toolDefinitions",
+ name: "Tool Definitions",
+ description: "Tool definitions",
+ internal: "tool_definitions",
+ },
+ {
+ id: "toolCallNames",
+ name: "Tool Call Names",
+ description: "Tool call names",
+ internal: "tool_call_names",
+ },
+ {
+ id: "providedModelName",
+ name: "Model",
+ description: "Model",
+ internal: "provided_model_name",
+ },
+ {
+ id: "modelParameters",
+ name: "Model Parameters",
+ description: "Model parameters",
+ internal: "model_parameters",
+ },
+ {
+ id: "usageDetails",
+ name: "Usage Details",
+ description: "Usage details",
+ internal: "usage_details",
+ },
+ {
+ id: "costDetails",
+ name: "Cost Details",
+ description: "Cost details",
+ internal: "cost_details",
+ },
+];
+
+type ObservationEvalColumnDef = ColumnDefinition & {
+ internal: ObservationEvalFilterColumnInternal;
+};
+
+/**
+ * Columns available for filtering in observation-based evals.
+ *
+ * These columns can be used in filter conditions to determine
+ * which observations should be evaluated.
+ */
+export const observationEvalFilterColumns: ObservationEvalColumnDef[] = [
+ {
+ name: "Type",
+ id: "type",
+ type: "stringOptions",
+ internal: "type",
+ options: Object.values(ObservationType).map((key) => ({ value: key })),
+ },
+ {
+ name: "Name",
+ id: "name",
+ type: "stringOptions",
+ internal: "name",
+ options: [], // to be filled at runtime
+ },
+ {
+ name: "Environment",
+ id: "environment",
+ type: "stringOptions",
+ internal: "environment",
+ options: [], // to be filled at runtime
+ },
+ {
+ name: "Level",
+ id: "level",
+ type: "stringOptions",
+ internal: "level",
+ options: Object.values(ObservationLevel).map((key) => ({ value: key })),
+ },
+ {
+ name: "Version",
+ id: "version",
+ type: "string",
+ internal: "version",
+ nullable: true,
+ },
+ {
+ name: "Trace Name",
+ id: "traceName",
+ type: "stringOptions",
+ internal: "trace_name",
+ options: [], // to be filled at runtime
+ nullable: true,
+ },
+ {
+ name: "User ID",
+ id: "userId",
+ type: "string",
+ internal: "user_id",
+ nullable: true,
+ },
+ {
+ name: "Session ID",
+ id: "sessionId",
+ type: "string",
+ internal: "session_id",
+ nullable: true,
},
+ {
+ name: "Tags",
+ id: "tags",
+ type: "arrayOptions",
+ internal: "tags",
+ options: [], // to be filled at runtime
+ },
+ {
+ name: "Metadata",
+ id: "metadata",
+ type: "stringObject",
+ internal: "metadata",
+ },
+];
+
+export const experimentEvalFilterColumns: ObservationEvalColumnDef[] = [
+ {
+ name: "Dataset",
+ id: "experimentDatasetId",
+ type: "stringOptions",
+ internal: "experiment_dataset_id",
+ options: [], // to be filled at runtime
+ },
+];
+
+export const eventsEvalFilterColumns: ObservationEvalColumnDef[] = [
+ ...observationEvalFilterColumns,
+ ...experimentEvalFilterColumns,
];
+
+// Options type for observation eval filters
+export type ObservationEvalOptions = {
+ environment?: Array<SingleValueOption>;
+ tags?: Array<SingleValueOption>;
+ traceName?: Array<SingleValueOption>;
+ name?: Array<SingleValueOption>;
+};
+
+export type ExperimentEvalOptions = {
+ experimentDatasetId?: Array<SingleValueOption>;
+};
+
+export function observationEvalFilterColsWithOptions(
+ options?: ObservationEvalOptions,
+ cols: ColumnDefinition[] = observationEvalFilterColumns,
+): ColumnDefinition[] {
+ return cols.map((col) => {
+ if (col.id === "environment") {
+ return formatColumnOptions(col, options?.environment ?? []);
+ }
+ if (col.id === "tags") {
+ return formatColumnOptions(col, options?.tags ?? []);
+ }
+ if (col.id === "traceName") {
+ return formatColumnOptions(col, options?.traceName ?? []);
+ }
+ if (col.id === "name") {
+ return formatColumnOptions(col, options?.name ?? []);
+ }
+ return col;
+ });
+}
+
+export function experimentEvalFilterColsWithOptions(
+ options?: ExperimentEvalOptions,
+ cols: ColumnDefinition[] = experimentEvalFilterColumns,
+): ColumnDefinition[] {
+ return cols.map((col) => {
+ if (col.id === "experimentDatasetId") {
+ return formatColumnOptions(col, options?.experimentDatasetId ?? []);
+ }
+ return col;
+ });
+}
+
+/**
+ * Field mapper for observation eval filters.
+ * Maps camelCase filter column IDs to snake_case observation fields.
+ * Based on events table column definitions.
+ *
+ * @param observation - The observation data object
+ * @param column - The camelCase column ID from filter definitions
+ * @returns The value from the observation object
+ */
+export function mapEventEvalFilterColumnIdToField(
+ observation: ObservationForEval,
+ column: string,
+) {
+ const columnMapping = eventsEvalFilterColumns.find((c) => c.id === column);
+ if (!columnMapping) {
+ return undefined;
+ }
+ return observation[columnMapping.internal];
+}
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index b5390a1ea8..834e9bdaef 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -35,16 +35,20 @@ export const variableMapping = z
.object({
templateVariable: z.string(), // variable name in the template
// name of the observation to extract the variable from
- // not required for trace, as we only have one.
+ // not required for trace or dataset_item, as we only have one of each.
objectName: z.string().nullish(),
langfuseObject: langfuseObject,
selectedColumnId: z.string(),
jsonSelector: z.string().nullish(),
})
.refine(
- (value) => value.langfuseObject === "trace" || value.objectName !== null,
+ (value) =>
+ value.langfuseObject === "trace" ||
+ value.langfuseObject === "dataset_item" ||
+ value.objectName !== null,
{
- message: "objectName is required for langfuseObjects other than trace",
+ message:
+ "objectName is required for observation objects (generation, span, score)",
},
);
@@ -53,7 +57,7 @@ export const variableMappingList = z.array(variableMapping);
export const wipVariableMapping = z.object({
templateVariable: z.string(),
objectName: z.string().nullish(),
- langfuseObject: langfuseObject,
+ langfuseObject: langfuseObject.optional(),
selectedColumnId: z.string().nullish(),
jsonSelector: z.string().nullish(),
});
@@ -173,12 +177,9 @@ export const TimeScopeSchema = z.array(JobTimeScopeZod).default(["NEW"]);
// Simplified variable mapping for observation-based evals.
// Unlike trace-based evals, we don't need objectName since we're directly
// targeting a specific observation - no need to specify which observation to extract from.
-//
-// Note: selectedColumnId must be a valid column ID from observationEvalVariableColumns.
-// See packages/shared/src/features/evals/observationForEval.ts for the source of truth.
export const observationVariableMapping = z.object({
templateVariable: z.string(), // variable name in the template
- selectedColumnId: z.string(), // column to extract (must match observationEvalVariableColumns)
+ selectedColumnId: z.string(), // column to extract (must match observationEvalVariableColumns.id)
jsonSelector: z.string().nullish(), // optional JSON path selector
});
diff --git a/packages/shared/src/features/evals/utilities.ts b/packages/shared/src/features/evals/utilities.ts
index b24aaf080a..abe930b7b0 100644
--- a/packages/shared/src/features/evals/utilities.ts
+++ b/packages/shared/src/features/evals/utilities.ts
@@ -1,6 +1,4 @@
-import z from "zod/v4";
import { JSONPath } from "jsonpath-plus";
-import { variableMapping } from "./types";
/**
* Parses an unknown value to a string representation
@@ -67,10 +65,11 @@ function parseJsonDefault(selectedColumn: unknown, jsonSelector: string) {
export function extractValueFromObject(
obj: Record<string, unknown>,
- mapping: z.infer<typeof variableMapping>,
+ selectedColumnId: string,
+ jsonSelector?: string,
parseJson?: (selectedColumn: unknown, jsonSelector: string) => unknown,
): { value: string; error: Error | null } {
- let selectedColumn = obj[mapping.selectedColumnId];
+ let selectedColumn = obj[selectedColumnId];
// Simple preprocessing: attempt to parse to valid JSON object
if (typeof selectedColumn === "string") {
@@ -82,9 +81,9 @@ export function extractValueFromObject(
let jsonSelectedColumn;
let error: Error | null = null;
- if (mapping.jsonSelector && selectedColumn) {
+ if (jsonSelector && selectedColumn) {
try {
- jsonSelectedColumn = jsonParser(selectedColumn, mapping.jsonSelector);
+ jsonSelectedColumn = jsonParser(selectedColumn, jsonSelector);
} catch (err) {
error =
err instanceof Error
diff --git a/web/src/components/table/peek/peek-evaluator-config-detail.tsx b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
index 8575ae7d47..488a0e66fb 100644
--- a/web/src/components/table/peek/peek-evaluator-config-detail.tsx
+++ b/web/src/components/table/peek/peek-evaluator-config-detail.tsx
@@ -19,6 +19,8 @@ import { useState } from "react";
import { cn } from "@/src/utils/tailwind";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { api } from "@/src/utils/api";
+import { LegacyEvalCallout } from "@/src/features/evals/components/legacy-eval-callout";
+import { useObservationEvals } from "@/src/features/events/hooks/useObservationEvals";
export const PeekViewEvaluatorConfigDetail = ({
projectId,
@@ -26,6 +28,7 @@ export const PeekViewEvaluatorConfigDetail = ({
projectId: string;
}) => {
const router = useRouter();
+ const isBetaEnabled = useObservationEvals();
const peekId = router.query.peek as string | undefined;
const [isEditMode, setIsEditMode] = useState(false);
const utils = api.useUtils();
@@ -75,6 +78,19 @@ export const PeekViewEvaluatorConfigDetail = ({
/>
</div>
</div>
+
+ {isBetaEnabled &&
+ evalConfig &&
+ evalConfig.targetObject &&
+ evalConfig.evalTemplate &&
+ evalConfig.finalStatus === "ACTIVE" && (
+ <LegacyEvalCallout
+ projectId={projectId}
+ evalConfigId={evalConfig.id}
+ targetObject={evalConfig.targetObject}
+ />
+ )}
+
<CardDescription className="flex items-center text-sm">
<span className="mr-2 text-sm font-medium">Referenced Evaluator</span>
{evalConfig.evalTemplate && (
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index d505836feb..d9ee4d64d3 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -37,7 +37,10 @@ import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { MemoizedIOTableCell } from "../../ui/IOTableCell";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
-import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
+import {
+ toAbsoluteTimeRange,
+ type TableDateRange,
+} from "@/src/utils/date-range-utils";
import { type ScoreAggregate } from "@langfuse/shared";
import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
@@ -126,6 +129,11 @@ export type ObservationsTableProps = {
promptVersion?: number;
modelId?: string;
omittedFilter?: string[];
+ // External control props for embedded preview tables
+ hideControls?: boolean;
+ externalFilterState?: FilterState;
+ externalDateRange?: TableDateRange;
+ limitRows?: number;
};
export default function ObservationsTable({
@@ -133,6 +141,10 @@ export default function ObservationsTable({
promptName,
promptVersion,
modelId,
+ hideControls = false,
+ externalFilterState,
+ externalDateRange,
+ limitRows,
}: ObservationsTableProps) {
const router = useRouter();
const { viewId } = router.query;
@@ -191,10 +203,11 @@ export default function ObservationsTable({
pageSize: withDefault(NumberParam, 50),
});
- const [rowHeight, setRowHeight] = useRowHeightLocalStorage(
+ const [storedRowHeight, setRowHeight] = useRowHeightLocalStorage(
"generations",
"s",
);
+ const rowHeight = hideControls ? "s" : storedRowHeight;
const [inputFilterState] = useQueryFilterState(
// If the user loads saved table view presets, we should not apply the default type filter
@@ -230,11 +243,13 @@ export default function ObservationsTable({
// Convert timeRange to absolute date range for compatibility
// refreshTick forces recalculation on each refresh cycle
- const dateRange = useMemo(() => {
+ const tableDateRange = useMemo(() => {
return toAbsoluteTimeRange(timeRange) ?? undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timeRange, refreshTick]);
+ const dateRange = externalDateRange ?? tableDateRange;
+
const promptNameFilter: FilterState = promptName
? [
{
@@ -416,6 +431,7 @@ export default function ObservationsTable({
newFilterOptions,
projectId,
filterOptions.isPending || environmentFilterOptions.isPending,
+ hideControls, // Disable URL persistence for embedded preview tables
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -427,13 +443,16 @@ export default function ObservationsTable({
[],
);
- const filterState = queryFilter.filterState.concat(
+ const combinedFilterState = queryFilter.filterState.concat(
dateRangeFilter,
promptNameFilter,
promptVersionFilter,
modelIdFilter,
);
+ // Use external filter state if provided, otherwise use combined filter state
+ const filterState = externalFilterState || combinedFilterState;
+
const backendFilterState = transformFiltersForBackend(
filterState,
OBSERVATION_COLUMN_TO_BACKEND_KEY,
@@ -452,8 +471,8 @@ export default function ObservationsTable({
const getAllPayload = {
...getCountPayload,
- page: paginationState.pageIndex,
- limit: paginationState.pageSize,
+ page: limitRows ? 0 : paginationState.pageIndex,
+ limit: limitRows ?? paginationState.pageSize,
orderBy: orderByState,
};
@@ -485,12 +504,12 @@ export default function ObservationsTable({
"observations",
generations.data.generations.map((g) => ({
id: g.id,
- params: g.traceTimestamp
- ? {
- timestamp: g.traceTimestamp.toISOString(),
- traceId: g.traceId || "",
- }
- : undefined,
+ params: {
+ traceId: g.traceId || "",
+ ...(g.traceTimestamp
+ ? { timestamp: g.traceTimestamp.toISOString() }
+ : {}),
+ },
})),
);
}
@@ -561,15 +580,17 @@ export default function ObservationsTable({
},
];
+ const enableSorting = !hideControls;
+
const columns: LangfuseColumnDef<ObservationsTableRow>[] = [
- selectActionColumn,
+ ...(hideControls ? [] : [selectActionColumn]),
{
accessorKey: "startTime",
id: "startTime",
header: "Start Time",
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: Date = row.getValue("startTime");
return <LocalIsoDate date={value} />;
@@ -580,7 +601,7 @@ export default function ObservationsTable({
id: "type",
header: "Type",
size: 50,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: ObservationType = row.getValue("type");
return value ? (
@@ -595,7 +616,7 @@ export default function ObservationsTable({
id: "name",
header: "Name",
size: 150,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: ObservationsTableRow["name"] = row.getValue("name");
return value ?? undefined;
@@ -668,7 +689,7 @@ export default function ObservationsTable({
</span>
) : undefined;
},
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "statusMessage",
@@ -695,7 +716,7 @@ export default function ObservationsTable({
) : undefined;
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "totalCost",
@@ -719,7 +740,7 @@ export default function ObservationsTable({
) : undefined;
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "toolDefinitions",
@@ -727,7 +748,7 @@ export default function ObservationsTable({
header: "Available Tools",
size: 120,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
cell: ({ row }) => {
const value: number | undefined = row.getValue("toolDefinitions");
@@ -742,7 +763,7 @@ export default function ObservationsTable({
header: "Tool Calls",
size: 100,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
cell: ({ row }) => {
const value: number | undefined = row.getValue("toolCalls");
@@ -757,7 +778,7 @@ export default function ObservationsTable({
header: "Time to First Token",
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const timeToFirstToken: number | undefined =
row.getValue("timeToFirstToken");
@@ -796,7 +817,7 @@ export default function ObservationsTable({
);
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "model",
@@ -804,7 +825,7 @@ export default function ObservationsTable({
header: "Model",
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const model = row.getValue("model") as string;
const modelId = row.getValue("modelId") as string | undefined;
@@ -852,7 +873,7 @@ export default function ObservationsTable({
},
size: 200,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const promptName = row.original.promptName;
const promptVersion = row.original.promptVersion;
@@ -942,7 +963,7 @@ export default function ObservationsTable({
header: "End Time",
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
cell: ({ row }) => {
const value: Date | undefined = row.getValue("endTime");
@@ -955,7 +976,7 @@ export default function ObservationsTable({
header: "ObservationID",
size: 100,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
enableHiding: true,
cell: ({ row }) => {
const observationId = row.getValue("id");
@@ -972,7 +993,7 @@ export default function ObservationsTable({
header: "Trace Name",
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
},
{
@@ -986,7 +1007,7 @@ export default function ObservationsTable({
<TableIdOrName value={value} />
) : undefined;
},
- enableSorting: true,
+ enableSorting,
enableHiding: true,
defaultHidden: true,
},
@@ -1008,7 +1029,7 @@ export default function ObservationsTable({
href: "https://langfuse.com/docs/experimentation",
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
},
{
@@ -1046,7 +1067,7 @@ export default function ObservationsTable({
},
defaultHidden: true,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "inputTokens",
@@ -1055,7 +1076,7 @@ export default function ObservationsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<ObservationsTableRow> }) => {
const value: {
inputUsage: number;
@@ -1072,7 +1093,7 @@ export default function ObservationsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<ObservationsTableRow> }) => {
const value: {
inputUsage: number;
@@ -1089,7 +1110,7 @@ export default function ObservationsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<ObservationsTableRow> }) => {
const value: {
inputUsage: number;
@@ -1130,7 +1151,7 @@ export default function ObservationsTable({
},
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "outputCost",
@@ -1149,7 +1170,7 @@ export default function ObservationsTable({
},
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
},
],
},
@@ -1196,17 +1217,17 @@ export default function ObservationsTable({
currentFilterState: queryFilter.filterState,
});
- const peekConfig: DataTablePeekViewProps = useMemo(
- () => ({
+ const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {
+ if (hideControls) return undefined;
+ return {
itemType: "TRACE",
customTitlePrefix: "Observation ID:",
detailNavigationKey: "observations",
children: <PeekViewObservationDetail projectId={projectId} />,
tableDataUpdatedAt: generations.dataUpdatedAt,
...peekNavigationProps,
- }),
- [projectId, generations.dataUpdatedAt, peekNavigationProps],
- );
+ };
+ }, [projectId, generations.dataUpdatedAt, peekNavigationProps, hideControls]);
const rows: ObservationsTableRow[] = useMemo(() => {
return generations.isSuccess
@@ -1257,85 +1278,93 @@ export default function ObservationsTable({
<DataTableControlsProvider>
<div className="flex h-full w-full flex-col">
{/* Toolbar spanning full width */}
- <DataTableToolbar
- columns={columns}
- filterState={queryFilter.filterState}
- searchConfig={{
- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- searchType,
- setSearchType,
- tableAllowsFullTextSearch: true,
- }}
- viewConfig={{
- tableName: TableViewPresetTableName.Observations,
- projectId,
- controllers: viewControllers,
- }}
- columnsWithCustomSelect={["model", "name", "traceName", "promptName"]}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibilityState}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- orderByState={orderByState}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- refreshConfig={{
- onRefresh: handleRefresh,
- isRefreshing: generations.isFetching || totalCountQuery.isFetching,
- interval: refreshInterval,
- setInterval: setRefreshInterval,
- }}
- actionButtons={[
- <BatchExportTableButton
- {...{
- projectId,
- filterState: backendFilterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Observations}
- key="batchExport"
- />,
- Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ).length > 0 ? (
- <TableActionMenu
- key="observations-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
- tableName={BatchExportTableName.Observations}
- onCustomAction={(actionType) => {
- if (actionType === ActionId.ObservationAddToDataset) {
- setShowAddToDatasetDialog(true);
- }
+ {!hideControls && (
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ searchType,
+ setSearchType,
+ tableAllowsFullTextSearch: true,
+ }}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Observations,
+ projectId,
+ controllers: viewControllers,
+ }}
+ columnsWithCustomSelect={[
+ "model",
+ "name",
+ "traceName",
+ "promptName",
+ ]}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibilityState}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ orderByState={orderByState}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ refreshConfig={{
+ onRefresh: handleRefresh,
+ isRefreshing:
+ generations.isFetching || totalCountQuery.isFetching,
+ interval: refreshInterval,
+ setInterval: setRefreshInterval,
+ }}
+ actionButtons={[
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState: backendFilterState,
+ orderByState,
+ searchQuery,
+ searchType,
}}
- />
- ) : null,
- ]}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
- generations.data?.generations
- .map((g) => g.id)
- .includes(generationId),
- ),
- setRowSelection: setSelectedRows,
- totalCount,
- ...paginationState,
- }}
- />
+ tableName={BatchExportTableName.Observations}
+ key="batchExport"
+ />,
+ Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ).length > 0 ? (
+ <TableActionMenu
+ key="observations-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Observations}
+ onCustomAction={(actionType) => {
+ if (actionType === ActionId.ObservationAddToDataset) {
+ setShowAddToDatasetDialog(true);
+ }
+ }}
+ />
+ ) : null,
+ ]}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds: Object.keys(selectedRows).filter((generationId) =>
+ generations.data?.generations
+ .map((g) => g.id)
+ .includes(generationId),
+ ),
+ setRowSelection: setSelectedRows,
+ totalCount,
+ ...paginationState,
+ }}
+ />
+ )}
{/* Content area with sidebar and table */}
<ResizableFilterLayout>
- <DataTableControls queryFilter={queryFilter} />
+ {!hideControls && <DataTableControls queryFilter={queryFilter} />}
<div className="flex flex-1 flex-col overflow-hidden">
<DataTable
@@ -1357,11 +1386,15 @@ export default function ObservationsTable({
data: rows,
}
}
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
+ pagination={
+ limitRows
+ ? undefined
+ : {
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }
+ }
rowSelection={selectedRows}
setRowSelection={setSelectedRows}
setOrderBy={setOrderByState}
diff --git a/web/src/components/ui/callout.tsx b/web/src/components/ui/callout.tsx
new file mode 100644
index 0000000000..d5b308f85e
--- /dev/null
+++ b/web/src/components/ui/callout.tsx
@@ -0,0 +1,118 @@
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { Button } from "@/src/components/ui/button";
+import useLocalStorage from "@/src/components/useLocalStorage";
+import { Info, AlertTriangle, X } from "lucide-react";
+import { useEffect, useState } from "react";
+
+const DEFAULT_STORAGE_KEY = "dismissed-callouts";
+const DEFAULT_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
+
+interface Callout {
+ id: string;
+ dismissedAt: number;
+}
+
+export interface CalloutProps {
+ id: string;
+ ttlMs?: number;
+ variant?: "info" | "warning";
+ align?: "top" | "middle";
+ children: React.ReactNode;
+ onDismiss?: () => void;
+ actions?: () => React.ReactNode;
+}
+
+export function Callout({
+ id: id,
+ ttlMs = DEFAULT_TTL_MS,
+ variant = "info",
+ align = "middle",
+ children,
+ onDismiss,
+ actions,
+}: CalloutProps) {
+ const [dismissedCallouts, setDismissedCallouts] = useLocalStorage<Callout[]>(
+ id + "-" + DEFAULT_STORAGE_KEY,
+ [],
+ );
+ const [isVisible, setIsVisible] = useState(false);
+
+ useEffect(() => {
+ // Check if this callout is dismissed and not expired
+ const dismissedCallout = dismissedCallouts.find((c) => c.id === id);
+
+ if (!dismissedCallout) {
+ setIsVisible(true);
+ return;
+ }
+
+ const now = Date.now();
+ const isExpired = now - dismissedCallout.dismissedAt > ttlMs;
+
+ if (isExpired) {
+ // Remove expired dismissal
+ setDismissedCallouts(dismissedCallouts.filter((c) => c.id !== id));
+ setIsVisible(true);
+ } else {
+ setIsVisible(false);
+ }
+ }, [id, dismissedCallouts, ttlMs, setDismissedCallouts]);
+
+ const handleDismiss = () => {
+ // Add this callout to dismissed list
+ const now = Date.now();
+ const updatedDismissedCallouts = dismissedCallouts.filter(
+ (c) => c.id !== id,
+ );
+ updatedDismissedCallouts.push({ id: id, dismissedAt: now });
+ setDismissedCallouts(updatedDismissedCallouts);
+
+ // Call optional callback
+ onDismiss?.();
+
+ setIsVisible(false);
+ };
+
+ if (!isVisible) return null;
+
+ const Icon = variant === "warning" ? AlertTriangle : Info;
+ const variantClass =
+ variant === "warning"
+ ? "border-light-yellow bg-light-yellow dark:border-light-yellow dark:bg-light-yellow"
+ : "border-light-blue bg-light-blue dark:border-light-blue dark:bg-light-blue";
+ const alignmentClass = align === "middle" ? "items-center" : "items-start";
+
+ const alignmentOverrides =
+ align === "middle"
+ ? "[&>svg]:top-1/2 [&>svg]:-translate-y-1/2 [&>svg+div]:translate-y-0"
+ : "";
+
+ return (
+ <Alert className={`${variantClass} ${alignmentOverrides}`}>
+ <Icon
+ className={`h-4 w-4 ${
+ variant === "warning"
+ ? "text-dark-yellow dark:text-dark-yellow"
+ : "text-dark-blue dark:text-dark-blue"
+ }`}
+ />
+ <AlertDescription
+ className={`flex ${alignmentClass} ml-1 justify-between`}
+ >
+ <div className="flex-1 text-sm text-foreground">{children}</div>
+ <div className="ml-4 flex items-center gap-2">
+ {actions && actions()}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={handleDismiss}
+ className="h-6 w-6 p-0 text-muted-foreground hover:text-foreground"
+ aria-label="Dismiss"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+ );
+}
diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsx
index e3a406b6bd..7fa8b82f49 100644
--- a/web/src/components/ui/dialog.tsx
+++ b/web/src/components/ui/dialog.tsx
@@ -38,6 +38,7 @@ const dialogContentVariants = cva(
default: "max-w-lg max-h-[85vh]",
lg: "max-w-4xl max-h-[85vh]",
xl: "max-w-7xl h-[90vh]",
+ xxl: "max-w-[95vw] h-[90vh]",
},
},
defaultVariants: {
@@ -160,7 +161,7 @@ const DialogDescription = React.forwardRef<
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
- className={cn("text-sm text-muted-foreground", className)}
+ className={cn("mt-1 text-sm text-muted-foreground", className)}
{...props}
/>
));
diff --git a/web/src/components/ui/input.tsx b/web/src/components/ui/input.tsx
index b3e9e10fdd..c783e25f83 100644
--- a/web/src/components/ui/input.tsx
+++ b/web/src/components/ui/input.tsx
@@ -14,7 +14,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
{...(!allowPasswordManager && { "data-1p-ignore": true })}
type={type}
className={cn(
- "flex h-8 w-full min-w-14 rounded-md border border-input bg-background px-2 py-1 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus:ring-0 focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-8 w-full min-w-14 rounded-md border border-input bg-background px-2 py-1 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus:ring-0 focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:bg-muted/50 disabled:opacity-50",
className,
)}
ref={ref}
diff --git a/web/src/components/ui/select.tsx b/web/src/components/ui/select.tsx
index b12c887740..b7783408f5 100644
--- a/web/src/components/ui/select.tsx
+++ b/web/src/components/ui/select.tsx
@@ -21,7 +21,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
- "flex h-8 w-full items-center justify-between gap-1 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
+ "flex h-8 w-full items-center justify-between gap-1 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:bg-muted/50 disabled:opacity-50 [&>span]:line-clamp-1",
className,
)}
{...props}
diff --git a/web/src/components/ui/textarea.tsx b/web/src/components/ui/textarea.tsx
index cc141a579c..83c080aabf 100644
--- a/web/src/components/ui/textarea.tsx
+++ b/web/src/components/ui/textarea.tsx
@@ -10,7 +10,7 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
return (
<textarea
className={cn(
- "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ "flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-muted/50 disabled:opacity-50",
className,
)}
ref={ref}
diff --git a/web/src/features/evals/components/eval-form-descriptions.tsx b/web/src/features/evals/components/eval-form-descriptions.tsx
index 62f037d4ab..e628bba8ac 100644
--- a/web/src/features/evals/components/eval-form-descriptions.tsx
+++ b/web/src/features/evals/components/eval-form-descriptions.tsx
@@ -13,27 +13,3 @@ export function VariableMappingDescription(p: {
</div>
);
}
-
-export function TimeScopeDescription(props: {
- projectId: string;
- timeScope: ("NEW" | "EXISTING")[] | undefined;
- target: "trace" | "dataset_item" | undefined;
-}) {
- if (!props.timeScope || props.timeScope.length === 0) {
- return "Select a time scope to run this configuration on.";
- }
-
- return (
- <span>
- This configuration will target{" "}
- {props.timeScope?.includes("NEW") && props.timeScope?.includes("EXISTING")
- ? "all future and existing"
- : props.timeScope?.includes("NEW")
- ? "all future"
- : "all existing"}{" "}
- {props.target === "trace" ? "traces" : "dataset run items"} that match
- these filters. Please note that it might take a while for your data to be
- evaluated.
- </span>
- );
-}
diff --git a/web/src/features/evals/components/eval-version-callout.tsx b/web/src/features/evals/components/eval-version-callout.tsx
new file mode 100644
index 0000000000..8d91327ed2
--- /dev/null
+++ b/web/src/features/evals/components/eval-version-callout.tsx
@@ -0,0 +1,155 @@
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { Info, AlertTriangle } from "lucide-react";
+import { type EvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";
+import {
+ isTraceTarget,
+ isEventTarget,
+ isExperimentTarget,
+ isDatasetTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+
+interface EvalVersionCalloutProps {
+ targetObject: string;
+ evalCapabilities: EvalCapabilities;
+}
+
+type CalloutVariant = "info" | "warning" | "hidden";
+
+interface CalloutContent {
+ variant: CalloutVariant;
+ title: string;
+ description: React.ReactNode;
+}
+
+const getCalloutContent = (
+ targetObject: string,
+ evalCapabilities: EvalCapabilities,
+): CalloutContent => {
+ // For event/observation target
+ if (isEventTarget(targetObject)) {
+ // If user IS compatible with OTEL, don't show callout
+ if (evalCapabilities.isNewCompatible) {
+ return {
+ variant: "hidden",
+ title: "",
+ description: "",
+ };
+ }
+
+ // If user is NOT compatible with OTEL, show warning
+ return {
+ variant: "warning",
+ title: "Newer version of the Langfuse SDK required",
+ description: (
+ <>
+ Running evaluators on live observations require JS SDK &ge; 4.0.0 or
+ Python SDK &ge; 3.0.0. You can still set up this evaluator now—it will
+ start running once you upgrade your SDK to latest.{" "}
+ <a
+ href="https://langfuse.com/docs/tracing/overview#langfuse-tracing-vs-opentelemetry"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-dark-blue hover:opacity-80"
+ >
+ Learn how to upgrade
+ </a>
+ .
+ </>
+ ),
+ };
+ }
+
+ // For experiment target (OTEL-based experiments)
+ if (isExperimentTarget(targetObject)) {
+ // If user is NOT compatible with OTEL, show warning
+ if (!evalCapabilities.isNewCompatible) {
+ return {
+ variant: "warning",
+ title: "Are you sure you are already on the recommended SDK version?",
+ description: (
+ <>
+ Running evaluators requires JS SDK &ge; 4.4.0 or Python SDK &ge;
+ 3.9.0. You can still set your evaluator up now—it will start running
+ once you upgrade to the latest SDK version.{" "}
+ <a
+ href="https://langfuse.com/docs/tracing/overview#langfuse-tracing-vs-opentelemetry"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-dark-blue hover:opacity-80"
+ >
+ Learn how to upgrade
+ </a>
+ .
+ </>
+ ),
+ };
+ }
+ }
+
+ // For dataset target (now represents non-OTEL experiments when selected via second tab)
+ if (isDatasetTarget(targetObject)) {
+ return {
+ variant: "info",
+ title: "You selected an old SDK version",
+ description:
+ "Please consider upgrading to the latest SDK version for improved performance and features. You can even set up the evaluator for the new version now—it will start running once you upgrade to the latest SDK version.",
+ };
+ }
+
+ // For trace target - always show deprecation info
+ if (isTraceTarget(targetObject)) {
+ return {
+ variant: "info",
+ title: "Consider upgrading to live observations evaluators",
+ description:
+ "Live observations evaluators provide more granular control and an easier workflow. We strongly recommend upgrading to live observations evaluators.",
+ };
+ }
+
+ // Default: hidden
+ return {
+ variant: "hidden",
+ title: "",
+ description: "",
+ };
+};
+
+export function EvalVersionCallout({
+ targetObject,
+ evalCapabilities,
+}: EvalVersionCalloutProps) {
+ const content = getCalloutContent(targetObject, evalCapabilities);
+
+ if (content.variant === "hidden") {
+ return null;
+ }
+
+ const isWarning = content.variant === "warning";
+
+ return (
+ <Alert
+ variant="default"
+ className={
+ isWarning
+ ? "mt-2 border-light-yellow bg-light-yellow"
+ : "mt-2 border-light-blue bg-light-blue"
+ }
+ >
+ {isWarning ? (
+ <AlertTriangle className="h-4 w-4 text-dark-yellow dark:text-dark-yellow" />
+ ) : (
+ <Info className="h-4 w-4 text-dark-blue dark:text-dark-blue" />
+ )}
+ <AlertDescription>
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-1">
+ <span className="font-medium text-foreground">{content.title}</span>
+ <span className="text-sm text-foreground">
+ {content.description}
+ </span>
+ </div>
+ </div>
+ </AlertDescription>
+ </Alert>
+ );
+}
diff --git a/web/src/features/evals/components/evaluation-prompt-preview.tsx b/web/src/features/evals/components/evaluation-prompt-preview.tsx
index 4a4019db0a..23877b6d26 100644
--- a/web/src/features/evals/components/evaluation-prompt-preview.tsx
+++ b/web/src/features/evals/components/evaluation-prompt-preview.tsx
@@ -1,12 +1,13 @@
-import { ItemBadge } from "@/src/components/ItemBadge";
+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";
import { Skeleton } from "@/src/components/ui/skeleton";
import { useExtractVariables } from "@/src/features/evals/hooks/useExtractVariables";
import { type VariableMapping } from "@/src/features/evals/utils/evaluator-form-utils";
import { cn } from "@/src/utils/tailwind";
-import { type RouterOutput } from "@/src/utils/types";
-import { type EvalTemplate } from "@langfuse/shared";
+import { EvalTargetObject, type EvalTemplate } from "@langfuse/shared";
import Link from "next/link";
import { Fragment, useMemo } from "react";
+import { isTraceTarget } from "@/src/features/evals/utils/typeHelpers";
+import { type PreviewData } from "@/src/features/evals/hooks/usePreviewData";
const VARIABLE_COLORS = [
"text-primary-accent",
@@ -112,16 +113,18 @@ const ColoredPromptView = ({
};
export const EvaluationPromptPreview = ({
+ previewData,
+ projectId,
evalTemplate,
- trace,
variableMapping,
isLoading,
showControls = true,
className,
controlButtons,
}: {
+ previewData: PreviewData;
+ projectId: string;
evalTemplate: EvalTemplate;
- trace: RouterOutput["traces"]["byIdWithObservationsAndScores"];
variableMapping: VariableMapping[];
isLoading: boolean;
showControls?: boolean;
@@ -136,7 +139,7 @@ export const EvaluationPromptPreview = ({
const { extractedVariables, isExtracting } = useExtractVariables({
variables: memoizedVariables,
variableMapping,
- trace: trace,
+ previewData,
isLoading,
});
@@ -210,19 +213,41 @@ export const EvaluationPromptPreview = ({
return content;
}
+ // Get target URL and badge type based on target type
+ const getTargetLink = () => {
+ if (isTraceTarget(previewData.type)) {
+ return {
+ href: `/project/${projectId}/traces/${previewData.traceId}`,
+ badgeType: "TRACE" as const,
+ };
+ } else if (previewData.type === EvalTargetObject.EVENT) {
+ return {
+ href: `/project/${projectId}/traces/${previewData.traceId}?observation=${previewData.observationId}`,
+ badgeType: "OBSERVATION" as const,
+ };
+ }
+ };
+
+ const targetLink = getTargetLink();
+
return (
<div className={cn("flex flex-col", className)}>
<span className="mb-1 flex flex-row items-center justify-between py-0 text-sm font-medium capitalize">
<div className="flex flex-row items-center gap-2">
Evaluation Prompt Preview
- <Link
- href={`/project/${trace.projectId}/traces/${trace.id}`}
- className="hover:cursor-pointer"
- target="_blank"
- rel="noopener noreferrer"
- >
- <ItemBadge type="TRACE" showLabel />
- </Link>
+ {targetLink && (
+ <Link
+ href={targetLink.href}
+ className="hover:cursor-pointer"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <ItemBadge
+ type={targetLink.badgeType as LangfuseItemType}
+ showLabel
+ />
+ </Link>
+ )}
</div>
{controlButtons}
</span>
diff --git a/web/src/features/evals/components/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsx
index 4236ae7bbe..df297a1dbf 100644
--- a/web/src/features/evals/components/evaluator-form.tsx
+++ b/web/src/features/evals/components/evaluator-form.tsx
@@ -1,6 +1,8 @@
import { type EvalTemplate } 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";
+import { Skeleton } from "@/src/components/ui/skeleton";
export const EvaluatorForm = (props: {
projectId: string;
@@ -16,6 +18,8 @@ export const EvaluatorForm = (props: {
preventRedirect?: boolean;
preprocessFormValues?: (values: any) => any;
}) => {
+ const evalCapabilities = useEvalCapabilities(props.projectId);
+
const currentTemplate =
props.existingEvaluator?.evalTemplate ??
props.evalTemplates.find((t) => t.id === props.templateId);
@@ -26,19 +30,26 @@ export const EvaluatorForm = (props: {
return (
<>
- <InnerEvaluatorForm
- projectId={props.projectId}
- disabled={props.disabled}
- existingEvaluator={props.existingEvaluator}
- evalTemplate={props.existingEvaluator?.evalTemplate ?? currentTemplate}
- onFormSuccess={props.onFormSuccess}
- shouldWrapVariables={props.shouldWrapVariables}
- hideTargetSection={props.hideTargetSection}
- mode={props.mode}
- preventRedirect={props.preventRedirect ?? true}
- preprocessFormValues={props.preprocessFormValues}
- useDialog={props.useDialog}
- />
+ {evalCapabilities.isLoading ? (
+ <Skeleton className="h-[30dvh] w-full" />
+ ) : (
+ <InnerEvaluatorForm
+ projectId={props.projectId}
+ disabled={props.disabled}
+ existingEvaluator={props.existingEvaluator}
+ evalTemplate={
+ props.existingEvaluator?.evalTemplate ?? currentTemplate
+ }
+ onFormSuccess={props.onFormSuccess}
+ shouldWrapVariables={props.shouldWrapVariables}
+ hideTargetSection={props.hideTargetSection}
+ mode={props.mode}
+ preventRedirect={props.preventRedirect ?? true}
+ preprocessFormValues={props.preprocessFormValues}
+ useDialog={props.useDialog}
+ evalCapabilities={evalCapabilities}
+ />
+ )}
</>
);
};
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index 1b6db526a1..b4c3b3df8d 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -17,7 +17,7 @@ import { type RouterOutputs, api } from "@/src/utils/api";
import { safeExtract } from "@/src/utils/map-utils";
import { type FilterState, singleFilter } from "@langfuse/shared";
import { createColumnHelper } from "@tanstack/react-table";
-import { useEffect, useState } from "react";
+import { useEffect, useState, useMemo } from "react";
import {
useQueryParams,
withDefault,
@@ -27,9 +27,19 @@ import {
} from "use-query-params";
import { z } from "zod/v4";
import { generateJobExecutionCounts } from "@/src/features/evals/utils/job-execution-utils";
+import {
+ isLegacyEvalTarget,
+ isEventTarget,
+} from "@/src/features/evals/utils/typeHelpers";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import TableIdOrName from "@/src/components/table/table-id";
-import { MoreVertical, Loader2, ExternalLinkIcon, Edit } from "lucide-react";
+import {
+ MoreVertical,
+ Loader2,
+ ExternalLinkIcon,
+ Edit,
+ Info,
+} from "lucide-react";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { PeekViewEvaluatorConfigDetail } from "@/src/components/table/peek/peek-evaluator-config-detail";
import {
@@ -55,6 +65,15 @@ import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-to
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { Skeleton } from "@/src/components/ui/skeleton";
import { usdFormatter } from "@/src/utils/numbers";
+import { Callout } from "@/src/components/ui/callout";
+import Link from "next/link";
+import { Badge } from "@/src/components/ui/badge";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { useObservationEvals } from "@/src/features/events/hooks/useObservationEvals";
export type EvaluatorDataRow = {
id: string;
@@ -78,9 +97,49 @@ export type EvaluatorDataRow = {
logs?: string;
actions?: string;
totalCost?: number | null;
+ isLegacy?: boolean;
};
+function LegacyBadgeCell({ status }: { status: string }) {
+ return (
+ <div className="flex items-center gap-1.5">
+ <Badge variant="warning">
+ Legacy
+ {status === "ACTIVE" && (
+ <Tooltip>
+ <TooltipTrigger>
+ <Info className="ml-1 h-3.5 w-3.5 text-dark-yellow" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[280px]">
+ <div className="space-y-1 text-sm">
+ <p className="font-medium">Action required</p>
+ <p className="text-muted-foreground">
+ This evaluator requires changes to benefit from new features
+ and performance improvements. Please follow{" "}
+ <Link
+ href="https://langfuse.com/faq/all/llm-as-a-judge-migration"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-dark-blue hover:opacity-80"
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ >
+ this guide
+ </Link>{" "}
+ to upgrade to the new version.
+ </p>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </Badge>
+ </div>
+ );
+}
+
export default function EvaluatorTable({ projectId }: { projectId: string }) {
+ const isBetaEnabled = useObservationEvals();
const router = useRouter();
const { setDetailPageList } = useDetailPageLists();
const [paginationState, setPaginationState] = useQueryParams({
@@ -151,6 +210,15 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
},
);
+ const hasLegacyEvals = useMemo(() => {
+ if (!evaluators.data?.configs) return false;
+ return evaluators.data.configs.some(
+ (config) =>
+ config.finalStatus === "ACTIVE" &&
+ isLegacyEvalTarget(config.targetObject),
+ );
+ }, [evaluators.data?.configs]);
+
useEffect(() => {
if (evaluators.isSuccess) {
const { configs: configList = [] } = evaluators.data ?? {};
@@ -263,11 +331,37 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
enableSorting: true,
size: 150,
}),
+ ...(isBetaEnabled
+ ? [
+ columnHelper.accessor("isLegacy", {
+ id: "isLegacy",
+ header: "Eval Version",
+ size: 180,
+ enableHiding: true,
+ cell: (row) => {
+ const targetObject = row.row.original.target;
+ const status = row.row.original.status;
+ const isDeprecated = isLegacyEvalTarget(targetObject);
+
+ if (!isDeprecated) return null;
+
+ return <LegacyBadgeCell status={status} />;
+ },
+ }),
+ ]
+ : []),
columnHelper.accessor("target", {
id: "target",
- header: "Target",
+ header: "Runs on",
size: 150,
enableHiding: true,
+ cell: (row) => {
+ const targetObject = row.getValue();
+ const renderText = isEventTarget(targetObject)
+ ? "observations"
+ : targetObject;
+ return <span className="text-muted-foreground">{renderText}</span>;
+ },
}),
columnHelper.accessor("filter", {
id: "filter",
@@ -395,6 +489,7 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
: "Langfuse maintained"
: "Not available",
totalCost: costData,
+ isLegacy: isLegacyEvalTarget(jobConfig.targetObject),
};
};
@@ -404,6 +499,32 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
defaultSidebarCollapsed={evaluatorFilterConfig.defaultSidebarCollapsed}
>
<div className="flex h-full w-full flex-col">
+ {isBetaEnabled && hasLegacyEvals && (
+ <div className="p-2 pb-0">
+ <Callout
+ id="eval-remapping-table"
+ variant="info"
+ key="dismissed-eval-remapping-callouts"
+ >
+ <span>New LLM-as-a-Judge functionality has landed. </span>
+ <span className="font-semibold">
+ Some of your evaluators (marked &quot;Legacy&quot;) require
+ changes{" "}
+ </span>
+ <span>for new features and improvements. </span>
+ <Link
+ href="https://langfuse.com/faq/all/llm-as-a-judge-migration"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-dark-blue hover:opacity-80"
+ >
+ Learn what is changing and how to upgrade
+ </Link>
+ <span>.</span>
+ </Callout>
+ </div>
+ )}
+
{/* Toolbar spanning full width */}
<DataTableToolbar
columns={columns}
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index b05e76b399..771dae0ec7 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -1,4 +1,4 @@
-import { type UseFormReturn, useFieldArray, useForm } from "react-hook-form";
+import { type UseFormReturn, useForm } from "react-hook-form";
import { Input } from "@/src/components/ui/input";
import { Button } from "@/src/components/ui/button";
import {
@@ -10,123 +10,138 @@ import {
FormLabel,
FormMessage,
} from "@/src/components/ui/form";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
import { zodResolver } from "@hookform/resolvers/zod";
import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import {
tracesTableColsWithOptions,
- evalTraceTableCols,
- evalDatasetFormFilterCols,
singleFilter,
availableTraceEvalVariables,
datasetFormFilterColsWithOptions,
- availableDatasetEvalVariables,
- type ObservationType,
- LangfuseInternalTraceEnvironment,
+ type availableDatasetEvalVariables,
+ observationEvalFilterColsWithOptions,
+ experimentEvalFilterColsWithOptions,
+ type ColumnDefinition,
} from "@langfuse/shared";
import { z } from "zod/v4";
import { useEffect, useMemo, useState, memo } from "react";
import { api } from "@/src/utils/api";
-import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";
-import { type EvalTemplate, variableMapping } from "@langfuse/shared";
+import {
+ InlineFilterBuilder,
+ type ColumnDefinitionWithAlert,
+} from "@/src/features/filters/components/filter-builder";
+import {
+ type EvalTemplate,
+ variableMapping,
+ observationVariableMapping,
+} from "@langfuse/shared";
import { useRouter } from "next/router";
import { Slider } from "@/src/components/ui/slider";
import { Card } from "@/src/components/ui/card";
-import { JSONView } from "@/src/components/ui/CodeJsonViewer";
-import DocPopup from "@/src/components/layouts/doc-popup";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { cn } from "@/src/utils/tailwind";
import { Checkbox } from "@/src/components/ui/checkbox";
import {
evalConfigFormSchema,
type EvalFormType,
- isTraceOrDatasetObject,
- isTraceTarget,
+ getTargetDisplayName,
+ inferDefaultMapping,
type LangfuseObject,
- type VariableMapping,
} from "@/src/features/evals/utils/evaluator-form-utils";
+import { validateAndTransformVariableMapping } from "@/src/features/evals/utils/variable-mapping-validation";
+import { EvalTargetObject } from "@langfuse/shared";
import { ExecutionCountTooltip } from "@/src/features/evals/components/execution-count-tooltip";
-import {
- TimeScopeDescription,
- VariableMappingDescription,
-} from "@/src/features/evals/components/eval-form-descriptions";
import { Suspense, lazy } from "react";
import {
getDateFromOption,
type TableDateRange,
} from "@/src/utils/date-range-utils";
-import { useEvalConfigMappingData } from "@/src/features/evals/hooks/useEvalConfigMappingData";
import { type PartialConfig } from "@/src/features/evals/types";
-import { Switch } from "@/src/components/ui/switch";
-import {
- EvaluationPromptPreview,
- getVariableColor,
-} from "@/src/features/evals/components/evaluation-prompt-preview";
-import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { type EvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";
+import { EvalVersionCallout } from "@/src/features/evals/components/eval-version-callout";
import { Skeleton } from "@/src/components/ui/skeleton";
-import { DialogBody, DialogFooter } from "@/src/components/ui/dialog";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
import {
Tooltip,
TooltipTrigger,
TooltipContent,
} from "@/src/components/ui/tooltip";
import { InfoIcon } from "lucide-react";
+import {
+ isDatasetTarget,
+ isEventTarget,
+ isExperimentTarget,
+ isLegacyEvalTarget,
+ isTraceTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+import {
+ useUserFacingTarget,
+ useEvaluatorTargetState,
+} from "@/src/features/evals/hooks/useEvaluatorTarget";
+import {
+ COLUMN_IDENTIFIERS_THAT_REQUIRE_PROPAGATION,
+ DEFAULT_TRACE_FILTER,
+} from "@/src/features/evals/utils/evaluator-constants";
+import { useEvalConfigFilterOptions } from "@/src/features/evals/hooks/useEvalConfigFilterOptions";
+import { VariableMappingCard } from "@/src/features/evals/components/variable-mapping-card";
+import { useObservationEvals } from "@/src/features/events/hooks/useObservationEvals";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
-// Lazy load TracesTable
+/**
+ * Adds propagation warnings to columns that require OTEL SDK with span propagation
+ */
+const addPropagationWarnings = (
+ columns: ColumnDefinition[],
+ allowPropagationFilters: boolean,
+): ColumnDefinitionWithAlert[] => {
+ return columns.map((col) => {
+ if (
+ !allowPropagationFilters &&
+ COLUMN_IDENTIFIERS_THAT_REQUIRE_PROPAGATION.has(col.id)
+ ) {
+ return {
+ ...col,
+ alert: {
+ severity: "warning" as const,
+ content: (
+ <>
+ This filter requires JS SDK &ge; 4.4.0 or Python SDK &ge; 3.9.0
+ with attribute propagation enabled. Please{" "}
+ <a
+ href="https://langfuse.com/integrations/native/opentelemetry"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-dark-blue hover:opacity-80"
+ >
+ follow our docs
+ </a>{" "}
+ to configure your instrumentation to use this filter.
+ </>
+ ),
+ },
+ };
+ }
+
+ return col;
+ });
+};
+
+// Lazy load tables
const TracesTable = lazy(
() => import("@/src/components/table/use-cases/traces"),
);
+const ObservationsTable = lazy(
+ () => import("@/src/components/table/use-cases/observations"),
+);
-const OUTPUT_MAPPING = [
- "generation",
- "output",
- "response",
- "answer",
- "completion",
-];
-
-const INTERNAL_ENVIRONMENTS = [
- LangfuseInternalTraceEnvironment.LLMJudge,
- "langfuse-prompt-experiments",
- "langfuse-evaluation",
- "sdk-experiment",
-] as const;
-
-// Default filter for new trace evaluators - excludes internal Langfuse environments
-// to prevent evaluators from running on their own traces
-const DEFAULT_TRACE_FILTER = [
- {
- column: "environment",
- operator: "none of" as const,
- value: [...INTERNAL_ENVIRONMENTS],
- type: "stringOptions" as const,
- },
-];
-
-const inferDefaultMapping = (
- variable: string,
-): Pick<VariableMapping, "langfuseObject" | "selectedColumnId"> => {
- return {
- langfuseObject: "trace" as const,
- selectedColumnId: OUTPUT_MAPPING.includes(variable.toLowerCase())
- ? "output"
- : "input",
- };
-};
-
-const fieldHasJsonSelectorOption = (
- selectedColumnId: string | undefined | null,
-): boolean =>
- selectedColumnId === "input" ||
- selectedColumnId === "output" ||
- selectedColumnId === "metadata" ||
- selectedColumnId === "expected_output";
+const EventsTable = lazy(
+ () => import("@/src/features/events/components/EventsTable"),
+);
const TracesPreview = memo(
({
@@ -173,6 +188,63 @@ const TracesPreview = memo(
TracesPreview.displayName = "TracesPreview";
+const ObservationsPreview = memo(
+ ({
+ projectId,
+ filterState,
+ }: {
+ projectId: string;
+ filterState: z.infer<typeof singleFilter>[];
+ }) => {
+ const isv4Enabled = useV4Beta();
+
+ const dateRange = useMemo(() => {
+ return {
+ from: getDateFromOption({
+ filterSource: "TABLE",
+ option: "last1Day",
+ }),
+ } as TableDateRange;
+ }, []);
+
+ return (
+ <>
+ <div className="flex flex-col items-start gap-1">
+ <span className="text-sm font-medium leading-none">
+ Preview sample matched observations
+ </span>
+ <FormDescription>
+ Sample over the last 24 hours that match these filters
+ </FormDescription>
+ </div>
+ <div className="mb-4 flex max-h-[30dvh] w-full flex-col overflow-hidden border-b border-l border-r">
+ <Suspense fallback={<Skeleton className="h-[30dvh] w-full" />}>
+ {isv4Enabled ? (
+ <EventsTable
+ projectId={projectId}
+ hideControls
+ externalFilterState={filterState}
+ externalDateRange={dateRange}
+ limitRows={10}
+ />
+ ) : (
+ <ObservationsTable
+ projectId={projectId}
+ hideControls
+ externalFilterState={filterState}
+ externalDateRange={dateRange}
+ limitRows={10}
+ />
+ )}
+ </Suspense>
+ </div>
+ </>
+ );
+ },
+);
+
+ObservationsPreview.displayName = "ObservationsPreview";
+
export const InnerEvaluatorForm = (props: {
projectId: string;
evalTemplate: EvalTemplate;
@@ -185,12 +257,40 @@ export const InnerEvaluatorForm = (props: {
hideTargetSection?: boolean;
preventRedirect?: boolean;
preprocessFormValues?: (values: any) => any;
+ hideAdvancedSettings?: boolean;
+ hideTargetSelection?: boolean;
+ evalCapabilities: EvalCapabilities;
+ renderFooter?: (params: {
+ isLoading: boolean;
+ formError: string | null;
+ }) => React.ReactNode;
+ oldConfigId?: string;
}) => {
const [formError, setFormError] = useState<string | null>(null);
+ const isBetaEnabled = useObservationEvals();
const capture = usePostHogClientCapture();
- const [showPreview, setShowPreview] = useState(false);
const router = useRouter();
- const traceId = router.query.traceId as string;
+ const [showTraceConfirmDialog, setShowTraceConfirmDialog] = useState(false);
+
+ // Destructure eval capabilities passed from parent
+ const { allowLegacy, allowPropagationFilters } = props.evalCapabilities;
+
+ // Custom hooks for managing evaluator state
+ const {
+ userFacingTarget,
+ setUserFacingTarget,
+ useOtelDataForExperiment,
+ setUseOtelDataForExperiment,
+ } = useUserFacingTarget(props.existingEvaluator?.targetObject);
+
+ const {
+ traceFilterOptions,
+ observationEvalFilterOptions,
+ experimentEvalFilterOptions,
+ datasetFilterOptions,
+ } = useEvalConfigFilterOptions({ projectId: props.projectId });
+
+ const targetState = useEvaluatorTargetState();
const form = useForm({
resolver: zodResolver(evalConfigFormSchema),
@@ -198,23 +298,33 @@ export const InnerEvaluatorForm = (props: {
defaultValues: {
scoreName:
props.existingEvaluator?.scoreName ?? `${props.evalTemplate.name}`,
- target: props.existingEvaluator?.targetObject ?? "trace",
+ target:
+ props.existingEvaluator?.targetObject ??
+ (isBetaEnabled ? EvalTargetObject.EVENT : EvalTargetObject.TRACE),
filter: props.existingEvaluator?.filter
? z.array(singleFilter).parse(props.existingEvaluator.filter)
: // For new trace evaluators, exclude internal environments by default
- (props.existingEvaluator?.targetObject ?? "trace") === "trace"
+ (props.existingEvaluator?.targetObject ?? EvalTargetObject.TRACE) ===
+ EvalTargetObject.TRACE
? DEFAULT_TRACE_FILTER
: [],
mapping: props.existingEvaluator?.variableMapping
- ? z
- .array(variableMapping)
- .parse(props.existingEvaluator.variableMapping)
+ ? isEventTarget(props.existingEvaluator.targetObject) ||
+ isExperimentTarget(props.existingEvaluator.targetObject)
+ ? z
+ .array(observationVariableMapping)
+ .parse(props.existingEvaluator.variableMapping)
+ : z
+ .array(variableMapping)
+ .parse(props.existingEvaluator.variableMapping)
: z.array(variableMapping).parse(
props.evalTemplate
? props.evalTemplate.vars.map((v) => ({
templateVariable: v,
langfuseObject: "trace" as const,
+ objectName: null,
selectedColumnId: "input",
+ jsonSelector: null,
}))
: [],
),
@@ -231,101 +341,16 @@ export const InnerEvaluatorForm = (props: {
},
}) as UseFormReturn<EvalFormType>;
- const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
- { projectId: props.projectId },
- {
- trpc: { context: { skipBatch: true } },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
- const environmentFilterOptionsResponse =
- api.projects.environmentFilterOptions.useQuery(
- {
- projectId: props.projectId,
- },
- {
- trpc: { context: { skipBatch: true } },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
- const traceFilterOptions = useMemo(() => {
- // Normalize API response to match TraceOptions type (count should be number, not string)
- const normalized = traceFilterOptionsResponse.data
- ? {
- name: traceFilterOptionsResponse.data.name?.map((n) => ({
- value: n.value,
- count: Number(n.count),
- })),
- scores_avg: traceFilterOptionsResponse.data.scores_avg,
- score_categories: traceFilterOptionsResponse.data.score_categories,
- tags: traceFilterOptionsResponse.data.tags?.map((t) => ({
- value: t.value,
- })),
- }
- : {};
-
- return {
- ...normalized,
- environment: environmentFilterOptionsResponse.data?.map((e) => ({
- value: e.environment,
- })),
- };
- }, [traceFilterOptionsResponse.data, environmentFilterOptionsResponse.data]);
-
- const datasets = api.datasets.allDatasetMeta.useQuery(
- {
- projectId: props.projectId,
- },
- {
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- staleTime: Infinity,
- },
- );
-
- const shouldFetch = !props.disabled && form.watch("target") === "trace";
- const { observationTypeToNames, traceWithObservations, isLoading } =
- useEvalConfigMappingData(props.projectId, form, traceId, shouldFetch);
-
- const datasetFilterOptions = useMemo(() => {
- if (!datasets.data) return undefined;
- return {
- datasetId: datasets.data?.map((d) => ({
- value: d.id,
- displayValue: d.name,
- })),
- };
- }, [datasets.data]);
-
- useEffect(() => {
- if (form.getValues("target") === "trace" && !props.disabled) {
- setShowPreview(true);
- } else if (form.getValues("target") === "dataset") {
- setShowPreview(false);
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [form.watch("target"), props.disabled]);
-
useEffect(() => {
if (props.evalTemplate && form.getValues("mapping").length === 0) {
+ const target = form.getValues("target");
form.setValue(
"mapping",
props.evalTemplate.vars.map((v) => ({
templateVariable: v,
+ langfuseObject: isLegacyEvalTarget(target)
+ ? ("trace" as const)
+ : undefined,
...inferDefaultMapping(v),
})),
);
@@ -333,11 +358,6 @@ export const InnerEvaluatorForm = (props: {
}
}, [form, props.evalTemplate]);
- const { fields } = useFieldArray({
- control: form.control,
- name: "mapping",
- });
-
const utils = api.useUtils();
const createJobMutation = api.evals.createJob.useMutation({
onSuccess: () => utils.models.invalidate(),
@@ -349,10 +369,11 @@ export const InnerEvaluatorForm = (props: {
});
const [availableVariables, setAvailableVariables] = useState<
typeof availableTraceEvalVariables | typeof availableDatasetEvalVariables
- >(
- isTraceTarget(props.existingEvaluator?.targetObject ?? "trace")
- ? availableTraceEvalVariables
- : availableDatasetEvalVariables,
+ >(() =>
+ targetState.getAvailableVariables(
+ props.existingEvaluator?.targetObject ??
+ (isBetaEnabled ? EvalTargetObject.EVENT : EvalTargetObject.TRACE),
+ ),
);
function onSubmit(values: z.infer<typeof evalConfigFormSchema>) {
@@ -397,14 +418,15 @@ export const InnerEvaluatorForm = (props: {
return;
}
- const validatedVarMapping = z
- .array(variableMapping)
- .safeParse(values.mapping);
+ const validatedVarMapping = validateAndTransformVariableMapping(
+ values.mapping,
+ values.target as EvalTargetObject,
+ );
- if (validatedVarMapping.success === false) {
+ if (!validatedVarMapping.success) {
form.setError("mapping", {
type: "manual",
- message: "Please fill out all variable mappings",
+ message: validatedVarMapping.error,
});
return;
}
@@ -442,10 +464,13 @@ export const InnerEvaluatorForm = (props: {
)
.then(() => {
props.onFormSuccess?.();
- form.reset();
if (props.mode !== "edit" && !props.preventRedirect) {
void router.push(`/project/${props.projectId}/evals`);
+ // Don't reset form when redirecting - it will unmount anyway
+ } else {
+ // Only reset form when NOT redirecting
+ form.reset();
}
})
.catch((error) => {
@@ -454,40 +479,60 @@ export const InnerEvaluatorForm = (props: {
return;
} else {
setFormError(JSON.stringify(error));
- console.error(error);
}
});
}
- const mappingControlButtons = (
- <div className="flex items-center gap-2">
- {form.watch("target") === "trace" && !props.disabled && (
- <>
- <span className="text-xs text-muted-foreground">Show Preview</span>
- <Switch
- checked={showPreview}
- onCheckedChange={setShowPreview}
- disabled={props.disabled}
- />
- {showPreview &&
- (traceWithObservations ? (
- <DetailPageNav
- currentId={traceWithObservations.id}
- listKey="traces"
- path={(entry) =>
- `/project/${props.projectId}/evals/new?evaluator=${props.evalTemplate.id}&traceId=${entry.id}`
- }
- />
- ) : (
- <div className="flex flex-row gap-1">
- <Skeleton className="h-8 w-[54px]" />
- <Skeleton className="h-8 w-[54px]" />
- </div>
- ))}
- </>
- )}
- </div>
- );
+ function handleAndResolveTarget(value: string) {
+ const newUserFacingTarget = value as
+ | "trace"
+ | "event"
+ | "offline-experiment";
+
+ if (newUserFacingTarget === userFacingTarget) {
+ return;
+ }
+
+ // Show dialog when clicking trace if user has no legacy evals
+ if (
+ newUserFacingTarget === "trace" &&
+ !props.evalCapabilities.hasLegacyEvals &&
+ props.mode !== "edit"
+ ) {
+ setShowTraceConfirmDialog(true);
+ return;
+ }
+
+ // Update user-facing target
+ setUserFacingTarget(newUserFacingTarget);
+
+ // Determine the actual target based on selection
+ let actualTarget: EvalTargetObject;
+ if (newUserFacingTarget === "trace") {
+ actualTarget = EvalTargetObject.TRACE;
+ } else if (newUserFacingTarget === "event") {
+ actualTarget = EvalTargetObject.EVENT;
+ } else {
+ // offline-experiment: only use EXPERIMENT if beta is enabled AND OTEL is selected
+ actualTarget =
+ isBetaEnabled && useOtelDataForExperiment
+ ? EvalTargetObject.EXPERIMENT
+ : EvalTargetObject.DATASET;
+ }
+
+ // Transform variable mapping for new target type
+ const currentMapping = form.getValues("mapping");
+ const newMapping = targetState.transformMapping(
+ currentMapping,
+ actualTarget,
+ );
+
+ // Update form state
+ form.setValue("filter", []);
+ form.setValue("mapping", newMapping);
+ setAvailableVariables(targetState.getAvailableVariables(actualTarget));
+ return actualTarget;
+ }
const formBody = (
<div className="grid gap-4">
@@ -506,186 +551,294 @@ export const InnerEvaluatorForm = (props: {
/>
{!props.hideTargetSection && (
<Card className="flex max-w-full flex-col gap-2 overflow-y-auto p-4">
- <span className="text-lg font-medium">Target</span>
<div className="flex flex-col gap-4">
- <FormField
- control={form.control}
- name="target"
- render={({ field }) => (
- <FormItem>
- <FormLabel>
- Target data{" "}
- {props.mode === "edit" && (
- <Tooltip>
- <TooltipTrigger>
- <InfoIcon className="size-3 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent className="max-w-[200px] p-2">
- <span className="leading-4">
- An evaluator&apos;s target data may only be
- configured at creation.
- </span>
- </TooltipContent>
- </Tooltip>
- )}
- </FormLabel>
- <FormControl>
- <Tabs
- defaultValue="trace"
- value={field.value}
- onValueChange={(value) => {
- const isTrace = isTraceTarget(value);
- const langfuseObject: LangfuseObject = isTrace
- ? "trace"
- : "dataset_item";
- const newMapping = form
- .getValues("mapping")
- .map((field) => ({
- ...field,
- langfuseObject,
- }));
- form.setValue("filter", []);
- form.setValue("mapping", newMapping);
- setAvailableVariables(
- isTrace
- ? availableTraceEvalVariables
- : availableDatasetEvalVariables,
- );
- field.onChange(value);
- }}
- >
- <TabsList>
- <TabsTrigger
- value="trace"
- disabled={props.disabled || props.mode === "edit"}
- >
- Live tracing data
- </TabsTrigger>
- <TabsTrigger
- value="dataset"
- disabled={props.disabled || props.mode === "edit"}
- >
- Dataset runs
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </FormControl>
- <FormMessage />
- </FormItem>
+ {!props.hideTargetSelection && (
+ <FormField
+ control={form.control}
+ name="target"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ Run on{" "}
+ {props.mode === "edit" && (
+ <Tooltip>
+ <TooltipTrigger>
+ <InfoIcon className="size-3 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[200px] p-2">
+ <span className="leading-4">
+ An evaluator&apos;s target data may only be
+ configured at creation.
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </FormLabel>
+ <FormControl>
+ <Tabs
+ value={userFacingTarget}
+ onValueChange={(value) => {
+ const actualTarget = handleAndResolveTarget(value);
+ field.onChange(actualTarget);
+ }}
+ >
+ <TabsList className="grid w-fit max-w-fit grid-flow-col">
+ {isBetaEnabled && (
+ <TabsTrigger
+ value="event"
+ disabled={props.disabled || props.mode === "edit"}
+ className="min-w-[100px]"
+ >
+ Live Observations [New]
+ </TabsTrigger>
+ )}
+ {allowLegacy && (
+ <TabsTrigger
+ value="trace"
+ disabled={props.disabled || props.mode === "edit"}
+ className="min-w-[100px]"
+ >
+ Live Traces {isBetaEnabled ? "[Legacy]" : ""}
+ </TabsTrigger>
+ )}
+ <TabsTrigger
+ value="offline-experiment"
+ disabled={props.disabled || props.mode === "edit"}
+ className="min-w-[100px]"
+ >
+ Offline Experiments
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {/* Second tab bar for experiment data source selection */}
+ {isBetaEnabled &&
+ !props.hideTargetSelection &&
+ userFacingTarget === "offline-experiment" &&
+ props.evalCapabilities.allowLegacy && (
+ <div className="flex flex-col gap-2">
+ <FormLabel className="text-sm">SDK Version</FormLabel>
+ <Tabs
+ value={useOtelDataForExperiment ? "otel" : "non-otel"}
+ onValueChange={(value) => {
+ // Don't allow changes in edit mode or disabled mode
+ if (props.mode === "edit" || props.disabled) {
+ return;
+ }
+
+ const useOtel = value === "otel";
+ setUseOtelDataForExperiment(useOtel);
+
+ // Update the actual form target: only use EXPERIMENT if beta is enabled
+ const actualTarget =
+ isBetaEnabled && useOtel
+ ? EvalTargetObject.EXPERIMENT
+ : EvalTargetObject.DATASET;
+ form.setValue("target", actualTarget);
+
+ // Transform variable mapping for new target type
+ const currentMapping = form.getValues("mapping");
+ const newMapping = targetState.transformMapping(
+ currentMapping,
+ actualTarget,
+ );
+
+ // Update form state
+ form.setValue("filter", []);
+ form.setValue("mapping", newMapping);
+ setAvailableVariables(
+ targetState.getAvailableVariables(actualTarget),
+ );
+ }}
+ >
+ <TabsList className="grid w-fit max-w-fit grid-cols-2">
+ <TabsTrigger
+ value="otel"
+ className="min-w-[150px]"
+ disabled={props.mode === "edit" || props.disabled}
+ >
+ {"JS SDK >= 4.4.0, Python SDK >= 3.9.0 [New]"}
+ </TabsTrigger>
+ <TabsTrigger
+ value="non-otel"
+ className="min-w-[150px]"
+ disabled={props.mode === "edit" || props.disabled}
+ >
+ {"JS SDK < 4.4.0, Python SDK < 3.9.0 [Legacy]"}
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ {!props.disabled && (
+ <FormDescription>
+ Check with your technical team to see which version of the
+ Langfuse SDK you are using.
+ </FormDescription>
+ )}
+ </div>
)}
- />
- <FormField
- control={form.control}
- name="timeScope"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>Evaluator runs on</FormLabel>
- <FormControl>
- <div className="flex flex-col gap-2">
- <div className="items-top flex space-x-2">
- <Checkbox
- id="newObjects"
- checked={field.value.includes("NEW")}
- onCheckedChange={(checked) => {
- const newValue = checked
- ? [...field.value, "NEW"]
- : field.value.filter((v) => v !== "NEW");
- field.onChange(newValue);
- }}
- disabled={props.disabled}
- />
- <div className="grid gap-1.5 leading-none">
- <label
- htmlFor="newObjects"
- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- >
- New{" "}
- {form.watch("target") === "trace"
- ? "traces"
- : "dataset run items"}
- </label>
- </div>
- </div>
- <div className="items-top flex space-x-2">
- <Checkbox
- id="existingObjects"
- checked={field.value.includes("EXISTING")}
- onCheckedChange={(checked) => {
- const newValue = checked
- ? [...field.value, "EXISTING"]
- : field.value.filter((v) => v !== "EXISTING");
- field.onChange(newValue);
- }}
- disabled={
- props.disabled ||
- (props.mode === "edit" &&
- field.value.includes("EXISTING"))
- }
- />
- <div className="flex items-center gap-1.5 leading-none">
- <label
- htmlFor="existingObjects"
- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- >
- Existing{" "}
- {form.watch("target") === "trace"
- ? "traces"
- : "dataset run items"}
- </label>
- {field.value.includes("EXISTING") &&
- !props.disabled &&
- (props.mode === "edit" ? (
- <Tooltip>
- <TooltipTrigger>
- <InfoIcon className="size-3 text-muted-foreground" />
- </TooltipTrigger>
- <TooltipContent className="max-w-[300px] p-2">
- <span className="leading-4">
- This evaluator has already run on existing{" "}
- {form.watch("target") === "trace"
- ? "traces"
- : "dataset run items"}{" "}
- once. Set up a new evaluator to re-run on
- existing{" "}
- {form.watch("target") === "trace"
- ? "traces"
- : "dataset run items"}
- .
- </span>
- </TooltipContent>
- </Tooltip>
- ) : (
- <ExecutionCountTooltip
- projectId={props.projectId}
- item={form.watch("target")}
- filter={form.watch("filter")}
- />
- ))}
+ {isBetaEnabled &&
+ !props.hideTargetSelection &&
+ props.mode !== "edit" &&
+ !props.disabled && (
+ <EvalVersionCallout
+ targetObject={form.watch("target")}
+ evalCapabilities={props.evalCapabilities}
+ />
+ )}
+
+ {!props.hideAdvancedSettings &&
+ isLegacyEvalTarget(form.watch("target")) && (
+ <FormField
+ control={form.control}
+ name="timeScope"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>Evaluate</FormLabel>
+ <FormControl>
+ <div className="flex flex-col gap-2">
+ <div className="items-top flex space-x-2">
+ <Checkbox
+ id="newObjects"
+ checked={field.value.includes("NEW")}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...field.value, "NEW"]
+ : field.value.filter((v) => v !== "NEW");
+ field.onChange(newValue);
+ }}
+ disabled={props.disabled}
+ />
+ <div className="grid gap-1.5 leading-none">
+ <label
+ htmlFor="newObjects"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ New {getTargetDisplayName(form.watch("target"))}
+ </label>
+ </div>
+ </div>
+ <div className="items-top flex space-x-2">
+ <Checkbox
+ id="existingObjects"
+ checked={field.value.includes("EXISTING")}
+ onCheckedChange={(checked) => {
+ const newValue = checked
+ ? [...field.value, "EXISTING"]
+ : field.value.filter((v) => v !== "EXISTING");
+ field.onChange(newValue);
+ }}
+ disabled={
+ props.disabled ||
+ (props.mode === "edit" &&
+ field.value.includes("EXISTING"))
+ }
+ />
+ <div className="flex items-center gap-1.5 leading-none">
+ <label
+ htmlFor="existingObjects"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Existing{" "}
+ {getTargetDisplayName(form.watch("target"))}
+ </label>
+ {field.value.includes("EXISTING") &&
+ !props.disabled &&
+ (props.mode === "edit" ? (
+ <Tooltip>
+ <TooltipTrigger>
+ <InfoIcon className="size-3 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[300px] p-2">
+ <span className="leading-4">
+ This evaluator has already run on
+ existing{" "}
+ {getTargetDisplayName(
+ form.watch("target"),
+ )}{" "}
+ once. Set up a new evaluator to re-run
+ on existing{" "}
+ {getTargetDisplayName(
+ form.watch("target"),
+ )}
+ .
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <ExecutionCountTooltip
+ projectId={props.projectId}
+ item={form.watch("target")}
+ filter={form.watch("filter")}
+ />
+ ))}
+ </div>
+ </div>
</div>
- </div>
- </div>
- </FormControl>
- <FormMessage />
- </FormItem>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
)}
- />
<FormField
control={form.control}
name="filter"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Target filter</FormLabel>
- {isTraceTarget(form.watch("target")) ? (
- <>
- <FormControl>
- <div className="max-w-[500px]">
+ render={({ field }) => {
+ const target = form.watch("target");
+
+ // Get appropriate columns based on target type
+ const getFilterColumns = () => {
+ if (isEventTarget(target)) {
+ // Event evaluators - use observation columns with propagation warnings
+ const baseColumns = observationEvalFilterColsWithOptions(
+ observationEvalFilterOptions,
+ );
+ return addPropagationWarnings(
+ baseColumns,
+ allowPropagationFilters,
+ );
+ } else if (isTraceTarget(target)) {
+ return tracesTableColsWithOptions(traceFilterOptions);
+ } else if (isExperimentTarget(target)) {
+ // Experiment evaluators - only dataset filter
+ return experimentEvalFilterColsWithOptions(
+ experimentEvalFilterOptions,
+ );
+ } else {
+ // dataset (legacy non-OTEL experiments)
+ return datasetFormFilterColsWithOptions(
+ datasetFilterOptions,
+ );
+ }
+ };
+
+ const hasFilters = field.value && field.value.length > 0;
+
+ return (
+ <FormItem>
+ <FormLabel>Where</FormLabel>
+ <FormControl>
+ <div className="max-w-[500px]">
+ {props.disabled && !hasFilters ? (
+ <p className="text-xs text-muted-foreground">
+ All {getTargetDisplayName(target)} will be evaluated
+ </p>
+ ) : (
<InlineFilterBuilder
- columns={tracesTableColsWithOptions(
- traceFilterOptions,
- evalTraceTableCols,
- )}
+ columnIdentifier={
+ isDatasetTarget(target) || isTraceTarget(target)
+ ? "name"
+ : "id"
+ }
+ columns={getFilterColumns()}
filterState={field.value ?? []}
onChange={(
value: z.infer<typeof singleFilter>[],
@@ -705,468 +858,114 @@ export const InnerEvaluatorForm = (props: {
}
}}
disabled={props.disabled}
- columnsWithCustomSelect={["tags"]}
+ columnsWithCustomSelect={
+ isEventTarget(target) || isTraceTarget(target)
+ ? ["tags"]
+ : undefined
+ }
/>
- </div>
- </FormControl>
- <FormMessage />
- </>
- ) : (
- <>
- <FormControl>
- <InlineFilterBuilder
- columns={datasetFormFilterColsWithOptions(
- datasetFilterOptions,
- evalDatasetFormFilterCols,
- )}
- filterState={field.value ?? []}
- onChange={field.onChange}
- disabled={props.disabled}
- />
- </FormControl>
- <FormMessage />
- </>
- )}
- </FormItem>
- )}
+ )}
+ </div>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ );
+ }}
/>
- {form.watch("target") === "trace" && !props.disabled && (
- <TracesPreview
- projectId={props.projectId}
- filterState={form.watch("filter") ?? []}
- />
- )}
+ {/* Preview based on target type */}
+ {!props.disabled && (
+ <>
+ {isTraceTarget(form.watch("target")) && (
+ <TracesPreview
+ projectId={props.projectId}
+ filterState={form.watch("filter") ?? []}
+ />
+ )}
- <FormField
- control={form.control}
- name="sampling"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Sampling</FormLabel>
- <FormControl>
- <div className="max-w-[500px]">
- <Slider
- disabled={props.disabled}
- min={0}
- max={1}
- step={0.0001}
- value={[field.value]}
- onValueChange={(value) => field.onChange(value[0])}
- showInput={true}
- displayAsPercentage={true}
- />
- </div>
- </FormControl>
- <div className="flex flex-col">
- <FormDescription className="mt-1 flex flex-row gap-1">
- <TimeScopeDescription
- projectId={props.projectId}
- timeScope={form.watch("timeScope")}
- target={
- form.watch("target") as "trace" | "dataset_item"
- }
- />
- </FormDescription>
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
+ {isEventTarget(form.watch("target")) && (
+ <ObservationsPreview
+ projectId={props.projectId}
+ filterState={form.watch("filter") ?? []}
+ />
+ )}
+ </>
+ )}
- <FormField
- control={form.control}
- name="delay"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Delay (seconds)</FormLabel>
- <FormControl>
- <Input {...field} type="number" min={0} />
- </FormControl>
- <FormDescription>
- Time between first Trace/Dataset run event and evaluation
- execution to ensure all data is available
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </Card>
- )}
- <Card className="min-w-0 max-w-full p-4">
- <div className="mb-2 flex items-center justify-between">
- <span className="text-lg font-medium">Variable mapping</span>
- </div>
- {form.watch("target") === "trace" && !props.disabled && (
- <FormDescription>
- Preview of the evaluation prompt with the variables replaced with
- the first matched trace data subject to the filters.
- </FormDescription>
- )}
- <div className="flex max-w-full flex-col gap-4">
- <FormField
- control={form.control}
- name="mapping"
- render={() => (
+ {!props.hideAdvancedSettings && (
<>
- <div
- className={cn(
- "my-2 flex max-w-full flex-col gap-2",
- !props.shouldWrapVariables && "lg:flex-row",
- )}
- >
- {showPreview ? (
- traceWithObservations ? (
- <EvaluationPromptPreview
- evalTemplate={props.evalTemplate}
- trace={traceWithObservations}
- variableMapping={form.watch("mapping")}
- isLoading={isLoading}
- className={cn(
- "min-h-48",
- !props.shouldWrapVariables && "lg:w-2/3",
- )}
- controlButtons={mappingControlButtons}
- />
- ) : (
- <div className="flex max-h-full min-h-48 w-full flex-col gap-1 lg:w-2/3">
- <div className="flex flex-row items-center justify-between py-0 text-sm font-medium capitalize">
- <div className="flex flex-row items-center gap-2">
- Evaluation Prompt Preview
- <Skeleton className="h-[25px] w-[63px]" />
- </div>
- <div className="flex justify-end">
- {mappingControlButtons}
- </div>
- </div>
- <div className="flex h-full w-full flex-1 items-center justify-center rounded border">
- <p className="text-center text-sm text-muted-foreground">
- No trace data found, please adjust filters or switch
- to not show preview.
- </p>
+ <FormField
+ control={form.control}
+ name="sampling"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Sampling</FormLabel>
+ <FormControl>
+ <div className="max-w-[500px]">
+ <Slider
+ disabled={props.disabled}
+ min={0}
+ max={1}
+ step={0.0001}
+ value={[field.value]}
+ onValueChange={(value) => field.onChange(value[0])}
+ showInput={true}
+ displayAsPercentage={true}
+ />
</div>
- </div>
- )
- ) : (
- <JSONView
- title={"Evaluation Prompt"}
- json={props.evalTemplate.prompt ?? null}
- className={cn(
- "min-h-48",
- !props.shouldWrapVariables && "lg:w-2/3",
- )}
- codeClassName="flex-1"
- collapseStringsAfterLength={null}
- controlButtons={mappingControlButtons}
- />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
)}
- <div
- className={cn(
- "flex flex-col gap-2",
- !props.shouldWrapVariables && "lg:w-1/3",
+ />
+ {isLegacyEvalTarget(form.watch("target")) && (
+ <FormField
+ control={form.control}
+ name="delay"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Delay (seconds)</FormLabel>
+ <FormControl>
+ <Input {...field} type="number" min={0} />
+ </FormControl>
+ <FormDescription>
+ Time between first Trace/Dataset run event and
+ evaluation execution to ensure all data is available
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
)}
- >
- {fields.map((mappingField, index) => (
- <Card className="flex flex-col gap-2 p-4" key={index}>
- <div
- className={cn(
- "text-sm font-semibold",
- getVariableColor(index),
- )}
- >
- {"{{"}
- {mappingField.templateVariable}
- {"}}"}
- <DocPopup
- description={
- "Variable in the template to be replaced with the mapped data."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- </div>
- <FormField
- control={form.control}
- key={`${mappingField.id}-langfuseObject`}
- name={`mapping.${index}.langfuseObject`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title="Object"
- description={
- "Langfuse object to retrieve the data from."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Select
- disabled={props.disabled}
- defaultValue={field.value}
- onValueChange={(value) => {
- field.onChange(value);
- form.setValue(
- `mapping.${index}.objectName`,
- undefined,
- );
- }}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {availableVariables.map((evalObject) => (
- <SelectItem
- value={evalObject.id}
- key={evalObject.id}
- >
- {evalObject.display}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
-
- {!isTraceOrDatasetObject(
- form.watch(`mapping.${index}.langfuseObject`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-objectName`}
- name={`mapping.${index}.objectName`}
- render={({ field }) => {
- const type = String(
- form.watch(`mapping.${index}.langfuseObject`),
- ).toUpperCase() as ObservationType;
- const nameOptions = Array.from(
- observationTypeToNames.get(type) ?? [],
- );
- const isCustomOption =
- field.value === "custom" ||
- (field.value &&
- !nameOptions.includes(field.value));
- return (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"Object Name"}
- description={
- "Name of the Langfuse object to retrieve the data from."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- {isCustomOption ? (
- <div className="flex flex-col gap-2">
- <Select
- onValueChange={(value) => {
- if (value !== "custom") {
- field.onChange(value);
- }
- }}
- value="custom"
- disabled={props.disabled}
- >
- <SelectTrigger>
- <SelectValue>
- Enter name...
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- {nameOptions?.map((name) => (
- <SelectItem
- key={name}
- value={name}
- >
- {name}
- </SelectItem>
- ))}
- <SelectItem
- key="custom"
- value="custom"
- >
- Enter name...
- </SelectItem>
- </SelectContent>
- </Select>
- <Input
- value={
- field.value === "custom"
- ? ""
- : field.value || ""
- }
- onChange={(e) =>
- field.onChange(e.target.value)
- }
- placeholder="Enter langfuse object name"
- disabled={props.disabled}
- />
- </div>
- ) : (
- <Select
- {...field}
- value={field.value ?? ""}
- onValueChange={field.onChange}
- disabled={props.disabled}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {nameOptions?.map((name) => (
- <SelectItem
- key={name}
- value={name}
- >
- {name}
- </SelectItem>
- ))}
- <SelectItem
- key="custom"
- value="custom"
- >
- Enter name...
- </SelectItem>
- </SelectContent>
- </Select>
- )}
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- );
- }}
- />
- ) : undefined}
-
- <FormField
- control={form.control}
- key={`${mappingField.id}-selectedColumnId`}
- name={`mapping.${index}.selectedColumnId`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"Object Variable"}
- description={
- "Variable on the Langfuse object to insert into the template."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Select
- disabled={props.disabled}
- defaultValue={field.value ?? undefined}
- onValueChange={(value) => {
- const availableColumns =
- availableVariables.find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )?.availableColumns;
-
- const column = availableColumns?.find(
- (column) => column.id === value,
- );
-
- field.onChange(column?.id);
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Object type" />
- </SelectTrigger>
- <SelectContent>
- {availableVariables
- .find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )
- ?.availableColumns.map((column) => (
- <SelectItem
- value={column.id}
- key={column.id}
- >
- {column.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- {fieldHasJsonSelectorOption(
- form.watch(`mapping.${index}.selectedColumnId`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-jsonSelector`}
- name={`mapping.${index}.jsonSelector`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"JsonPath"}
- description={
- "Optional selection: Use JsonPath syntax to select from a JSON object stored on a trace. If not selected, we will pass the entire object into the prompt."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Input
- {...field}
- value={field.value ?? ""}
- disabled={props.disabled}
- placeholder="Optional"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- ) : undefined}
- </Card>
- ))}
- </div>
- </div>
- <FormMessage />
+ />
+ )}
</>
)}
- />
- </div>
- </Card>
+ </div>
+ </Card>
+ )}
+ <VariableMappingCard
+ projectId={props.projectId}
+ availableVariables={availableVariables}
+ evalTemplate={props.evalTemplate}
+ form={form}
+ disabled={props.disabled}
+ shouldWrapVariables={props.shouldWrapVariables}
+ hideAdvancedSettings={props.hideAdvancedSettings}
+ oldConfigId={props.oldConfigId}
+ />
</div>
);
- const formFooter = (
+ const mutationIsLoading =
+ createJobMutation.isPending || updateJobMutation.isPending;
+
+ const formFooter = props.renderFooter ? (
+ props.renderFooter({ isLoading: mutationIsLoading, formError })
+ ) : (
<div className="flex w-full flex-col items-end gap-4">
{!props.disabled ? (
<Button
type="submit"
- loading={createJobMutation.isPending || updateJobMutation.isPending}
+ loading={mutationIsLoading}
className="mt-3 max-w-fit"
>
{props.mode === "edit" ? "Update" : "Execute"}
@@ -1181,27 +980,74 @@ export const InnerEvaluatorForm = (props: {
);
return (
- <Form {...form}>
- <form
- onSubmit={(e) => {
- e.stopPropagation(); // Prevent event bubbling to parent forms
- form.handleSubmit(onSubmit)(e);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" && e.target instanceof HTMLInputElement) {
- e.preventDefault();
- }
- }}
- className="flex w-full flex-col gap-4"
+ <>
+ <Form {...form}>
+ <form
+ onSubmit={(e) => {
+ e.stopPropagation(); // Prevent event bubbling to parent forms
+ form.handleSubmit(onSubmit)(e);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && e.target instanceof HTMLInputElement) {
+ e.preventDefault();
+ }
+ }}
+ className="flex w-full flex-col gap-4"
+ >
+ {props.useDialog ? <DialogBody>{formBody}</DialogBody> : formBody}
+
+ {formFooter &&
+ (props.useDialog ? (
+ <DialogFooter>{formFooter}</DialogFooter>
+ ) : (
+ <div className="mt-4 flex flex-row justify-end">{formFooter}</div>
+ ))}
+ </form>
+ </Form>
+
+ <Dialog
+ open={showTraceConfirmDialog}
+ onOpenChange={setShowTraceConfirmDialog}
>
- {props.useDialog ? <DialogBody>{formBody}</DialogBody> : formBody}
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>You selected a legacy evaluator</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="text-sm">
+ We strongly recommend using live observations evaluators. Trace
+ evaluators will be deprecated in the future. Only proceed if you are
+ sure you cannot upgrade your SDK version now.
+ </DialogBody>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => setShowTraceConfirmDialog(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={() => {
+ setShowTraceConfirmDialog(false);
+ setUserFacingTarget("trace");
- {props.useDialog ? (
- <DialogFooter>{formFooter}</DialogFooter>
- ) : (
- <div className="mt-4 flex flex-row justify-end">{formFooter}</div>
- )}
- </form>
- </Form>
+ // Update form and mapping
+ const actualTarget = "trace";
+ const langfuseObject: LangfuseObject = "trace";
+ const newMapping = form.getValues("mapping").map((field) => ({
+ ...field,
+ langfuseObject,
+ }));
+ form.setValue("filter", []);
+ form.setValue("mapping", newMapping);
+ setAvailableVariables(availableTraceEvalVariables);
+ form.setValue("target", actualTarget);
+ }}
+ >
+ Continue
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
};
diff --git a/web/src/features/evals/components/legacy-eval-callout.tsx b/web/src/features/evals/components/legacy-eval-callout.tsx
new file mode 100644
index 0000000000..15738a1b1f
--- /dev/null
+++ b/web/src/features/evals/components/legacy-eval-callout.tsx
@@ -0,0 +1,61 @@
+import { Callout } from "@/src/components/ui/callout";
+import { Button } from "@/src/components/ui/button";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { isLegacyEvalTarget } from "@/src/features/evals/utils/typeHelpers";
+
+interface LegacyEvalCalloutProps {
+ projectId: string;
+ evalConfigId: string;
+ targetObject: string;
+}
+
+export function LegacyEvalCallout({
+ projectId,
+ evalConfigId,
+ targetObject,
+}: LegacyEvalCalloutProps) {
+ const router = useRouter();
+ const isDeprecated = isLegacyEvalTarget(targetObject);
+
+ if (!isDeprecated) return null;
+
+ return (
+ <Callout
+ id={`eval-remapping-peek-${evalConfigId}`}
+ variant="info"
+ key="dismissed-eval-remapping-callouts"
+ actions={() => (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ router.push(
+ `/project/${projectId}/evals/remap?evaluator=${evalConfigId}`,
+ )
+ }
+ className="h-7 text-xs text-dark-blue hover:opacity-80"
+ >
+ Upgrade this evaluator
+ </Button>
+ </>
+ )}
+ >
+ <span>This evaluator </span>
+ <span className="text-dark-blue hover:opacity-80">
+ <Link
+ href="https://langfuse.com/faq/all/llm-as-a-judge-migration"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ requires changes{" "}
+ </Link>
+ </span>
+ <span>
+ to benefit from new features and performance improvements. Upgrade for
+ full compatibility.
+ </span>
+ </Callout>
+ );
+}
diff --git a/web/src/features/evals/components/variable-mapping-card.tsx b/web/src/features/evals/components/variable-mapping-card.tsx
new file mode 100644
index 0000000000..d3338dae13
--- /dev/null
+++ b/web/src/features/evals/components/variable-mapping-card.tsx
@@ -0,0 +1,647 @@
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import {
+ type availableDatasetEvalVariables,
+ type availableTraceEvalVariables,
+ type EvalTemplate,
+ observationEvalVariableColumns,
+} from "@langfuse/shared";
+import { Card } from "@/src/components/ui/card";
+import { JSONView } from "@/src/components/ui/CodeJsonViewer";
+import DocPopup from "@/src/components/layouts/doc-popup";
+import { cn } from "@/src/utils/tailwind";
+import {
+ type EvalFormType,
+ fieldHasJsonSelectorOption,
+} from "@/src/features/evals/utils/evaluator-form-utils";
+import { EvalTargetObject } from "@langfuse/shared";
+import { VariableMappingDescription } from "@/src/features/evals/components/eval-form-descriptions";
+import {
+ EvaluationPromptPreview,
+ getVariableColor,
+} from "@/src/features/evals/components/evaluation-prompt-preview";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import {
+ isEventTarget,
+ isLegacyEvalTarget,
+ isTraceTarget,
+ isTraceOrDatasetObject,
+ isTraceOrEventTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { useFieldArray, type UseFormReturn } from "react-hook-form";
+import { Input } from "@/src/components/ui/input";
+import { Switch } from "@/src/components/ui/switch";
+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { useEvalConfigMappingData } from "@/src/features/evals/hooks/useEvalConfigMappingData";
+import { useEffect, useState } from "react";
+
+export const VariableMappingCard = ({
+ projectId,
+ availableVariables,
+ evalTemplate,
+ form,
+ oldConfigId,
+ disabled = false,
+ shouldWrapVariables = false,
+ hideAdvancedSettings = false,
+}: {
+ projectId: string;
+ availableVariables:
+ | typeof availableTraceEvalVariables
+ | typeof availableDatasetEvalVariables;
+ evalTemplate: EvalTemplate;
+ form: UseFormReturn<EvalFormType>;
+ oldConfigId?: string;
+ disabled?: boolean;
+ shouldWrapVariables?: boolean;
+ hideAdvancedSettings?: boolean;
+}) => {
+ const [showPreview, setShowPreview] = useState(false);
+
+ const { fields } = useFieldArray({
+ control: form.control,
+ name: "mapping",
+ });
+
+ const { namesByObject, isLoading, previewData } = useEvalConfigMappingData(
+ projectId,
+ form,
+ disabled,
+ );
+
+ useEffect(() => {
+ if (isTraceOrEventTarget(form.getValues("target")) && !disabled) {
+ setShowPreview(true);
+ } else {
+ // For dataset and experiment targets, disable preview
+ setShowPreview(false);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [form.watch("target"), disabled]);
+
+ const mappingControlButtons = (
+ <div className="flex items-center gap-2">
+ {isTraceOrEventTarget(form.watch("target")) && !disabled && (
+ <>
+ <span className="text-xs text-muted-foreground">Preview</span>
+ <Switch
+ checked={showPreview}
+ onCheckedChange={setShowPreview}
+ disabled={disabled}
+ />
+ {showPreview &&
+ (previewData ? (
+ <DetailPageNav
+ currentId={
+ previewData.type === EvalTargetObject.EVENT
+ ? previewData.observationId
+ : previewData.traceId
+ }
+ listKey={
+ isEventTarget(form.watch("target"))
+ ? "observations"
+ : "traces"
+ }
+ path={(entry) => {
+ const isEvent = isEventTarget(form.watch("target"));
+ const basePath = hideAdvancedSettings
+ ? `/project/${projectId}/evals/remap?evaluator=${oldConfigId}`
+ : `/project/${projectId}/evals/new?evaluator=${evalTemplate.id}`;
+ if (isEvent) {
+ // For observations/events: entry.id is observationId, entry.params.traceId is traceId
+ return `${basePath}&traceId=${entry.params?.traceId}&observationId=${entry.id}`;
+ } else {
+ // For traces: entry.id is traceId
+ return `${basePath}&traceId=${entry.id}`;
+ }
+ }}
+ />
+ ) : (
+ <div className="flex flex-row gap-1">
+ <Skeleton className="h-8 w-[54px]" />
+ <Skeleton className="h-8 w-[54px]" />
+ </div>
+ ))}
+ </>
+ )}
+ </div>
+ );
+
+ return (
+ <Card className="min-w-0 max-w-full p-4">
+ <div className="mb-2 flex items-center justify-between">
+ <span className="text-lg font-medium">Variable mapping</span>
+ </div>
+ {isTraceTarget(form.watch("target")) && !disabled && (
+ <FormDescription>
+ Preview of the evaluation prompt with the variables replaced with the
+ first matched trace data subject to the filters.
+ </FormDescription>
+ )}
+ <div className="flex max-w-full flex-col gap-4">
+ <FormField
+ control={form.control}
+ name="mapping"
+ render={() => (
+ <>
+ <div
+ className={cn(
+ "my-2 flex max-w-full flex-col gap-2",
+ !shouldWrapVariables && "lg:flex-row",
+ )}
+ >
+ {showPreview ? (
+ previewData ? (
+ <EvaluationPromptPreview
+ projectId={projectId}
+ previewData={previewData}
+ evalTemplate={evalTemplate}
+ variableMapping={form.watch("mapping")}
+ isLoading={isLoading}
+ className={cn(
+ "min-h-48 bg-muted/50",
+ !shouldWrapVariables && "lg:w-2/3",
+ )}
+ controlButtons={mappingControlButtons}
+ />
+ ) : (
+ <div className="flex max-h-full min-h-48 w-full flex-col gap-1 bg-muted/50 lg:w-2/3">
+ <div className="flex flex-row items-center justify-between py-0 text-sm font-medium capitalize">
+ <div className="flex flex-row items-center gap-2">
+ Evaluation Prompt Preview
+ <Skeleton className="h-[25px] w-[63px]" />
+ </div>
+ <div className="flex justify-end">
+ {mappingControlButtons}
+ </div>
+ </div>
+ <div className="flex h-full w-full flex-1 items-center justify-center rounded border">
+ <p className="text-center text-sm text-muted-foreground">
+ No trace data found, please adjust filters or switch
+ to not show preview.
+ </p>
+ </div>
+ </div>
+ )
+ ) : (
+ <JSONView
+ title={"Evaluation Prompt"}
+ json={evalTemplate.prompt ?? null}
+ className={cn(
+ "min-h-48 bg-muted/50",
+ !shouldWrapVariables && "lg:w-2/3",
+ )}
+ codeClassName="flex-1"
+ collapseStringsAfterLength={null}
+ controlButtons={mappingControlButtons}
+ />
+ )}
+ <div
+ className={cn(
+ "flex flex-col gap-2",
+ !shouldWrapVariables && "lg:w-1/3",
+ )}
+ >
+ {isLegacyEvalTarget(form.watch("target")) // Complex variable mapping for trace/dataset targets (legacy)
+ ? fields.map((mappingField, index) => (
+ <Card className="flex flex-col gap-2 p-4" key={index}>
+ <div
+ className={cn(
+ "text-sm font-semibold",
+ getVariableColor(index),
+ )}
+ >
+ {"{{"}
+ {mappingField.templateVariable}
+ {"}}"}
+ <DocPopup
+ description={
+ "Variable in the template to be replaced with the mapped data."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ </div>
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-langfuseObject`}
+ name={`mapping.${index}.langfuseObject`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title="Object"
+ description={
+ "Langfuse object to retrieve the data from."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={disabled}
+ defaultValue={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ form.setValue(
+ `mapping.${index}.objectName`,
+ undefined,
+ );
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {availableVariables.map(
+ (evalObject) => (
+ <SelectItem
+ value={evalObject.id}
+ key={evalObject.id}
+ >
+ {evalObject.display}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+
+ {!isTraceOrDatasetObject(
+ form.watch(`mapping.${index}.langfuseObject`) ?? "",
+ ) ? (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-objectName`}
+ name={`mapping.${index}.objectName`}
+ render={({ field }) => {
+ const type = String(
+ form.watch(`mapping.${index}.langfuseObject`),
+ ).toUpperCase();
+ const nameOptions = Array.from(
+ namesByObject.get(type) ?? [],
+ );
+ const isCustomOption =
+ field.value === "custom" ||
+ (field.value &&
+ !nameOptions.includes(field.value));
+ return (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"Object Name"}
+ description={
+ "Name of the Langfuse object to retrieve the data from."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ {isCustomOption ? (
+ <div className="flex flex-col gap-2">
+ <Select
+ onValueChange={(value) => {
+ if (value !== "custom") {
+ field.onChange(value);
+ }
+ }}
+ value="custom"
+ disabled={disabled}
+ >
+ <SelectTrigger>
+ <SelectValue>
+ Enter name...
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {nameOptions?.map((name) => (
+ <SelectItem
+ key={name}
+ value={name}
+ >
+ {name}
+ </SelectItem>
+ ))}
+ <SelectItem
+ key="custom"
+ value="custom"
+ >
+ Enter name...
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ <Input
+ value={
+ field.value === "custom"
+ ? ""
+ : field.value || ""
+ }
+ onChange={(e) =>
+ field.onChange(e.target.value)
+ }
+ placeholder="Enter langfuse object name"
+ disabled={disabled}
+ />
+ </div>
+ ) : (
+ <Select
+ {...field}
+ value={field.value ?? ""}
+ onValueChange={field.onChange}
+ disabled={disabled}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {nameOptions?.map((name) => (
+ <SelectItem
+ key={name}
+ value={name}
+ >
+ {name}
+ </SelectItem>
+ ))}
+ <SelectItem
+ key="custom"
+ value="custom"
+ >
+ Enter name...
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ );
+ }}
+ />
+ ) : undefined}
+
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-selectedColumnId`}
+ name={`mapping.${index}.selectedColumnId`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"Object Field"}
+ description={
+ "Field on the Langfuse object to insert into the template."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={disabled}
+ defaultValue={field.value ?? undefined}
+ onValueChange={(value) => {
+ const availableColumns =
+ availableVariables.find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )?.availableColumns;
+
+ const column = availableColumns?.find(
+ (column) => column.id === value,
+ );
+
+ field.onChange(column?.id);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Object type" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableVariables
+ .find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )
+ ?.availableColumns.map((column) => (
+ <SelectItem
+ value={column.id}
+ key={column.id}
+ >
+ {column.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+ {fieldHasJsonSelectorOption(
+ form.watch(`mapping.${index}.selectedColumnId`),
+ ) ? (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-jsonSelector`}
+ name={`mapping.${index}.jsonSelector`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"JsonPath"}
+ description={
+ "Optional selection: Use JsonPath syntax to select from a JSON object stored on a trace. If not selected, we will pass the entire object into the prompt."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ disabled={disabled}
+ placeholder="Optional"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+ ) : undefined}
+ </Card>
+ ))
+ : // Simplified variable mapping for event/experiment targets
+ fields.map((mappingField, index) => (
+ <Card className="flex flex-col gap-2 p-4" key={index}>
+ <div
+ className={cn(
+ "text-sm font-semibold",
+ getVariableColor(index),
+ )}
+ >
+ {"{{"}
+ {mappingField.templateVariable}
+ {"}}"}
+ <DocPopup
+ description={
+ "Variable in the template to be replaced with the mapped data."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ </div>
+ {hideAdvancedSettings && (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title="Object"
+ description="Type of object to retrieve the data from."
+ href="https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ />
+ <div className="w-2/3">
+ <Input
+ value={
+ isEventTarget(form.watch("target"))
+ ? "Observation"
+ : "Experiment item"
+ }
+ disabled
+ />
+ </div>
+ </div>
+ )}
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-selectedColumnId`}
+ name={`mapping.${index}.selectedColumnId`}
+ render={({ field }) => {
+ // Filter columns based on target
+ // For observations (event), exclude experiment-specific fields
+ const availableColumns =
+ form.watch("target") === EvalTargetObject.EVENT
+ ? observationEvalVariableColumns.filter(
+ (col) =>
+ col.id !==
+ "experimentItemExpectedOutput",
+ )
+ : observationEvalVariableColumns;
+
+ return (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"Object Field"}
+ description={
+ "Observation field to insert into the template."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={disabled}
+ defaultValue={field.value ?? undefined}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select field" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableColumns.map((column) => (
+ <SelectItem
+ value={column.id}
+ key={column.id}
+ >
+ {column.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ );
+ }}
+ />
+ {(form.watch(`mapping.${index}.selectedColumnId`) ===
+ "metadata" ||
+ form.watch(`mapping.${index}.selectedColumnId`) ===
+ "input" ||
+ form.watch(`mapping.${index}.selectedColumnId`) ===
+ "output" ||
+ form.watch(`mapping.${index}.selectedColumnId`) ===
+ "experimentItemExpectedOutput") && (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-jsonSelector`}
+ name={`mapping.${index}.jsonSelector`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"JsonPath"}
+ description={
+ "Optional selection: Use JsonPath syntax to select from a JSON object. If not selected, we will pass the entire object into the prompt."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ disabled={disabled}
+ placeholder="Optional"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+ )}
+ </Card>
+ ))}
+ </div>
+ </div>
+ <FormMessage />
+ </>
+ )}
+ />
+ </div>
+ </Card>
+ );
+};
diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.ts
new file mode 100644
index 0000000000..11d48d475c
--- /dev/null
+++ b/web/src/features/evals/hooks/useEvalCapabilities.ts
@@ -0,0 +1,37 @@
+import { api } from "@/src/utils/api";
+export interface EvalCapabilities {
+ isNewCompatible: boolean;
+ allowLegacy: boolean;
+ allowPropagationFilters: boolean;
+ isLoading: boolean;
+ hasLegacyEvals: boolean;
+}
+
+const mockOtelStatus = {
+ isOtel: false,
+ isPropagating: false,
+};
+
+/**
+ * Hook to determine which eval configuration features are available
+ * @param projectId - The project ID to check
+ * @returns Capabilities object indicating which eval features are allowed
+ */
+export function useEvalCapabilities(projectId: string): EvalCapabilities {
+ // Query OTEL SDK status
+ const { isOtel, isPropagating } = mockOtelStatus;
+
+ // Get eval counts including legacy eval count
+ const evalCounts = api.evals.counts.useQuery({ projectId });
+ const hasLegacyEvals = (evalCounts.data?.legacyConfigCount ?? 0) > 0;
+
+ return {
+ isNewCompatible: isOtel,
+ // Allow legacy evals if user already has them OR if not using OTEL
+ allowLegacy: hasLegacyEvals || !isOtel,
+ // Allow propagation filters only when using OTEL and spans are propagating
+ allowPropagationFilters: isOtel && isPropagating,
+ isLoading: evalCounts.isLoading,
+ hasLegacyEvals,
+ };
+}
diff --git a/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts b/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts
new file mode 100644
index 0000000000..b6247da172
--- /dev/null
+++ b/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts
@@ -0,0 +1,127 @@
+import { api } from "@/src/utils/api";
+import {
+ type ExperimentEvalOptions,
+ type ObservationEvalOptions,
+} from "@langfuse/shared";
+import { useMemo } from "react";
+
+export function useEvalConfigFilterOptions({
+ projectId,
+}: {
+ projectId: string;
+}) {
+ const traceFilterOptionsResponse = api.traces.filterOptions.useQuery(
+ { projectId },
+ {
+ trpc: { context: { skipBatch: true } },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const environmentFilterOptionsResponse =
+ api.projects.environmentFilterOptions.useQuery(
+ {
+ projectId,
+ },
+ {
+ trpc: { context: { skipBatch: true } },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const observationsFilterOptionsResponse =
+ api.generations.filterOptions.useQuery({
+ projectId,
+ });
+
+ const traceFilterOptions = useMemo(() => {
+ // Normalize API response to match TraceOptions type (count should be number, not string)
+ const normalized = traceFilterOptionsResponse.data
+ ? {
+ name: traceFilterOptionsResponse.data.name?.map((n) => ({
+ value: n.value,
+ count: Number(n.count),
+ })),
+ scores_avg: traceFilterOptionsResponse.data.scores_avg,
+ score_categories: traceFilterOptionsResponse.data.score_categories,
+ tags: traceFilterOptionsResponse.data.tags?.map((t) => ({
+ value: t.value,
+ })),
+ }
+ : {};
+
+ return {
+ ...normalized,
+ environment: environmentFilterOptionsResponse.data?.map((e) => ({
+ value: e.environment,
+ })),
+ };
+ }, [traceFilterOptionsResponse.data, environmentFilterOptionsResponse.data]);
+
+ const datasets = api.datasets.allDatasetMeta.useQuery(
+ {
+ projectId,
+ },
+ {
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ );
+
+ const datasetFilterOptions = useMemo(() => {
+ if (!datasets.data) return undefined;
+ return {
+ datasetId: datasets.data?.map((d) => ({
+ value: d.id,
+ displayValue: d.name,
+ })),
+ };
+ }, [datasets.data]);
+
+ const observationEvalFilterOptions: ObservationEvalOptions = useMemo(() => {
+ return {
+ environment: environmentFilterOptionsResponse.data?.map((e) => ({
+ value: e.environment,
+ })),
+ tags: traceFilterOptionsResponse.data?.tags?.map((t) => ({
+ value: t.value,
+ })),
+ traceName: traceFilterOptionsResponse.data?.name?.map((n) => ({
+ value: n.value,
+ })),
+ name: observationsFilterOptionsResponse.data?.name?.map((n) => ({
+ value: n.value,
+ })),
+ };
+ }, [
+ traceFilterOptionsResponse.data,
+ environmentFilterOptionsResponse.data,
+ observationsFilterOptionsResponse.data,
+ ]);
+
+ const experimentEvalFilterOptions: ExperimentEvalOptions = useMemo(() => {
+ return {
+ experimentDatasetId: datasetFilterOptions?.datasetId,
+ };
+ }, [datasetFilterOptions]);
+
+ return {
+ traceFilterOptions,
+ datasetFilterOptions,
+ observationEvalFilterOptions,
+ experimentEvalFilterOptions,
+ };
+}
diff --git a/web/src/features/evals/hooks/useEvalConfigMappingData.ts b/web/src/features/evals/hooks/useEvalConfigMappingData.ts
index e11166f436..6607942bf6 100644
--- a/web/src/features/evals/hooks/useEvalConfigMappingData.ts
+++ b/web/src/features/evals/hooks/useEvalConfigMappingData.ts
@@ -1,57 +1,85 @@
import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";
-import { api } from "@/src/utils/api";
-import { type ObservationType } from "@langfuse/shared";
+import { EvalTargetObject, type ObservationType } from "@langfuse/shared";
import { type UseFormReturn } from "react-hook-form";
+import { useRouter } from "next/router";
+import {
+ type PreviewData,
+ usePreviewData,
+} from "@/src/features/evals/hooks/usePreviewData";
+import { useEffect, useRef } from "react";
+
+type EvalConfigMappingData = {
+ namesByObject: Map<string, Set<string>>;
+ isLoading: boolean;
+ previewData: PreviewData | null;
+};
export function useEvalConfigMappingData(
projectId: string,
form: UseFormReturn<EvalFormType>,
- traceId?: string,
- shouldFetch = true,
-) {
- const latestTrace = api.traces.all.useQuery(
- {
- projectId,
- filter: form.watch("filter"),
- searchQuery: "",
- searchType: [],
- limit: 1,
- page: 0,
- orderBy: { column: "timestamp", order: "DESC" },
- },
- {
- enabled: !traceId && shouldFetch,
- },
+ disabled = false,
+): EvalConfigMappingData {
+ const router = useRouter();
+
+ // Get traceId and observationId from URL query parameters
+ const traceId =
+ typeof router.query.traceId === "string" ? router.query.traceId : undefined;
+ const observationId =
+ typeof router.query.observationId === "string"
+ ? router.query.observationId
+ : undefined;
+
+ const { previewData, isLoading } = usePreviewData(
+ projectId,
+ form,
+ !disabled,
+ traceId,
+ observationId,
);
- const relevantTraceId = traceId ?? latestTrace.data?.traces[0]?.id;
+ const targetValue = form.watch("target");
+ const prevTargetRef = useRef(targetValue);
- // TODO: figure out timestamp logic here
- const traceWithObservations =
- api.traces.byIdWithObservationsAndScores.useQuery(
- {
- projectId,
- traceId: relevantTraceId as string,
- },
- {
- enabled: !!relevantTraceId && shouldFetch,
- },
- );
+ // drop the traceId and observation-related params from the URL query parameters when target changes
+ useEffect(() => {
+ if (
+ prevTargetRef.current !== targetValue &&
+ prevTargetRef.current !== undefined
+ ) {
+ // Remove navigation-related params when target changes
+ const { traceId, observationId, ...restQuery } = router.query;
+
+ // Use replace to avoid adding to browser history
+ void router.replace(
+ {
+ pathname: router.pathname,
+ query: restQuery,
+ },
+ undefined,
+ { shallow: true },
+ );
+ }
+ prevTargetRef.current = targetValue;
+ }, [targetValue, router]);
const observationTypeToNames = new Map<ObservationType, Set<string>>([
["SPAN", new Set()],
["EVENT", new Set()],
["GENERATION", new Set()],
]);
- traceWithObservations.data?.observations.forEach((observation) => {
- if (observation.type && observation.name) {
- observationTypeToNames.get(observation.type)?.add(observation.name);
- }
- });
+
+ // Only populate observation names for trace evals (where observations are available)
+ if (previewData?.type === EvalTargetObject.TRACE) {
+ previewData?.data?.observations.forEach((observation) => {
+ if (observation.type && observation.name) {
+ observationTypeToNames.get(observation.type)?.add(observation.name);
+ }
+ });
+ }
return {
- observationTypeToNames,
- traceWithObservations: traceWithObservations.data,
- isLoading: traceWithObservations.isLoading,
+ namesByObject: new Map<string, Set<string>>(),
+ isLoading,
+ previewData,
};
}
diff --git a/web/src/features/evals/hooks/useEvalTargetCount.ts b/web/src/features/evals/hooks/useEvalTargetCount.ts
index ac53b60779..2ede9f6e88 100644
--- a/web/src/features/evals/hooks/useEvalTargetCount.ts
+++ b/web/src/features/evals/hooks/useEvalTargetCount.ts
@@ -1,8 +1,6 @@
import { api } from "@/src/utils/api";
-import {
- type EvalFormType,
- isTraceTarget,
-} from "@/src/features/evals/utils/evaluator-form-utils";
+import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";
+import { isTraceTarget } from "@/src/features/evals/utils/typeHelpers";
interface UseEvalTargetCountProps {
projectId: string;
diff --git a/web/src/features/evals/hooks/useEvaluatorTarget.ts b/web/src/features/evals/hooks/useEvaluatorTarget.ts
new file mode 100644
index 0000000000..74d0498518
--- /dev/null
+++ b/web/src/features/evals/hooks/useEvaluatorTarget.ts
@@ -0,0 +1,107 @@
+import { useState, useEffect } from "react";
+import {
+ EvalTargetObject,
+ availableTraceEvalVariables,
+ availableDatasetEvalVariables,
+} from "@langfuse/shared";
+import {
+ isTraceTarget,
+ isEventTarget,
+ isExperimentTarget,
+ isLegacyEvalTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+import {
+ type VariableMapping,
+ type LangfuseObject,
+} from "../utils/evaluator-form-utils";
+import { OBSERVATION_VARIABLES } from "../utils/evaluator-constants";
+import { useObservationEvals } from "@/src/features/events/hooks/useObservationEvals";
+
+/**
+ * Custom hook to manage user-facing target state.
+ * Maps internal target objects to UI tabs (trace/event/offline-experiment).
+ */
+export const useUserFacingTarget = (targetObject?: string) => {
+ const isBetaEnabled = useObservationEvals();
+ const [userFacingTarget, setUserFacingTarget] = useState<
+ "trace" | "event" | "offline-experiment"
+ >("event");
+ const [useOtelDataForExperiment, setUseOtelDataForExperiment] =
+ useState(true);
+
+ useEffect(() => {
+ const currentTarget =
+ targetObject ??
+ (isBetaEnabled ? EvalTargetObject.EVENT : EvalTargetObject.TRACE);
+
+ if (isTraceTarget(currentTarget)) {
+ setUserFacingTarget("trace");
+ } else if (isEventTarget(currentTarget)) {
+ setUserFacingTarget("event");
+ } else if (isExperimentTarget(currentTarget)) {
+ setUserFacingTarget("offline-experiment");
+ setUseOtelDataForExperiment(true);
+ } else if (isLegacyEvalTarget(currentTarget)) {
+ // DATASET target (legacy non-OTEL experiments)
+ setUserFacingTarget("offline-experiment");
+ setUseOtelDataForExperiment(false);
+ }
+ }, [targetObject, isBetaEnabled]);
+
+ return {
+ userFacingTarget,
+ setUserFacingTarget,
+ useOtelDataForExperiment,
+ setUseOtelDataForExperiment,
+ };
+};
+
+/**
+ * Custom hook to manage evaluator target-dependent state.
+ * Handles available variables and variable mapping transformations.
+ */
+export const useEvaluatorTargetState = () => {
+ const getAvailableVariables = (targetObject: string) => {
+ if (isEventTarget(targetObject) || isExperimentTarget(targetObject)) {
+ return OBSERVATION_VARIABLES;
+ }
+ return isTraceTarget(targetObject)
+ ? availableTraceEvalVariables
+ : availableDatasetEvalVariables;
+ };
+
+ const transformMapping = (
+ currentMapping: VariableMapping[],
+ targetObject: string,
+ ): VariableMapping[] => {
+ const isObservationBased =
+ isEventTarget(targetObject) || isExperimentTarget(targetObject);
+
+ return currentMapping.map((field) => {
+ if (isObservationBased) {
+ // Placeholder langfuseObject (stripped in onSubmit)
+ return {
+ templateVariable: field.templateVariable,
+ selectedColumnId: field.selectedColumnId,
+ jsonSelector: field.jsonSelector,
+ langfuseObject: "event" as LangfuseObject,
+ objectName: null,
+ };
+ }
+
+ // Proper langfuseObject for trace/dataset
+ return {
+ ...field,
+ langfuseObject: (isTraceTarget(targetObject)
+ ? "trace"
+ : "dataset_item") as LangfuseObject,
+ objectName: field.objectName ?? null,
+ };
+ });
+ };
+
+ return {
+ getAvailableVariables,
+ transformMapping,
+ };
+};
diff --git a/web/src/features/evals/hooks/useExtractVariables.ts b/web/src/features/evals/hooks/useExtractVariables.ts
index e3c1e12062..ef5be7ecbd 100644
--- a/web/src/features/evals/hooks/useExtractVariables.ts
+++ b/web/src/features/evals/hooks/useExtractVariables.ts
@@ -1,13 +1,15 @@
+import { type PreviewData } from "@/src/features/evals/hooks/usePreviewData";
import { type VariableMapping } from "@/src/features/evals/utils/evaluator-form-utils";
+import { useObservationEvals } from "@/src/features/events/hooks/useObservationEvals";
import { api } from "@/src/utils/api";
import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
-import { extractValueFromObject } from "@langfuse/shared";
+import { EvalTargetObject, extractValueFromObject } from "@langfuse/shared";
import { useEffect, useState, useRef } from "react";
/**
* Helper function to find an observation by name in the trace data
*/
-function getObservation(
+function getObservationByName(
objectName: string | null | undefined,
observations: Record<string, unknown>[] | undefined,
): Record<string, unknown> | null {
@@ -25,17 +27,16 @@ type ExtractedVariable = {
export function useExtractVariables({
variables,
variableMapping,
- trace,
+ previewData,
isLoading,
}: {
variables: string[];
variableMapping: VariableMapping[];
- trace?: Record<string, unknown> & {
- observations?: Record<string, unknown>[];
- };
+ previewData: PreviewData;
isLoading: boolean;
}) {
const utils = api.useUtils();
+ const isBetaEnabled = useObservationEvals();
const [extractedVariables, setExtractedVariables] = useState<
ExtractedVariable[]
>([]);
@@ -47,9 +48,11 @@ export function useExtractVariables({
const currentMappingString =
variables.length > 0 ? JSON.stringify(variableMapping) : "";
- // Create a stable reference to the trace ID
- const traceId = trace?.id;
- const traceIdRef = useRef<string | undefined>(traceId as string | undefined);
+ const id =
+ previewData.type === EvalTargetObject.EVENT
+ ? previewData.observationId
+ : previewData.traceId;
+ const idRef = useRef<string | undefined>(id);
// Handle error toasts separately to avoid repeated toasts on re-renders
useEffect(() => {
@@ -72,14 +75,14 @@ export function useExtractVariables({
}
// Check if the variableMapping has changed by comparing string representations
- // OR if the trace ID has changed
+ // OR if the target ID has changed
const mappingChanged = previousMappingRef.current !== currentMappingString;
- const traceChanged = traceIdRef.current !== traceId;
- const shouldExtract = mappingChanged || traceChanged;
+ const idChanged = idRef.current !== id;
+ const shouldExtract = mappingChanged || idChanged;
- // Update the trace ID reference
- if (traceChanged) {
- traceIdRef.current = traceId as string | undefined;
+ // Update the id reference
+ if (idChanged) {
+ idRef.current = id;
}
// Exit if we don't need to extract
@@ -87,8 +90,8 @@ export function useExtractVariables({
return;
}
- // Clear existing variables immediately when trace changes to avoid showing stale data
- if (traceChanged) {
+ // Clear existing variables immediately when id changes to avoid showing stale data
+ if (idChanged) {
setExtractedVariables(
variables.map((variable) => ({ variable, value: "n/a" })),
);
@@ -104,32 +107,44 @@ export function useExtractVariables({
(m) => m.templateVariable === variable,
);
- if (!mapping || !mapping.selectedColumnId) {
+ if (
+ !mapping ||
+ !mapping.selectedColumnId ||
+ (!mapping.langfuseObject &&
+ !(isBetaEnabled && previewData.type === "event"))
+ ) {
return { variable, value: "n/a" };
}
let object;
- if (mapping.langfuseObject === "trace") {
- object = trace;
- } else if (mapping.objectName) {
- // For observations, find them in the pre-loaded trace data
- const observation = getObservation(
- mapping.objectName,
- trace?.observations,
- );
- if (observation?.id) {
- try {
- const observationWithInputAndOutput =
- await utils.observations.byId.fetch({
- observationId: observation.id as string,
- startTime: observation.startTime as Date | null,
- traceId: trace?.id as string,
- projectId: trace?.projectId as string,
- });
- object = observationWithInputAndOutput;
- } catch (error) {
- console.error(`Error fetching observation data:`, error);
+ if (previewData.type === "event") {
+ object = previewData.data; // Already has input/output
+ } else {
+ // Trace eval: can map to trace or observation fields
+ if (mapping.langfuseObject === "trace") {
+ object = previewData.data;
+ } else if (mapping.langfuseObject !== "dataset_item") {
+ // Find observation by name from mapping
+ const observation = getObservationByName(
+ mapping.objectName,
+ previewData.data.observations as Record<string, unknown>[],
+ );
+
+ if (observation?.id) {
+ try {
+ // Fetch observation to get input/output
+ const observationWithInputAndOutput =
+ await utils.observations.byId.fetch({
+ observationId: observation.id as string,
+ startTime: observation.startTime as Date | null,
+ traceId: previewData.data.id as string,
+ projectId: previewData.data.projectId as string,
+ });
+ object = observationWithInputAndOutput;
+ } catch (error) {
+ console.error(`Error fetching observation data:`, error);
+ }
}
}
}
@@ -138,10 +153,11 @@ export function useExtractVariables({
return { variable, value: "n/a" };
}
- const { value, error } = extractValueFromObject(object, {
- ...mapping,
- selectedColumnId: mapping.selectedColumnId,
- });
+ const { value, error } = extractValueFromObject(
+ object,
+ mapping.selectedColumnId,
+ mapping.jsonSelector ?? undefined,
+ );
return { variable, value, error };
});
@@ -177,9 +193,10 @@ export function useExtractVariables({
variableMapping,
currentMappingString,
isLoading,
- traceId,
+ id,
utils.observations.byId,
- trace,
+ previewData,
+ isBetaEnabled,
]);
return { extractedVariables, isExtracting };
diff --git a/web/src/features/evals/hooks/usePreviewData.ts b/web/src/features/evals/hooks/usePreviewData.ts
new file mode 100644
index 0000000000..4d5cb11a53
--- /dev/null
+++ b/web/src/features/evals/hooks/usePreviewData.ts
@@ -0,0 +1,154 @@
+import { type EvalFormType } from "@/src/features/evals/utils/evaluator-form-utils";
+import { api, type RouterOutputs } from "@/src/utils/api";
+import { EvalTargetObject } from "@langfuse/shared";
+import { type UseFormReturn } from "react-hook-form";
+import { isEventTarget } from "@/src/features/evals/utils/typeHelpers";
+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
+
+export type PreviewData =
+ | {
+ type: typeof EvalTargetObject.TRACE;
+ traceId: string;
+ data: RouterOutputs["traces"]["byIdWithObservationsAndScores"];
+ }
+ | {
+ type: typeof EvalTargetObject.EVENT;
+ traceId: string;
+ observationId: string;
+ data: RouterOutputs["observations"]["byId"];
+ };
+
+export function usePreviewData(
+ projectId: string,
+ form: UseFormReturn<EvalFormType>,
+ enabled: boolean,
+ traceId: string | undefined,
+ observationId: string | undefined,
+): { previewData: PreviewData | null; isLoading: boolean } {
+ const { isBetaEnabled } = useV4Beta();
+
+ // For trace evals without traceId: fetch latest trace matching filter
+ const target = form.watch("target");
+ const isEventEval = isEventTarget(target);
+ const isTraceEval = target === EvalTargetObject.TRACE;
+ const latestTrace = api.traces.all.useQuery(
+ {
+ projectId,
+ filter: form.watch("filter"),
+ searchQuery: "",
+ searchType: [],
+ limit: 1,
+ page: 0,
+ orderBy: { column: "timestamp", order: "DESC" },
+ },
+ {
+ enabled: enabled && !traceId && isTraceEval,
+ },
+ );
+
+ const actualTraceId = traceId ?? latestTrace.data?.traces[0]?.id;
+
+ // For trace evals: fetch full trace with observations
+ const traceDetails = api.traces.byIdWithObservationsAndScores.useQuery(
+ {
+ projectId,
+ traceId: actualTraceId as string,
+ },
+ {
+ enabled: enabled && !!actualTraceId && isTraceEval,
+ },
+ );
+
+ const latestObservation = api.generations.all.useQuery(
+ {
+ projectId,
+ filter: form.watch("filter") ?? [],
+ searchQuery: "",
+ searchType: [],
+ limit: 1,
+ page: 0,
+ orderBy: {
+ column: "startTime",
+ order: "DESC",
+ },
+ },
+ {
+ enabled: enabled && !observationId && isEventEval && !isBetaEnabled,
+ },
+ );
+
+ const latestObservationBeta = api.events.all.useQuery(
+ {
+ projectId,
+ filter: form.watch("filter") ?? [],
+ searchQuery: "",
+ searchType: [],
+ limit: 1,
+ page: 0,
+ orderBy: {
+ column: "startTime",
+ order: "DESC",
+ },
+ },
+ {
+ enabled: enabled && !observationId && isEventEval && isBetaEnabled,
+ },
+ );
+
+ const latestObservationTraceId = !!observationId
+ ? traceId
+ : isBetaEnabled
+ ? latestObservationBeta.data?.observations[0]?.traceId
+ : latestObservation.data?.generations[0]?.traceId;
+ const latestObservationObservationId = !!observationId
+ ? observationId
+ : isBetaEnabled
+ ? latestObservationBeta.data?.observations[0]?.id
+ : latestObservation.data?.generations[0]?.id;
+
+ // For event evals: fetch only the single observation
+ const observationDetails = api.observations.byId.useQuery(
+ {
+ projectId,
+ traceId: latestObservationTraceId as string,
+ observationId: latestObservationObservationId as string,
+ startTime: null,
+ },
+ {
+ enabled:
+ enabled &&
+ !!latestObservationTraceId &&
+ !!latestObservationObservationId &&
+ isEventEval,
+ },
+ );
+
+ const previewData: PreviewData | null = isEventEval
+ ? observationDetails.data &&
+ latestObservationTraceId &&
+ latestObservationObservationId
+ ? {
+ type: EvalTargetObject.EVENT,
+ traceId: latestObservationTraceId,
+ observationId: latestObservationObservationId,
+ data: observationDetails.data,
+ }
+ : null
+ : traceDetails.data && actualTraceId
+ ? {
+ type: EvalTargetObject.TRACE,
+ traceId: actualTraceId,
+ data: traceDetails.data,
+ }
+ : null;
+
+ const isLoading =
+ latestTrace.isLoading ||
+ traceDetails.isLoading ||
+ observationDetails.isLoading;
+
+ return {
+ previewData,
+ isLoading,
+ };
+}
diff --git a/web/src/features/evals/pages/remap-evaluator.tsx b/web/src/features/evals/pages/remap-evaluator.tsx
new file mode 100644
index 0000000000..ea5a6e95c6
--- /dev/null
+++ b/web/src/features/evals/pages/remap-evaluator.tsx
@@ -0,0 +1,314 @@
+import { useState, useMemo } from "react";
+import { useRouter } from "next/router";
+import Page from "@/src/components/layouts/page";
+import { api } from "@/src/utils/api";
+import { InnerEvaluatorForm } from "@/src/features/evals/components/inner-evaluator-form";
+import {
+ mapLegacyToModernTarget,
+ isTraceTarget,
+ isEventTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+import { type PartialConfig } from "@/src/features/evals/types";
+import { Alert, AlertDescription } from "@/src/components/ui/alert";
+import { Skeleton } from "@/src/components/ui/skeleton";
+import { Button } from "@/src/components/ui/button";
+import { Separator } from "@/src/components/ui/separator";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+} from "@/src/components/ui/dropdown-menu";
+import { ChevronDown } from "lucide-react";
+import { useEvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";
+
+type LegacyEvalAction = "keep-active" | "mark-inactive" | "delete";
+
+export default function RemapEvaluatorPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const evalConfigId = router.query.evaluator as string;
+
+ const evalCapabilities = useEvalCapabilities(projectId);
+
+ const [error, setError] = useState<string | null>(null);
+ const [legacyAction, setLegacyAction] =
+ useState<LegacyEvalAction>("mark-inactive");
+
+ // Fetch old eval config
+ const { data: oldConfig, isLoading: isLoadingConfig } =
+ api.evals.configById.useQuery(
+ { projectId, id: evalConfigId },
+ { enabled: !!projectId && !!evalConfigId },
+ );
+
+ // Fetch eval template
+ const { data: evalTemplate, isLoading: isLoadingTemplate } =
+ api.evals.templateById.useQuery(
+ {
+ projectId,
+ id: oldConfig?.evalTemplateId ?? "",
+ },
+ { enabled: !!projectId && !!oldConfig?.evalTemplateId },
+ );
+
+ const utils = api.useUtils();
+
+ // Update mutation to set old eval to INACTIVE
+ const updateJobMutation = api.evals.updateEvalJob.useMutation({
+ onSuccess: () => {
+ utils.evals.invalidate();
+ void router.push(`/project/${projectId}/evals`);
+ },
+ onError: (err) => {
+ setError(err.message ?? "Failed to update old eval configuration");
+ },
+ });
+
+ // Delete mutation to remove old eval
+ const deleteJobMutation = api.evals.deleteEvalJob.useMutation({
+ onSuccess: () => {
+ utils.evals.invalidate();
+ void router.push(`/project/${projectId}/evals`);
+ },
+ onError: (err) => {
+ setError(err.message ?? "Failed to delete old eval configuration");
+ },
+ });
+
+ // Map old config to new config with modern target
+ // Only copy scoreName - filters and variable mapping will be initialized fresh
+ const mappedConfig: PartialConfig | null = useMemo(() => {
+ if (!oldConfig) return null;
+
+ return {
+ projectId: oldConfig.projectId,
+ evalTemplateId: oldConfig.evalTemplateId,
+ scoreName: oldConfig.scoreName,
+ targetObject: mapLegacyToModernTarget(oldConfig.targetObject),
+ jobType: oldConfig.jobType,
+ filter: [],
+ variableMapping: [],
+ sampling: oldConfig.sampling,
+ delay: oldConfig.delay,
+ status: "ACTIVE",
+ // Always set to NEW for remapped evals - new eval types cannot run on existing data
+ timeScope: ["NEW"],
+ };
+ }, [oldConfig]);
+
+ const handleFormSuccess = async () => {
+ if (!oldConfig) return;
+
+ try {
+ switch (legacyAction) {
+ case "keep-active":
+ // Do nothing - both old and new evals will be active
+ utils.evals.invalidate();
+ void router.push(`/project/${projectId}/evals`);
+ break;
+ case "mark-inactive":
+ // Set old eval to INACTIVE
+ await updateJobMutation.mutateAsync({
+ projectId,
+ evalConfigId,
+ config: {
+ status: "INACTIVE",
+ },
+ });
+ break;
+ case "delete":
+ // Delete old eval
+ await deleteJobMutation.mutateAsync({
+ projectId,
+ evalConfigId,
+ });
+ break;
+ }
+ } catch (err) {
+ // Error already handled in mutation onError
+ console.error(`Failed to ${legacyAction} old eval:`, err);
+ }
+ };
+
+ const isLoading = isLoadingConfig || isLoadingTemplate;
+
+ return (
+ <Page
+ withPadding
+ scrollable
+ headerProps={{
+ title: "Upgrade Evaluator",
+ breadcrumb: [
+ {
+ name: "Running Evaluators",
+ href: `/project/${projectId}/evals`,
+ },
+ ],
+ }}
+ >
+ <div className="space-y-4">
+ <div>
+ <p className="text-sm text-muted-foreground">
+ Review your legacy evaluator on the left and configure the new eval
+ settings on the right.{" "}
+ <a
+ href="https://langfuse.com/faq/all/llm-as-a-judge-migration"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-dark-blue hover:opacity-80"
+ >
+ Follow our step-by-step guide
+ </a>{" "}
+ to upgrade successfully.
+ </p>
+ {mappedConfig ? (
+ <Alert
+ variant="default"
+ className="mt-2 border-light-yellow bg-light-yellow"
+ >
+ <AlertDescription>
+ <div className="flex flex-col gap-2">
+ {isEventTarget(mappedConfig.targetObject ?? "event")
+ ? "Running evaluators requires JS SDK ≥ 4.0.0 or Python SDK ≥ 3.0.0."
+ : "Running evaluators requires JS SDK ≥ 4.4.0 or Python SDK ≥ 3.9.0."}
+ </div>
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ </div>
+
+ <div>
+ {isLoading ? (
+ <div className="grid grid-cols-2 gap-6">
+ <Skeleton className="h-[600px] w-full" />
+ <Skeleton className="h-[600px] w-full" />
+ </div>
+ ) : !oldConfig || !evalTemplate ? (
+ <Alert variant="destructive">
+ <AlertDescription>
+ Failed to load eval configuration or template.
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <div className="grid grid-cols-[1fr_2px_1fr] items-start">
+ {/* LEFT: Read-only old config */}
+ <div className="space-y-4 p-3">
+ <div className="flex items-center gap-2 pb-2">
+ <h3 className="text-lg font-semibold">
+ Legacy Configuration{" "}
+ {isTraceTarget(oldConfig.targetObject)
+ ? "(runs on traces)"
+ : ""}
+ </h3>
+ <span className="text-xs text-muted-foreground">
+ Read-only
+ </span>
+ </div>
+ <InnerEvaluatorForm
+ projectId={projectId}
+ evalTemplate={evalTemplate}
+ useDialog={false}
+ disabled={true}
+ existingEvaluator={oldConfig}
+ mode="edit"
+ hideTargetSection={false}
+ hideTargetSelection={true}
+ hideAdvancedSettings={true}
+ preventRedirect={true}
+ renderFooter={() => null}
+ evalCapabilities={evalCapabilities}
+ />
+ </div>
+
+ <Separator orientation="vertical" className="self-stretch" />
+
+ {/* RIGHT: Editable new config form */}
+ <div className="space-y-4 p-3">
+ <h3 className="pb-2 text-lg font-semibold">
+ New Configuration{" "}
+ {isTraceTarget(oldConfig.targetObject)
+ ? "(runs on observations)"
+ : ""}
+ </h3>
+ <InnerEvaluatorForm
+ projectId={projectId}
+ evalTemplate={evalTemplate}
+ useDialog={false}
+ existingEvaluator={mappedConfig ?? undefined}
+ onFormSuccess={handleFormSuccess}
+ mode="create"
+ hideTargetSection={false}
+ hideTargetSelection={true}
+ preventRedirect={true}
+ hideAdvancedSettings={true}
+ evalCapabilities={evalCapabilities}
+ oldConfigId={evalConfigId}
+ renderFooter={({ isLoading, formError }) => (
+ <div className="flex w-full flex-col items-end gap-4">
+ <div className="flex items-center">
+ <Button
+ type="submit"
+ loading={isLoading}
+ className="mt-3 rounded-l-md rounded-r-none"
+ >
+ {legacyAction === "keep-active"
+ ? "Save & keep legacy active"
+ : legacyAction === "mark-inactive"
+ ? "Save & mark legacy inactive"
+ : "Save & delete legacy"}
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ disabled={isLoading}
+ className="mt-3 rounded-l-none rounded-r-md border-l-2"
+ >
+ <ChevronDown className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => setLegacyAction("keep-active")}
+ >
+ {legacyAction === "keep-active" && "✓ "}
+ Save & keep legacy active
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => setLegacyAction("mark-inactive")}
+ >
+ {legacyAction === "mark-inactive" && "✓ "}
+ Save & mark legacy inactive
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => setLegacyAction("delete")}
+ >
+ {legacyAction === "delete" && "✓ "}
+ Save & delete legacy
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ {formError ? (
+ <p className="text-red w-full text-center">
+ <span className="font-bold">Error:</span> {formError}
+ </p>
+ ) : null}
+ </div>
+ )}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+
+ {error && (
+ <Alert variant="destructive">
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+ </Page>
+ );
+}
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 72d8bc15ca..a0335de9ed 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -10,6 +10,7 @@ import {
ZodModelConfig,
singleFilter,
variableMapping,
+ observationVariableMapping,
paginationZod,
type JobConfiguration,
JobType,
@@ -55,7 +56,11 @@ const ConfigWithTemplateSchema = z.object({
scoreName: z.string(),
targetObject: z.string(),
filter: z.array(singleFilter).nullable(), // reusing the filter type from the tables
- variableMapping: z.array(variableMapping),
+ // Accept either full variableMapping (trace/dataset) or simplified observationVariableMapping (event/experiment)
+ variableMapping: z.union([
+ z.array(variableMapping),
+ z.array(observationVariableMapping),
+ ]),
sampling: z.instanceof(Prisma.Decimal),
delay: z.number(),
status: z.enum(JobConfigState),
@@ -130,7 +135,11 @@ const CreateEvalJobSchema = z.object({
scoreName: z.string().min(1),
target: z.string(), // should be z.enum(["trace", "dataset-run-item"])
filter: z.array(singleFilter).nullable(), // reusing the filter type from the tables
- mapping: z.array(variableMapping),
+ // Accept either full variableMapping (trace/dataset) or simplified observationVariableMapping (event/experiment)
+ mapping: z.union([
+ z.array(variableMapping),
+ z.array(observationVariableMapping),
+ ]),
sampling: z.number().gt(0).lte(1),
delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default
timeScope: TimeScopeSchema,
@@ -139,7 +148,10 @@ const CreateEvalJobSchema = z.object({
const UpdateEvalJobSchema = z.object({
scoreName: z.string().min(1).optional(),
filter: z.array(singleFilter).optional(),
- variableMapping: z.array(variableMapping).optional(),
+ // Accept either full variableMapping (trace/dataset) or simplified observationVariableMapping (event/experiment)
+ variableMapping: z
+ .union([z.array(variableMapping), z.array(observationVariableMapping)])
+ .optional(),
sampling: z.number().gt(0).lte(1).optional(),
delay: z.number().gte(0).optional(),
status: z.enum(EvaluatorStatus).optional(),
@@ -217,8 +229,8 @@ export const evalRouter = createTRPCRouter({
scope: "evalJob:read",
});
- const [configCount, configActiveCount, templateCount] = await Promise.all(
- [
+ const [configCount, configActiveCount, templateCount, legacyConfigCount] =
+ await Promise.all([
ctx.prisma.jobConfiguration.count({
where: {
projectId: input.projectId,
@@ -237,13 +249,22 @@ export const evalRouter = createTRPCRouter({
projectId: input.projectId,
},
}),
- ],
- );
+ ctx.prisma.jobConfiguration.count({
+ where: {
+ projectId: input.projectId,
+ jobType: "EVAL",
+ targetObject: {
+ in: [EvalTargetObject.TRACE, EvalTargetObject.DATASET],
+ },
+ },
+ }),
+ ]);
return {
configCount,
configActiveCount,
templateCount,
+ legacyConfigCount,
};
}),
allConfigs: protectedProjectProcedure
@@ -626,7 +647,12 @@ export const evalRouter = createTRPCRouter({
}),
jobConfigsByTarget: protectedProjectProcedure
- .input(z.object({ projectId: z.string(), targetObject: z.string() }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ targetObject: z.string(),
+ }),
+ )
.query(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
diff --git a/web/src/features/evals/utils/evaluator-constants.ts b/web/src/features/evals/utils/evaluator-constants.ts
new file mode 100644
index 0000000000..203f58723a
--- /dev/null
+++ b/web/src/features/evals/utils/evaluator-constants.ts
@@ -0,0 +1,56 @@
+import {
+ LangfuseInternalTraceEnvironment,
+ observationEvalVariableColumns,
+} from "@langfuse/shared";
+
+/**
+ * Constant for observation-based evaluators (event/experiment).
+ * Provides the available variables structure for the UI dropdowns.
+ */
+export const OBSERVATION_VARIABLES = [
+ {
+ id: "observation",
+ display: "Observation",
+ availableColumns: observationEvalVariableColumns.map((col) => ({
+ // id corresponds to the internal column name
+ id: col.id,
+ name: col.name,
+ ...(col.type ? { type: col.type } : {}),
+ internal: col.internal,
+ })),
+ },
+];
+
+export const COLUMN_IDENTIFIERS_THAT_REQUIRE_PROPAGATION = new Set([
+ "release",
+ "traceName",
+ "userId",
+ "sessionId",
+ "tags",
+]);
+
+export const OUTPUT_MAPPING = [
+ "generation",
+ "output",
+ "response",
+ "answer",
+ "completion",
+];
+
+export const INTERNAL_ENVIRONMENTS = [
+ LangfuseInternalTraceEnvironment.LLMJudge,
+ "langfuse-prompt-experiments",
+ "langfuse-evaluation",
+ "sdk-experiment",
+] as const;
+
+// Default filter for new trace evaluators - excludes internal Langfuse environments
+// to prevent evaluators from running on their own traces
+export const DEFAULT_TRACE_FILTER = [
+ {
+ column: "environment",
+ operator: "none of" as const,
+ value: [...INTERNAL_ENVIRONMENTS],
+ type: "stringOptions" as const,
+ },
+];
diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.ts
index 0d68488693..b6ab2415a2 100644
--- a/web/src/features/evals/utils/evaluator-form-utils.ts
+++ b/web/src/features/evals/utils/evaluator-form-utils.ts
@@ -5,10 +5,7 @@ import {
TimeScopeSchema,
} from "@langfuse/shared";
import { wipVariableMapping } from "@langfuse/shared";
-
-export const isTraceTarget = (target: string): boolean => target === "trace";
-export const isTraceOrDatasetObject = (object: string): boolean =>
- object === "trace" || object === "dataset_item";
+import { OUTPUT_MAPPING } from "@/src/features/evals/utils/evaluator-constants";
export const evalConfigFormSchema = z.object({
scoreName: z.string(),
@@ -25,3 +22,39 @@ export type EvalFormType = z.infer<typeof evalConfigFormSchema>;
export type LangfuseObject = (typeof langfuseObjects)[number];
export type VariableMapping = z.infer<typeof wipVariableMapping>;
+
+export const inferDefaultMapping = (
+ variable: string,
+): Pick<VariableMapping, "selectedColumnId"> => {
+ return {
+ selectedColumnId: OUTPUT_MAPPING.includes(variable.toLowerCase())
+ ? "output"
+ : "input",
+ };
+};
+
+export const fieldHasJsonSelectorOption = (
+ selectedColumnId: string | undefined | null,
+): boolean =>
+ selectedColumnId === "input" ||
+ selectedColumnId === "output" ||
+ selectedColumnId === "metadata" ||
+ selectedColumnId === "expected_output" ||
+ selectedColumnId === "experiment_item_expected_output" ||
+ selectedColumnId === "expectedOutput" ||
+ selectedColumnId === "experimentItemExpectedOutput";
+
+export const getTargetDisplayName = (target: string): string => {
+ switch (target) {
+ case "trace":
+ return "traces";
+ case "event":
+ return "observations";
+ case "dataset":
+ return "dataset run items";
+ case "experiment":
+ return "experiments";
+ default:
+ return target;
+ }
+};
diff --git a/web/src/features/evals/utils/typeHelpers.ts b/web/src/features/evals/utils/typeHelpers.ts
index 6fe69e3f1e..19ed78d446 100644
--- a/web/src/features/evals/utils/typeHelpers.ts
+++ b/web/src/features/evals/utils/typeHelpers.ts
@@ -1,4 +1,8 @@
-import { type EvalTemplate } from "@langfuse/shared";
+import {
+ type EvalTemplate,
+ EvalTargetObject,
+ type EvalTargetObject as EvalTargetObjectType,
+} from "@langfuse/shared";
export const partnerIdentifierToName = new Map([["ragas", "Ragas"]]);
@@ -20,3 +24,52 @@ export const getMaintainer = (
}
return "User maintained";
};
+
+/**
+ * Determines if an eval target object is using the legacy (deprecated) eval system.
+ * Legacy eval types (trace-level, dataset-run-level) have limited SDK compatibility.
+ * @param targetObject - The eval target object type
+ * @returns true if the target object is legacy (trace or dataset)
+ */
+export const isLegacyEvalTarget = (targetObject: string): boolean => {
+ return (
+ targetObject === EvalTargetObject.TRACE ||
+ targetObject === EvalTargetObject.DATASET
+ );
+};
+
+export const isTraceTarget = (targetObject: string): boolean => {
+ return targetObject === EvalTargetObject.TRACE;
+};
+
+export const isEventTarget = (targetObject: string): boolean => {
+ return targetObject === EvalTargetObject.EVENT;
+};
+
+export const isDatasetTarget = (targetObject: string): boolean => {
+ return targetObject === EvalTargetObject.DATASET;
+};
+
+export const isExperimentTarget = (targetObject: string): boolean => {
+ return targetObject === EvalTargetObject.EXPERIMENT;
+};
+
+export const isTraceOrEventTarget = (targetObject: string): boolean => {
+ return (
+ targetObject === EvalTargetObject.TRACE ||
+ targetObject === EvalTargetObject.EVENT
+ );
+};
+
+export const isTraceOrDatasetObject = (object: string): boolean => {
+ return object === "trace" || object === "dataset_item";
+};
+
+export const mapLegacyToModernTarget = (
+ legacyTarget: string,
+): EvalTargetObjectType => {
+ if (legacyTarget === EvalTargetObject.TRACE) return EvalTargetObject.EVENT;
+ if (legacyTarget === EvalTargetObject.DATASET)
+ return EvalTargetObject.EXPERIMENT;
+ return legacyTarget as EvalTargetObjectType;
+};
diff --git a/web/src/features/evals/utils/variable-mapping-validation.ts b/web/src/features/evals/utils/variable-mapping-validation.ts
new file mode 100644
index 0000000000..8000e24c6a
--- /dev/null
+++ b/web/src/features/evals/utils/variable-mapping-validation.ts
@@ -0,0 +1,120 @@
+import { z } from "zod/v4";
+import {
+ variableMapping,
+ observationVariableMapping,
+ type EvalTargetObject,
+} from "@langfuse/shared";
+import {
+ isEventTarget,
+ isExperimentTarget,
+} from "@/src/features/evals/utils/typeHelpers";
+
+type FormMappingValue = {
+ templateVariable: string;
+ langfuseObject?: string;
+ objectName?: string | null;
+ selectedColumnId?: string | null;
+ jsonSelector?: string | null;
+};
+
+type ValidationResult =
+ | {
+ success: true;
+ data:
+ | z.infer<typeof variableMapping>[]
+ | z.infer<typeof observationVariableMapping>[];
+ }
+ | {
+ success: false;
+ error: string;
+ };
+
+/**
+ * Validates and transforms variable mappings based on the target type.
+ * Returns validated data or an error message.
+ */
+export function validateAndTransformVariableMapping(
+ mappings: FormMappingValue[],
+ target: EvalTargetObject,
+): ValidationResult {
+ const isEventOrExperimentTarget =
+ isEventTarget(target) || isExperimentTarget(target);
+
+ // Check for incomplete mappings (missing selectedColumnId)
+ const incompleteMappings = mappings.filter(
+ (m) =>
+ !m.selectedColumnId ||
+ m.selectedColumnId === null ||
+ m.selectedColumnId.trim() === "",
+ );
+
+ if (incompleteMappings.length > 0) {
+ return {
+ success: false,
+ error: "Please complete all variable mappings",
+ };
+ }
+
+ // For trace/dataset targets, check that observation objects have objectName
+ if (!isEventOrExperimentTarget) {
+ const missingObjectName = mappings.filter(
+ (m) =>
+ m.langfuseObject !== "trace" &&
+ m.langfuseObject !== "dataset_item" &&
+ (!m.objectName || m.objectName.trim() === ""),
+ );
+
+ if (missingObjectName.length > 0) {
+ return {
+ success: false,
+ error: "Please complete all variable mappings",
+ };
+ }
+ }
+
+ // Transform and validate mappings based on target type
+ const validatedVarMapping = isEventOrExperimentTarget
+ ? z.array(observationVariableMapping).safeParse(
+ mappings.map((m) => {
+ const mapping: Record<string, any> = {
+ templateVariable: m.templateVariable,
+ selectedColumnId: m.selectedColumnId!,
+ };
+ // Only include jsonSelector if it has a value
+ if (m.jsonSelector) {
+ mapping.jsonSelector = m.jsonSelector;
+ }
+ return mapping;
+ }),
+ )
+ : z.array(variableMapping).safeParse(
+ mappings.map((m) => {
+ const mapping: Record<string, any> = {
+ templateVariable: m.templateVariable,
+ langfuseObject: m.langfuseObject,
+ selectedColumnId: m.selectedColumnId!,
+ };
+ // Only include objectName if it has a value
+ if (m.objectName) {
+ mapping.objectName = m.objectName;
+ }
+ // Only include jsonSelector if it has a value
+ if (m.jsonSelector) {
+ mapping.jsonSelector = m.jsonSelector;
+ }
+ return mapping;
+ }),
+ );
+
+ if (!validatedVarMapping.success) {
+ return {
+ success: false,
+ error: "Please complete all variable mappings",
+ };
+ }
+
+ return {
+ success: true,
+ data: validatedVarMapping.data,
+ };
+}
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 9e3eef1781..baf67e098a 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -30,7 +30,10 @@ import { numberFormatter, usdFormatter } 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 {
+ toAbsoluteTimeRange,
+ type TableDateRange,
+} from "@/src/utils/date-range-utils";
import { type ScoreAggregate } from "@langfuse/shared";
import TagList from "@/src/features/tag/components/TagList";
import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";
@@ -143,12 +146,21 @@ export type EventsTableRow = {
export type EventsTableProps = {
projectId: string;
userId?: string;
+ hideControls?: boolean;
+ // External control props for embedded preview tables
+ externalFilterState?: FilterState;
+ externalDateRange?: TableDateRange;
+ limitRows?: number;
sessionId?: string;
};
export default function ObservationsEventsTable({
projectId,
userId,
+ hideControls = false,
+ externalFilterState,
+ externalDateRange,
+ limitRows,
sessionId,
}: EventsTableProps) {
const router = useRouter();
@@ -276,12 +288,14 @@ export default function ObservationsEventsTable({
// Convert timeRange to absolute date range for compatibility
// Include refreshTick to force recalculation on refresh
- const dateRange = useMemo(() => {
+ const tableDateRange = useMemo(() => {
// refreshTick forces recalculation but isn't used in computation
void refreshTick;
return toAbsoluteTimeRange(timeRange) ?? undefined;
}, [timeRange, refreshTick]);
+ const dateRange = externalDateRange ?? tableDateRange;
+
const dateRangeFilter: FilterState = dateRange
? [
{
@@ -317,6 +331,7 @@ export default function ObservationsEventsTable({
filterOptions,
projectId,
isFilterOptionsPending,
+ hideControls, // Disable URL persistence for embedded preview tables
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -364,12 +379,14 @@ export default function ObservationsEventsTable({
]
: [];
- const filterState = queryFilter.filterState
+ const combinedFilterState = queryFilter.filterState
.concat(dateRangeFilter)
.concat(viewModeFilter)
.concat(userIdFilter)
.concat(sessionIdFilter);
+ // Use external filter state if provided, otherwise use combined filter state
+ const filterState = externalFilterState || combinedFilterState;
// Filter state WITHOUT viewModeFilter - for auto-switch observation count check
const filterStateWithoutViewMode = useMemo(() => {
const filters: FilterState = [...queryFilter.filterState];
@@ -426,7 +443,9 @@ export default function ObservationsEventsTable({
} = useEventsTableData({
projectId,
filterState,
- paginationState,
+ paginationState: limitRows
+ ? { page: 1, limit: limitRows }
+ : paginationState,
orderByState,
searchQuery,
searchType,
@@ -501,12 +520,10 @@ export default function ObservationsEventsTable({
"observations",
observations?.rows?.map((o) => ({
id: o?.id,
- params: o?.startTime
- ? {
- timestamp: o?.startTime.toISOString(),
- traceId: o?.traceId || "",
- }
- : undefined,
+ params: {
+ traceId: o?.traceId || "",
+ ...(o?.startTime ? { timestamp: o?.startTime.toISOString() } : {}),
+ },
})) ?? [],
);
}
@@ -541,15 +558,17 @@ export default function ObservationsEventsTable({
},
];
+ const enableSorting = !hideControls;
+
const columns: LangfuseColumnDef<EventsTableRow>[] = [
- selectActionColumn,
+ ...(hideControls ? [] : [selectActionColumn]),
{
accessorKey: "startTime",
id: "startTime",
header: getEventsColumnName("startTime"),
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: Date = row.getValue("startTime");
return <LocalIsoDate date={value} />;
@@ -560,7 +579,7 @@ export default function ObservationsEventsTable({
id: "type",
header: getEventsColumnName("type"),
size: 50,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: ObservationType = row.getValue("type");
return value ? (
@@ -575,7 +594,7 @@ export default function ObservationsEventsTable({
id: "name",
header: getEventsColumnName("name"),
size: 150,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const value: EventsTableRow["name"] = row.getValue("name");
return value ?? undefined;
@@ -685,7 +704,7 @@ export default function ObservationsEventsTable({
</span>
) : undefined;
},
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "statusMessage",
@@ -722,7 +741,7 @@ export default function ObservationsEventsTable({
) : undefined;
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "totalCost",
@@ -746,7 +765,7 @@ export default function ObservationsEventsTable({
) : undefined;
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "cost",
@@ -777,7 +796,7 @@ export default function ObservationsEventsTable({
},
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "outputCost",
@@ -796,7 +815,7 @@ export default function ObservationsEventsTable({
},
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
},
],
},
@@ -806,7 +825,7 @@ export default function ObservationsEventsTable({
header: getEventsColumnName("timeToFirstToken"),
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const timeToFirstToken: number | undefined =
row.getValue("timeToFirstToken");
@@ -853,7 +872,7 @@ export default function ObservationsEventsTable({
},
defaultHidden: true,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
},
{
accessorKey: "inputTokens",
@@ -862,7 +881,7 @@ export default function ObservationsEventsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<EventsTableRow> }) => {
const value = row.getValue("usage") as {
inputUsage: number;
@@ -879,7 +898,7 @@ export default function ObservationsEventsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<EventsTableRow> }) => {
const value = row.getValue("usage") as {
inputUsage: number;
@@ -896,7 +915,7 @@ export default function ObservationsEventsTable({
size: 100,
enableHiding: true,
defaultHidden: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }: { row: Row<EventsTableRow> }) => {
const value = row.getValue("usage") as {
inputUsage: number;
@@ -914,7 +933,7 @@ export default function ObservationsEventsTable({
header: getEventsColumnName("providedModelName"),
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const model = row.getValue("providedModelName") as string;
const modelId = row.getValue("modelId") as string | undefined;
@@ -962,7 +981,7 @@ export default function ObservationsEventsTable({
},
size: 200,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
cell: ({ row }) => {
const promptName = row.original.promptName;
const promptVersion = row.original.promptVersion;
@@ -1028,7 +1047,7 @@ export default function ObservationsEventsTable({
header: getEventsColumnName("endTime"),
size: 150,
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
cell: ({ row }) => {
const value: Date | undefined = row.getValue("endTime");
@@ -1046,7 +1065,7 @@ export default function ObservationsEventsTable({
<TableIdOrName value={value} />
) : undefined;
},
- enableSorting: true,
+ enableSorting,
enableHiding: true,
defaultHidden: true,
},
@@ -1068,7 +1087,7 @@ export default function ObservationsEventsTable({
href: "https://langfuse.com/docs/experimentation",
},
enableHiding: true,
- enableSorting: true,
+ enableSorting,
defaultHidden: true,
},
{
@@ -1130,17 +1149,17 @@ export default function ObservationsEventsTable({
currentFilterState: queryFilter.filterState,
});
- const peekConfig: DataTablePeekViewProps = useMemo(
- () => ({
+ const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {
+ if (hideControls) return undefined;
+ return {
itemType: "TRACE",
customTitlePrefix: "Observation ID:",
detailNavigationKey: "observations",
children: <PeekViewObservationDetail projectId={projectId} />,
tableDataUpdatedAt: dataUpdatedAt,
...peekNavigationProps,
- }),
- [projectId, dataUpdatedAt, peekNavigationProps],
- );
+ };
+ }, [projectId, dataUpdatedAt, peekNavigationProps, hideControls]);
const rows: EventsTableRow[] = useMemo(() => {
const result =
@@ -1209,85 +1228,93 @@ export default function ObservationsEventsTable({
<DataTableControlsProvider>
<div className="flex h-full w-full flex-col">
{/* Toolbar spanning full width */}
- <DataTableToolbar
- columns={columns}
- filterState={queryFilter.filterState}
- searchConfig={{
- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
- updateQuery: setSearchQuery,
- currentQuery: searchQuery ?? undefined,
- searchType,
- setSearchType,
- tableAllowsFullTextSearch: true,
- }}
- viewConfig={{
- tableName: TableViewPresetTableName.Observations,
- projectId,
- controllers: viewControllers,
- }}
- columnsWithCustomSelect={["providedModelName", "name", "promptName"]}
- columnVisibility={columnVisibility}
- setColumnVisibility={setColumnVisibilityState}
- columnOrder={columnOrder}
- setColumnOrder={setColumnOrder}
- orderByState={orderByState}
- rowHeight={rowHeight}
- setRowHeight={setRowHeight}
- timeRange={timeRange}
- setTimeRange={setTimeRange}
- viewModeToggle={
- <EventsViewModeToggle
- viewMode={viewMode}
- onViewModeChange={setViewMode}
- />
- }
- refreshConfig={{
- onRefresh: handleRefresh,
- isRefreshing: observations.status === "loading",
- interval: refreshInterval,
- setInterval: setRefreshInterval,
- }}
- actionButtons={[
- <BatchExportTableButton
- {...{
- projectId,
- filterState,
- orderByState,
- searchQuery,
- searchType,
- }}
- tableName={BatchExportTableName.Observations}
- key="batchExport"
- />,
- Object.keys(selectedRows).filter((observationId) =>
- observations.rows?.map((o) => o.id).includes(observationId),
- ).length > 0 ? (
- <TableActionMenu
- key="observations-multi-select-actions"
- projectId={projectId}
- actions={tableActions}
- tableName={BatchExportTableName.Observations}
+ {!hideControls && (
+ <DataTableToolbar
+ columns={columns}
+ filterState={queryFilter.filterState}
+ searchConfig={{
+ metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
+ updateQuery: setSearchQuery,
+ currentQuery: searchQuery ?? undefined,
+ searchType,
+ setSearchType,
+ tableAllowsFullTextSearch: true,
+ }}
+ viewConfig={{
+ tableName: TableViewPresetTableName.Observations,
+ projectId,
+ controllers: viewControllers,
+ }}
+ columnsWithCustomSelect={[
+ "providedModelName",
+ "name",
+ "promptName",
+ ]}
+ columnVisibility={columnVisibility}
+ setColumnVisibility={setColumnVisibilityState}
+ columnOrder={columnOrder}
+ setColumnOrder={setColumnOrder}
+ orderByState={orderByState}
+ rowHeight={rowHeight}
+ setRowHeight={setRowHeight}
+ timeRange={timeRange}
+ setTimeRange={setTimeRange}
+ viewModeToggle={
+ <EventsViewModeToggle
+ viewMode={viewMode}
+ onViewModeChange={setViewMode}
/>
- ) : null,
- ]}
- multiSelect={{
- selectAll,
- setSelectAll,
- selectedRowIds:
+ }
+ refreshConfig={{
+ onRefresh: handleRefresh,
+ isRefreshing: observations.status === "loading",
+ interval: refreshInterval,
+ setInterval: setRefreshInterval,
+ }}
+ actionButtons={[
+ <BatchExportTableButton
+ {...{
+ projectId,
+ filterState,
+ orderByState,
+ searchQuery,
+ searchType,
+ }}
+ tableName={BatchExportTableName.Observations}
+ key="batchExport"
+ />,
Object.keys(selectedRows).filter((observationId) =>
observations.rows?.map((o) => o.id).includes(observationId),
- ) ?? [],
- setRowSelection: setSelectedRows,
- totalCount,
- pageSize: paginationState.limit,
- pageIndex: paginationState.page - 1,
- }}
- filterWithAI
- />
+ ).length > 0 ? (
+ <TableActionMenu
+ key="observations-multi-select-actions"
+ projectId={projectId}
+ actions={tableActions}
+ tableName={BatchExportTableName.Observations}
+ />
+ ) : null,
+ ]}
+ multiSelect={{
+ selectAll,
+ setSelectAll,
+ selectedRowIds:
+ Object.keys(selectedRows).filter((observationId) =>
+ observations.rows?.map((o) => o.id).includes(observationId),
+ ) ?? [],
+ setRowSelection: setSelectedRows,
+ totalCount,
+ pageSize: paginationState.limit,
+ pageIndex: paginationState.page - 1,
+ }}
+ filterWithAI
+ />
+ )}
{/* Content area with sidebar and table */}
<ResizableFilterLayout>
- <DataTableControls queryFilter={queryFilter} filterWithAI />
+ {!hideControls && (
+ <DataTableControls queryFilter={queryFilter} filterWithAI />
+ )}
<div className="flex flex-1 flex-col overflow-hidden">
<DataTable
@@ -1312,26 +1339,30 @@ export default function ObservationsEventsTable({
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,
- },
- }}
+ pagination={
+ limitRows
+ ? undefined
+ : {
+ 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}
diff --git a/web/src/features/events/hooks/useObservationEvals.ts b/web/src/features/events/hooks/useObservationEvals.ts
new file mode 100644
index 0000000000..18d711fac4
--- /dev/null
+++ b/web/src/features/events/hooks/useObservationEvals.ts
@@ -0,0 +1,5 @@
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
+
+export function useObservationEvals() {
+ return useIsFeatureEnabled("observationEvals") ?? false;
+}
diff --git a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
index 2030c15a31..446f43f96c 100644
--- a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
+++ b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
@@ -23,15 +23,15 @@ export function useEvaluatorDefaults() {
datasetId: string,
scoreName?: string,
): PartialConfig & { evalTemplate: EvalTemplate } => {
- // Create variable mappings that alternate between dataset_item and trace
- const alternatingMappings = createDefaultVariableMappings(template);
+ // Create variable mappings (dataset evaluator schema)
+ const variableMappings = createDefaultVariableMappings(template);
- // Return the configured evaluator
+ // Return the configured evaluator for dataset target
return {
...CONFIG_BASE,
evalTemplate: template,
scoreName: scoreName || template.name,
- variableMapping: alternatingMappings,
+ variableMapping: variableMappings,
filter: [
{
type: "stringOptions",
diff --git a/web/src/features/experiments/utils/evaluatorMappingUtils.ts b/web/src/features/experiments/utils/evaluatorMappingUtils.ts
index 5f9da10843..6bc37ab292 100644
--- a/web/src/features/experiments/utils/evaluatorMappingUtils.ts
+++ b/web/src/features/experiments/utils/evaluatorMappingUtils.ts
@@ -9,36 +9,135 @@ type VariableMapping = {
jsonSelector?: string;
};
+// Observation variable mapping (for event/experiment evaluators)
+type ObservationVariableMapping = {
+ templateVariable: string;
+ selectedColumnId: string;
+ jsonSelector?: string;
+};
+
const defaultMappings = new Map<string, Partial<VariableMapping>>([
- // Common input variables
- ["input", { langfuseObject: "trace", selectedColumnId: "input" }],
- ["query", { langfuseObject: "trace", selectedColumnId: "input" }],
- ["question", { langfuseObject: "trace", selectedColumnId: "input" }],
- ["prompt", { langfuseObject: "trace", selectedColumnId: "input" }],
+ // Common input variables (trace doesn't need objectName)
+ [
+ "input",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "input",
+ objectName: undefined,
+ },
+ ],
+ [
+ "query",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "input",
+ objectName: undefined,
+ },
+ ],
+ [
+ "question",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "input",
+ objectName: undefined,
+ },
+ ],
+ [
+ "prompt",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "input",
+ objectName: undefined,
+ },
+ ],
- // Common output variables
- ["output", { langfuseObject: "trace", selectedColumnId: "output" }],
- ["response", { langfuseObject: "trace", selectedColumnId: "output" }],
- ["answer", { langfuseObject: "trace", selectedColumnId: "output" }],
- ["completion", { langfuseObject: "trace", selectedColumnId: "output" }],
+ // Common output variables (trace doesn't need objectName)
+ [
+ "output",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "output",
+ objectName: undefined,
+ },
+ ],
+ [
+ "response",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "output",
+ objectName: undefined,
+ },
+ ],
+ [
+ "answer",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "output",
+ objectName: undefined,
+ },
+ ],
+ [
+ "completion",
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "output",
+ objectName: undefined,
+ },
+ ],
- // Common ground truth variables
+ // Common ground truth variables (dataset_item doesn't need objectName)
[
"expected_output",
- { langfuseObject: "dataset_item", selectedColumnId: "expected_output" },
+ {
+ langfuseObject: "dataset_item",
+ selectedColumnId: "expected_output",
+ objectName: undefined,
+ },
],
[
"ground_truth",
- { langfuseObject: "dataset_item", selectedColumnId: "expected_output" },
+ {
+ langfuseObject: "dataset_item",
+ selectedColumnId: "expected_output",
+ objectName: undefined,
+ },
],
[
"reference",
- { langfuseObject: "dataset_item", selectedColumnId: "expected_output" },
+ {
+ langfuseObject: "dataset_item",
+ selectedColumnId: "expected_output",
+ objectName: undefined,
+ },
],
]);
+// Default mappings for observation-based evaluators (event/experiment)
+const observationDefaultMappings = new Map<
+ string,
+ Partial<ObservationVariableMapping>
+>([
+ // Common input variables
+ ["input", { selectedColumnId: "input" }],
+ ["query", { selectedColumnId: "input" }],
+ ["question", { selectedColumnId: "input" }],
+ ["prompt", { selectedColumnId: "input" }],
+
+ // Common output variables
+ ["output", { selectedColumnId: "output" }],
+ ["response", { selectedColumnId: "output" }],
+ ["answer", { selectedColumnId: "output" }],
+ ["completion", { selectedColumnId: "output" }],
+
+ // Common ground truth variables (from experiment item)
+ ["expected_output", { selectedColumnId: "experimentItemExpectedOutput" }],
+ ["ground_truth", { selectedColumnId: "experimentItemExpectedOutput" }],
+ ["reference", { selectedColumnId: "experimentItemExpectedOutput" }],
+]);
+
/**
* Creates default variable mappings for an evaluator template.
+ * Used for trace/dataset evaluators (legacy).
*
* @param template - The evaluation template containing variables
* @returns Array of variable mappings
@@ -68,6 +167,44 @@ export function createDefaultVariableMappings(
langfuseObject: "dataset_item",
templateVariable: variable,
selectedColumnId: "expected_output",
+ objectName: undefined,
+ jsonSelector: undefined,
+ };
+ });
+}
+
+/**
+ * Creates default variable mappings for observation-based evaluators (event/experiment).
+ * Uses simplified schema without langfuseObject.
+ *
+ * @param template - The evaluation template containing variables
+ * @returns Array of observation variable mappings
+ */
+export function createDefaultObservationVariableMappings(
+ template: EvalTemplate,
+): ObservationVariableMapping[] {
+ if (!template.vars || template.vars.length === 0) {
+ return [];
+ }
+
+ return template.vars.map((variable) => {
+ // Check if we have a default mapping for this variable name
+ const defaultMapping = observationDefaultMappings.get(
+ variable.toLowerCase(),
+ );
+
+ if (defaultMapping) {
+ return {
+ templateVariable: variable,
+ selectedColumnId:
+ defaultMapping.selectedColumnId || "experimentItemExpectedOutput",
+ jsonSelector: defaultMapping.jsonSelector,
+ };
+ }
+
+ return {
+ templateVariable: variable,
+ selectedColumnId: "experimentItemExpectedOutput",
};
});
}
diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.ts
index c2fbbf82f0..e83365cf8f 100644
--- a/web/src/features/feature-flags/available-flags.ts
+++ b/web/src/features/feature-flags/available-flags.ts
@@ -2,4 +2,5 @@ export const availableFlags = [
"templateFlag",
"excludeClickhouseRead",
"v4BetaToggleVisible",
+ "observationEvals",
] as const;
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index fdfe16fccd..c8096e5e36 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -62,20 +62,34 @@ import {
import { useQueryProject } from "@/src/features/projects/hooks";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
+/**
+ * Extended ColumnDefinition with optional alert for UI display.
+ * Alerts are added dynamically in the web layer based on feature availability.
+ */
+export type ColumnDefinitionWithAlert = ColumnDefinition & {
+ alert?: {
+ severity: "info" | "warning" | "error";
+ content: React.ReactNode;
+ };
+};
+
// Has WipFilterState, passes all valid filters to parent onChange
export function PopoverFilterBuilder({
columns,
filterState,
onChange,
+ columnIdentifier = "name",
columnsWithCustomSelect = [],
filterWithAI = false,
buttonType = "default",
}: {
- columns: ColumnDefinition[];
+ /** Which column field to persist in filter.column: 'id' for stable refs, 'name' for legacy compatibility */
+ columns: ColumnDefinitionWithAlert[];
filterState: FilterState;
onChange:
| Dispatch<SetStateAction<FilterState>>
| ((newState: FilterState) => void);
+ columnIdentifier?: ColumnIdentifier;
columnsWithCustomSelect?: string[];
filterWithAI?: boolean;
buttonType?: "default" | "icon";
@@ -200,6 +214,7 @@ export function PopoverFilterBuilder({
align="start"
>
<FilterBuilderForm
+ columnIdentifier={columnIdentifier}
columns={columns}
filterState={wipFilterState}
onChange={setWipFilterState}
@@ -295,19 +310,24 @@ export function InlineFilterState({
});
}
+type ColumnIdentifier = "id" | "name";
+
export function InlineFilterBuilder({
columns,
filterState,
onChange,
+ columnIdentifier = "name",
disabled,
columnsWithCustomSelect,
filterWithAI = false,
}: {
- columns: ColumnDefinition[];
+ columns: ColumnDefinitionWithAlert[];
filterState: FilterState;
onChange:
| Dispatch<SetStateAction<FilterState>>
| ((newState: FilterState) => void);
+ /** Which column field to persist in filter.column: 'id' for stable refs, 'name' for legacy compatibility */
+ columnIdentifier?: ColumnIdentifier;
disabled?: boolean;
columnsWithCustomSelect?: string[];
filterWithAI?: boolean;
@@ -344,6 +364,7 @@ export function InlineFilterBuilder({
return (
<div className="flex flex-col">
<FilterBuilderForm
+ columnIdentifier={columnIdentifier}
columns={columns}
filterState={wipFilterState}
onChange={setWipFilterState}
@@ -363,7 +384,30 @@ const getOperator = (
: undefined;
};
+/**
+ * Returns severity-based styling classes for alert icons and tooltips
+ */
+const getAlertStyles = (severity: "info" | "warning" | "error") => {
+ const styles = {
+ error: {
+ iconColor: "text-red-600",
+ tooltipBg: "bg-red-50 dark:bg-red-950",
+ },
+ info: {
+ iconColor: "text-blue-600",
+ tooltipBg: "bg-blue-50 dark:bg-blue-950",
+ },
+ warning: {
+ iconColor: "text-amber-600",
+ tooltipBg: "bg-amber-50 dark:bg-amber-950",
+ },
+ };
+
+ return styles[severity];
+};
+
function FilterBuilderForm({
+ columnIdentifier,
columns,
filterState,
onChange,
@@ -371,7 +415,8 @@ function FilterBuilderForm({
columnsWithCustomSelect = [],
filterWithAI = false,
}: {
- columns: ColumnDefinition[];
+ columnIdentifier: ColumnIdentifier;
+ columns: ColumnDefinitionWithAlert[];
filterState: WipFilterState;
onChange: Dispatch<SetStateAction<WipFilterState>>;
disabled?: boolean;
@@ -590,44 +635,73 @@ function FilterBuilderForm({
No options found.
</InputCommandEmpty>
<InputCommandGroup>
- {columns.map((option) => (
- <InputCommandItem
- key={option.id}
- value={option.id}
- onSelect={(value) => {
- const col = columns.find(
- (c) => c.id === value,
- );
- const defaultOperator = col?.type
- ? getOperator(col.type)
- : undefined;
+ {columns.map((option) => {
+ const hasAlert = !!option.alert;
+ const severity =
+ option.alert?.severity ?? "warning";
+ const alertStyles = getAlertStyles(severity);
- handleFilterChange(
- {
- column: col?.name,
- type: col?.type,
- operator: defaultOperator,
- value: undefined,
- key:
- col?.type === "positionInTrace"
- ? "last"
- : undefined,
- } as WipFilterCondition,
- i,
- );
- }}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- option.id === column?.id
- ? "visible"
- : "invisible",
+ return (
+ <InputCommandItem
+ key={option.id}
+ value={option.id}
+ onSelect={(value) => {
+ const col = columns.find(
+ (c) => c.id === value,
+ );
+ const defaultOperator = col?.type
+ ? getOperator(col.type)
+ : undefined;
+
+ handleFilterChange(
+ {
+ column: col?.[columnIdentifier],
+ type: col?.type,
+ operator: defaultOperator,
+ value: undefined,
+ key:
+ col?.type === "positionInTrace"
+ ? "last"
+ : undefined,
+ } as WipFilterCondition,
+ i,
+ );
+ }}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ option.id === column?.id
+ ? "visible"
+ : "invisible",
+ )}
+ />
+ <span className="flex-1">
+ {option.name}
+ </span>
+ {hasAlert && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info
+ className={cn(
+ "ml-2 h-4 w-4",
+ alertStyles.iconColor,
+ )}
+ />
+ </TooltipTrigger>
+ <TooltipContent
+ className={cn(
+ "max-w-xs",
+ alertStyles.tooltipBg,
+ )}
+ >
+ {option.alert?.content}
+ </TooltipContent>
+ </Tooltip>
)}
- />
- {option.name}
- </InputCommandItem>
- ))}
+ </InputCommandItem>
+ );
+ })}
</InputCommandGroup>
</InputCommandList>
</InputCommand>
diff --git a/web/src/pages/project/[projectId]/evals/remap.tsx b/web/src/pages/project/[projectId]/evals/remap.tsx
new file mode 100644
index 0000000000..76b5c705d5
--- /dev/null
+++ b/web/src/pages/project/[projectId]/evals/remap.tsx
@@ -0,0 +1 @@
+export { default as default } from "@/src/features/evals/pages/remap-evaluator";
diff --git a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
index 16c30f5bcf..70043dce6f 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts
@@ -1,58 +1,62 @@
import { describe, it, expect } from "vitest";
import { extractObservationVariables } from "../extractObservationVariables";
import { type ObservationForEval } from "../types";
-import { type ObservationVariableMapping } from "@langfuse/shared";
+import {
+ availableObservationEvalVariableColumns,
+ ObservationEvalVariableColumn,
+ type ObservationVariableMapping,
+} from "@langfuse/shared";
describe("extractObservationVariables", () => {
const mockObservation: ObservationForEval = {
// Core identifiers
- id: "obs-123",
- traceId: "trace-456",
- projectId: "project-789",
- parentObservationId: null,
+ span_id: "obs-123",
+ trace_id: "trace-456",
+ project_id: "project-789",
+ parent_span_id: null,
// Observation properties
- type: "generation",
+ type: "GENERATION",
name: "chat-completion",
environment: "production",
level: "DEFAULT",
- statusMessage: null,
+ status_message: null,
version: "v1.0",
// Trace-level properties
- traceName: "my-trace",
- userId: "user-abc",
- sessionId: "session-xyz",
+ trace_name: "my-trace",
+ user_id: "user-abc",
+ session_id: "session-xyz",
tags: ["tag1", "tag2"],
release: "v2.0.0",
// Model properties
- model: "gpt-4",
- modelParameters: '{"temperature": 0.7}',
+ provided_model_name: "gpt-4",
+ model_parameters: '{"temperature": 0.7}',
// Prompt properties
- promptId: null,
- promptName: null,
- promptVersion: null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
// Tool call properties
- toolDefinitions: { search: '{"description": "Search the web"}' },
- toolCalls: ['{"name": "search", "args": {"query": "test"}}'],
- toolCallNames: ["search"],
+ tool_definitions: { search: '{"description": "Search the web"}' },
+ tool_calls: ['{"name": "search", "args": {"query": "test"}}'],
+ tool_call_names: ["search"],
// Usage & Cost
- usageDetails: { input: 100, output: 50 },
- costDetails: {},
- providedUsageDetails: {},
- providedCostDetails: {},
+ usage_details: { input: 100, output: 50 },
+ cost_details: {},
+ provided_usage_details: {},
+ provided_cost_details: {},
// Experiment properties
- experimentId: null,
- experimentName: null,
- experimentDescription: null,
- experimentDatasetId: null,
- experimentItemId: null,
- experimentItemExpectedOutput: "expected response",
+ experiment_id: null,
+ experiment_name: null,
+ experiment_description: null,
+ experiment_dataset_id: null,
+ experiment_item_id: null,
+ experiment_item_expected_output: "expected response",
// Data fields
input: JSON.stringify({
@@ -72,10 +76,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "input", selectedColumnId: "input" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("input");
@@ -87,10 +94,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "output", selectedColumnId: "output" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("output");
@@ -102,10 +112,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "meta", selectedColumnId: "metadata" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("meta");
@@ -119,10 +132,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "metadata", selectedColumnId: "metadata" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(3);
expect(result[0].var).toBe("userInput");
@@ -139,14 +155,17 @@ describe("extractObservationVariables", () => {
{ templateVariable: "tools", selectedColumnId: "toolCalls" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("tools");
- expect(result[0].value).toBe(JSON.stringify(mockObservation.toolCalls));
+ expect(result[0].value).toBe(JSON.stringify(mockObservation.tool_calls));
});
it("should extract toolDefinitions variable", () => {
@@ -157,15 +176,18 @@ describe("extractObservationVariables", () => {
},
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("definitions");
expect(result[0].value).toBe(
- JSON.stringify(mockObservation.toolDefinitions),
+ JSON.stringify(mockObservation.tool_definitions),
);
});
});
@@ -173,13 +195,19 @@ describe("extractObservationVariables", () => {
describe("model extraction", () => {
it("should extract model variable", () => {
const variableMapping: ObservationVariableMapping[] = [
- { templateVariable: "modelName", selectedColumnId: "model" },
+ {
+ templateVariable: "modelName",
+ selectedColumnId: "providedModelName",
+ },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("modelName");
@@ -191,14 +219,17 @@ describe("extractObservationVariables", () => {
{ templateVariable: "params", selectedColumnId: "modelParameters" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("params");
- expect(result[0].value).toBe(mockObservation.modelParameters);
+ expect(result[0].value).toBe(mockObservation.model_parameters);
});
});
@@ -228,15 +259,18 @@ describe("extractObservationVariables", () => {
{ templateVariable: "usage", selectedColumnId: "usageDetails" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("usage");
expect(result[0].value).toBe(
- JSON.stringify(mockObservation.usageDetails),
+ JSON.stringify(mockObservation.usage_details),
);
});
@@ -245,14 +279,19 @@ describe("extractObservationVariables", () => {
{ templateVariable: "cost", selectedColumnId: "costDetails" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result).toHaveLength(1);
expect(result[0].var).toBe("cost");
- expect(result[0].value).toBe(JSON.stringify(mockObservation.costDetails));
+ expect(result[0].value).toBe(
+ JSON.stringify(mockObservation.cost_details),
+ );
});
});
@@ -284,10 +323,13 @@ describe("extractObservationVariables", () => {
},
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result[0].value).toBe(JSON.stringify(["I am fine, thank you!"]));
});
@@ -349,10 +391,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "output", selectedColumnId: "output" },
];
- const result = extractObservationVariables({
- observation: observationWithNulls,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: observationWithNulls,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result[0].value).toBe("");
expect(result[1].value).toBe("");
@@ -367,10 +412,13 @@ describe("extractObservationVariables", () => {
},
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
// JSONPath returns empty array for non-matching paths
expect(result[0].value).toBe("[]");
@@ -390,10 +438,13 @@ describe("extractObservationVariables", () => {
},
];
- const result = extractObservationVariables({
- observation: observationWithPlainText,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: observationWithPlainText,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
// Should fall back to original value when JSON parsing fails
expect(result[0].value).toBe("plain text, not JSON");
@@ -406,10 +457,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "var", selectedColumnId: "input" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result[0].value).toBe(mockObservation.input);
});
@@ -419,10 +473,13 @@ describe("extractObservationVariables", () => {
{ templateVariable: "var", selectedColumnId: "output" },
];
- const result = extractObservationVariables({
- observation: mockObservation,
- variableMapping,
- });
+ const result = extractObservationVariables(
+ {
+ observation: mockObservation,
+ variableMapping,
+ },
+ availableObservationEvalVariableColumns as ObservationEvalVariableColumn[],
+ );
expect(result[0].value).toBe(mockObservation.output);
});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts b/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts
index f8977862c7..6fb0d09e8c 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/filterEvaluation.test.ts
@@ -763,7 +763,7 @@ describe("Filter Evaluation for Observation Evals", () => {
const matched = await testFilterMatch(observation, [
{
- column: "trace_name",
+ column: "traceName",
type: "string",
operator: "contains",
value: "query",
@@ -781,7 +781,7 @@ describe("Filter Evaluation for Observation Evals", () => {
const matched = await testFilterMatch(observation, [
{
- column: "user_id",
+ column: "userId",
type: "string",
operator: "=",
value: "user-123",
@@ -799,7 +799,7 @@ describe("Filter Evaluation for Observation Evals", () => {
const matched = await testFilterMatch(observation, [
{
- column: "session_id",
+ column: "sessionId",
type: "string",
operator: "=",
value: "session-abc",
@@ -808,24 +808,6 @@ describe("Filter Evaluation for Observation Evals", () => {
expect(matched).toBe(true);
});
-
- it("should filter by release", async () => {
- const observation = createTestObservation({
- project_id: projectId,
- release: "v2.0.0",
- });
-
- const matched = await testFilterMatch(observation, [
- {
- column: "release",
- type: "string",
- operator: "starts with",
- value: "v2",
- },
- ]);
-
- expect(matched).toBe(true);
- });
});
describe("experiment target object filtering", () => {
@@ -907,7 +889,7 @@ describe("Filter Evaluation for Observation Evals", () => {
// Filter that excludes this observation's dataset
const matched = await testExperimentFilterMatch(observation, [
{
- column: "experiment_dataset_id",
+ column: "experimentDatasetId",
type: "stringOptions",
operator: "any of",
value: ["dataset-456"], // Observation has dataset-123
@@ -930,7 +912,7 @@ describe("Filter Evaluation for Observation Evals", () => {
// Filter that includes this observation's dataset
const matched = await testExperimentFilterMatch(observation, [
{
- column: "experiment_dataset_id",
+ column: "experimentDatasetId",
type: "stringOptions",
operator: "any of",
value: ["dataset-123", "dataset-456"],
@@ -952,7 +934,7 @@ describe("Filter Evaluation for Observation Evals", () => {
// Filter matches the observation
const matched = await testExperimentFilterMatch(observation, [
{
- column: "experiment_dataset_id",
+ column: "experimentDatasetId",
type: "stringOptions",
operator: "any of",
value: ["dataset-123"],
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
index 9b92e67a8a..6563ca833b 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts
@@ -280,6 +280,7 @@ describe("Observation Eval E2E Pipeline", () => {
project_id: projectId,
type: "generation",
provided_model_name: "gpt-4",
+ trace_name: "llm-trace",
});
const config1 = createTestEvalConfig({
@@ -302,10 +303,10 @@ describe("Observation Eval E2E Pipeline", () => {
scoreName: "relevance",
filter: [
{
- column: "provided_model_name",
+ column: "traceName",
type: "stringOptions",
operator: "any of",
- value: ["gpt-4"],
+ value: ["llm-trace"],
},
],
});
@@ -455,7 +456,7 @@ describe("Observation Eval E2E Pipeline", () => {
{ templateVariable: "generated", selectedColumnId: "output" },
{
templateVariable: "expected",
- selectedColumnId: "experiment_item_expected_output",
+ selectedColumnId: "experimentItemExpectedOutput",
},
],
});
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
index 7ce05d31d7..f9ef9c3f65 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
@@ -240,9 +240,9 @@ describe("processObservationEval", () => {
evalTemplate: template,
});
const observation = createTestObservation({
- id: "obs-xyz",
- projectId,
- traceId: "trace-abc",
+ span_id: "obs-xyz",
+ project_id: projectId,
+ trace_id: "trace-abc",
environment: "production",
output: '{"response": "test output"}',
});
@@ -289,7 +289,7 @@ describe("processObservationEval", () => {
variableMapping: [],
});
const observation = createTestObservation({
- projectId,
+ project_id: projectId,
environment: undefined as unknown as string,
});
@@ -324,17 +324,12 @@ describe("processObservationEval", () => {
variableMapping: [
{ templateVariable: "input", selectedColumnId: "input" },
{ templateVariable: "output", selectedColumnId: "output" },
- {
- templateVariable: "model",
- selectedColumnId: "provided_model_name",
- },
],
});
const observation = createTestObservation({
project_id: projectId,
input: '{"prompt": "Hello"}',
output: '{"response": "World"}',
- provided_model_name: "gpt-4",
});
(prisma.jobExecution.findFirst as Mock).mockResolvedValue(job);
@@ -359,7 +354,6 @@ describe("processObservationEval", () => {
var: "output",
value: '{"response": "World"}',
}),
- expect.objectContaining({ var: "model", value: "gpt-4" }),
]),
}),
);
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts
index 5d0ef64ff9..8456f8c5b8 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationForEvalSchema.test.ts
@@ -4,6 +4,7 @@ import {
type ObservationForEval,
observationEvalFilterColumns,
observationEvalVariableColumns,
+ eventsEvalFilterColumns,
} from "@langfuse/shared";
describe("observationForEvalSchema", () => {
@@ -181,16 +182,16 @@ describe("observationForEvalSchema", () => {
});
describe("filter columns alignment", () => {
- it("should have all filter column IDs present in schema", () => {
+ it("should have all filter column internal mappings present in schema", () => {
const schemaKeys = Object.keys(observationForEvalSchema.shape);
for (const column of observationEvalFilterColumns) {
- expect(schemaKeys).toContain(column.id);
+ expect(schemaKeys).toContain(column.internal);
}
});
it("should include expected filter columns", () => {
- const columnIds = observationEvalFilterColumns.map((c) => c.id);
+ const columnIds = eventsEvalFilterColumns.map((c) => c.id);
// Observation properties
expect(columnIds).toContain("type");
@@ -199,14 +200,13 @@ describe("observationForEvalSchema", () => {
expect(columnIds).toContain("level");
expect(columnIds).toContain("version");
- // Trace-level properties (snake_case)
- expect(columnIds).toContain("trace_name");
- expect(columnIds).toContain("user_id");
- expect(columnIds).toContain("session_id");
+ // Trace-level properties
+ expect(columnIds).toContain("traceName");
+ expect(columnIds).toContain("userId");
+ expect(columnIds).toContain("sessionId");
expect(columnIds).toContain("tags");
- expect(columnIds).toContain("release");
- expect(columnIds).toContain("experiment_dataset_id");
+ expect(columnIds).toContain("experimentDatasetId");
// Metadata
expect(columnIds).toContain("metadata");
@@ -218,18 +218,20 @@ describe("observationForEvalSchema", () => {
const schemaKeys = Object.keys(observationForEvalSchema.shape);
for (const column of observationEvalVariableColumns) {
- expect(schemaKeys).toContain(column.id);
+ expect(schemaKeys).toContain(column.internal);
}
});
it("should include expected variable columns", () => {
- const columnIds = observationEvalVariableColumns.map((c) => c.id);
+ const columnInternals = observationEvalVariableColumns.map(
+ (c) => c.internal,
+ );
// Primary data fields
- expect(columnIds).toContain("input");
- expect(columnIds).toContain("output");
- expect(columnIds).toContain("metadata");
- expect(columnIds).toContain("experiment_item_expected_output");
+ expect(columnInternals).toContain("input");
+ expect(columnInternals).toContain("output");
+ expect(columnInternals).toContain("metadata");
+ expect(columnInternals).toContain("experiment_item_expected_output");
});
});
});
diff --git a/worker/src/features/evaluation/observationEval/extractObservationVariables.ts b/worker/src/features/evaluation/observationEval/extractObservationVariables.ts
index fe69c6334a..787b7fc489 100644
--- a/worker/src/features/evaluation/observationEval/extractObservationVariables.ts
+++ b/worker/src/features/evaluation/observationEval/extractObservationVariables.ts
@@ -1,5 +1,8 @@
import { type ObservationForEval } from "./types";
-import { type ObservationVariableMapping } from "@langfuse/shared";
+import {
+ observationEvalVariableColumns,
+ type ObservationVariableMapping,
+} from "@langfuse/shared";
import { JSONPath } from "jsonpath-plus";
import { logger } from "@langfuse/shared/src/server";
@@ -25,7 +28,7 @@ interface ExtractVariablesParams {
* 2. Optionally applies JSON selector if provided
* 3. Returns an array of extracted variables compatible with executeLLMAsJudgeEvaluation()
*
- * Column IDs are typed as keyof ObservationForEval (see observationEvalVariableColumns),
+ * Column internals are typed as keyof ObservationForEval (see observationEvalVariableColumns),
* ensuring compile-time safety when adding new columns.
*
* Note: Environment is passed directly to executeLLMAsJudgeEvaluation() by the caller,
@@ -33,14 +36,29 @@ interface ExtractVariablesParams {
*/
export function extractObservationVariables(
params: ExtractVariablesParams,
+ columns = observationEvalVariableColumns,
): ExtractedVariable[] {
const { observation, variableMapping } = params;
const variables: ExtractedVariable[] = [];
for (const mapping of variableMapping) {
// Direct property access - columnId is typed as keyof ObservationForEval
- const rawValue =
- observation[mapping.selectedColumnId as keyof ObservationForEval];
+ const internal = columns.find(
+ (col) => col.id === mapping.selectedColumnId,
+ )?.internal;
+
+ if (!internal) {
+ logger.info(
+ `No internal column found for variable ${mapping.templateVariable} and column ${mapping.selectedColumnId}`,
+ );
+ variables.push({
+ var: mapping.templateVariable,
+ value: "",
+ });
+ continue;
+ }
+
+ const rawValue = observation[internal];
const extractedValue = mapping.jsonSelector
? applyJsonSelector({ value: rawValue, selector: mapping.jsonSelector })
diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
index a3755b7a6f..df35de1176 100644
--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
@@ -9,6 +9,7 @@ import {
EvalTargetObject,
JobExecutionStatus,
type FilterState,
+ mapEventEvalFilterColumnIdToField,
} from "@langfuse/shared";
import { createW3CTraceId } from "../../utils";
@@ -163,13 +164,17 @@ function evaluateFilter(
!Array.isArray(filterConditions) ||
filterConditions.length === 0;
+ // Map filter column IDs to observation field values for in-memory filtering
+ const fieldMapper = (obs: ObservationForEval, column: string) =>
+ mapEventEvalFilterColumnIdToField(obs, column);
+
// Use InMemoryFilterService to evaluate filter if there are conditions
const isFilterMatch = isEmptyFilter
? true
: InMemoryFilterService.evaluateFilter(
observation,
filterConditions,
- (obs, columnId) => obs[columnId as keyof ObservationForEval],
+ fieldMapper,
);
// For experiment configs, must also match experiment root span