🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ui): add single observation evals (#11810)
marliessophiefa22296abd61
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.tsindex b5390a1ea8..221ce6488a 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)",},);diff --git a/web/src/components/table/peek/peek-evaluator-config-detail.tsx b/web/src/components/table/peek/peek-evaluator-config-detail.tsxindex 8575ae7d47..b69ce4e80d 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,7 @@ 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";export const PeekViewEvaluatorConfigDetail = ({projectId,@@ -75,6 +76,17 @@ export const PeekViewEvaluatorConfigDetail = ({/></div></div>++ {evalConfig &&+ evalConfig.targetObject &&+ 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/ui/callout.tsx b/web/src/components/ui/callout.tsxnew file mode 100644index 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.tsxindex 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.Descriptionref={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.tsxindex 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.tsxindex 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.Triggerref={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.tsxindex 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 (<textareaclassName={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.tsxindex 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.tsxnew file mode 100644index 0000000000..9732e3db84--- /dev/null+++ b/web/src/features/evals/components/eval-version-callout.tsx@@ -0,0 +1,154 @@+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 ≥ 4.4.0 or+ Python SDK ≥ 3.9.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: (+ <>+ 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/evaluator-form.tsx b/web/src/features/evals/components/evaluator-form.tsxindex 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.tsxindex 1b6db526a1..dd07ff080b 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-toimport { 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 { RemapEvalWizard } from "@/src/features/evals/components/remap-eval-wizard";export type EvaluatorDataRow = {id: string;@@ -78,8 +97,70 @@ export type EvaluatorDataRow = {logs?: string;actions?: string;totalCost?: number | null;+ isLegacy?: boolean;};+function LegacyBadgeCell({+ projectId,+ evalConfigId,+ status,+}: {+ projectId: string;+ evalConfigId: string;+ status: string;+}) {+ const [remapModalOpen, setRemapModalOpen] = useState(false);+ const utils = api.useUtils();++ 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>++ <RemapEvalWizard+ projectId={projectId}+ evalConfigId={evalConfigId}+ open={remapModalOpen}+ onOpenChange={setRemapModalOpen}+ onSuccess={() => {+ utils.evals.invalidate();+ }}+ />+ </>+ );+}+export default function EvaluatorTable({ projectId }: { projectId: string }) {const router = useRouter();const { setDetailPageList } = useDetailPageLists();@@ -151,6 +232,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 +353,39 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {enableSorting: true,size: 150,}),+ 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+ projectId={projectId}+ evalConfigId={row.row.original.id}+ 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 +513,7 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {: "Langfuse maintained": "Not available",totalCost: costData,+ isLegacy: isLegacyEvalTarget(jobConfig.targetObject),};};@@ -404,6 +523,32 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {defaultSidebarCollapsed={evaluatorFilterConfig.defaultSidebarCollapsed}><div className="flex h-full w-full flex-col">+ {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 "Legacy") 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 */}<DataTableToolbarcolumns={columns}diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsxindex b05e76b399..d52ea1eabe 100644--- a/web/src/features/evals/components/inner-evaluator-form.tsx+++ b/web/src/features/evals/components/inner-evaluator-form.tsx@@ -26,15 +26,24 @@ import {singleFilter,availableTraceEvalVariables,datasetFormFilterColsWithOptions,- availableDatasetEvalVariables,+ type availableDatasetEvalVariables,+ observationEvalVariableColumns,+ observationEvalFilterColumns,type ObservationType,LangfuseInternalTraceEnvironment,} 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";@@ -51,11 +60,10 @@ import {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 { VariableMappingDescription } from "@/src/features/evals/components/eval-form-descriptions";import { Suspense, lazy } from "react";import {getDateFromOption,@@ -64,19 +72,37 @@ import {import { useEvalConfigMappingData } from "@/src/features/evals/hooks/useEvalConfigMappingData";import { type PartialConfig } from "@/src/features/evals/types";import { Switch } from "@/src/components/ui/switch";+import { type EvalCapabilities } from "@/src/features/evals/hooks/useEvalCapabilities";import {EvaluationPromptPreview,getVariableColor,} from "@/src/features/evals/components/evaluation-prompt-preview";+import { EvalVersionCallout } from "@/src/features/evals/components/eval-version-callout";import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";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 {+ isEventTarget,+ isExperimentTarget,+ isLegacyEvalTarget,+} from "@/src/features/evals/utils/typeHelpers";+import {+ useUserFacingTarget,+ useEvaluatorTargetState,+} from "@/src/features/evals/hooks/useEvaluatorTarget";// Lazy load TracesTableconst TracesTable = lazy(@@ -128,6 +154,84 @@ const fieldHasJsonSelectorOption = (selectedColumnId === "metadata" ||selectedColumnId === "expected_output";+const propagationRequiredColumns = new Set([+ "release",+ "trace_name",+ "user_id",+ "session_id",+ "tags",+]);++/**+ * Converts observation filter columns to ColumnDefinition format and+ * augments with alerts for propagation-requiring columns when propagation is not available+ */+const getObservationFilterColumnsWithWarnings = (+ allowPropagationFilters: boolean,+): ColumnDefinitionWithAlert[] => {+ // Columns that require OTEL SDK with span propagation++ return observationEvalFilterColumns.map((col) => {+ // Convert to ColumnDefinition format+ let baseColumn: ColumnDefinitionWithAlert;++ if (col.type === "stringOptions" || col.type === "arrayOptions") {+ baseColumn = {+ ...col,+ internal: col.id,+ options: [], // Options will be populated at runtime if needed+ } as ColumnDefinitionWithAlert;+ } else {+ baseColumn = {+ ...col,+ internal: col.id,+ } as ColumnDefinitionWithAlert;+ }++ // Add alert if propagation is required but not available+ if (!allowPropagationFilters && propagationRequiredColumns.has(col.id)) {+ return {+ ...baseColumn,+ alert: {+ severity: "warning" as const,+ content: (+ <>+ This filter requires JS SDK ≥ 4.4.0 or Python SDK ≥ 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 baseColumn;+ });+};++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;+ }+};+const TracesPreview = memo(({projectId,@@ -185,12 +289,33 @@ 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;}) => {const [formError, setFormError] = useState<string | null>(null);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 targetState = useEvaluatorTargetState();const form = useForm({resolver: zodResolver(evalConfigFormSchema),@@ -198,23 +323,31 @@ export const InnerEvaluatorForm = (props: {defaultValues: {scoreName:props.existingEvaluator?.scoreName ?? `${props.evalTemplate.name}`,- target: props.existingEvaluator?.targetObject ?? "trace",+ target: props.existingEvaluator?.targetObject ?? EvalTargetObject.EVENT,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,})): [],),@@ -297,7 +430,7 @@ export const InnerEvaluatorForm = (props: {},);- const shouldFetch = !props.disabled && form.watch("target") === "trace";+ const shouldFetch = !props.disabled && isTraceTarget(form.watch("target"));const { observationTypeToNames, traceWithObservations, isLoading } =useEvalConfigMappingData(props.projectId, form, traceId, shouldFetch);@@ -312,9 +445,10 @@ export const InnerEvaluatorForm = (props: {}, [datasets.data]);useEffect(() => {- if (form.getValues("target") === "trace" && !props.disabled) {+ if (isTraceTarget(form.getValues("target")) && !props.disabled) {setShowPreview(true);- } else if (form.getValues("target") === "dataset") {+ } else {+ // For dataset, event, experiment targets, disable previewsetShowPreview(false);}// eslint-disable-next-line react-hooks/exhaustive-deps@@ -349,10 +483,10 @@ export const InnerEvaluatorForm = (props: {});const [availableVariables, setAvailableVariables] = useState<typeof availableTraceEvalVariables | typeof availableDatasetEvalVariables- >(- isTraceTarget(props.existingEvaluator?.targetObject ?? "trace")- ? availableTraceEvalVariables- : availableDatasetEvalVariables,+ >(() =>+ targetState.getAvailableVariables(+ props.existingEvaluator?.targetObject ?? EvalTargetObject.EVENT,+ ),);function onSubmit(values: z.infer<typeof evalConfigFormSchema>) {@@ -397,14 +531,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;}@@ -454,14 +589,13 @@ 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 && (+ {isTraceTarget(form.watch("target")) && !props.disabled && (<><span className="text-xs text-muted-foreground">Show Preview</span><Switch@@ -506,186 +640,325 @@ 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'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's target data may only be+ configured at creation.+ </span>+ </TooltipContent>+ </Tooltip>+ )}+ </FormLabel>+ <FormControl>+ <Tabs+ value={userFacingTarget}+ onValueChange={(value) => {+ const newUserFacingTarget = value as+ | "trace"+ | "event"+ | "offline-experiment";- <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"))+ if (newUserFacingTarget === userFacingTarget) {+ return;}- />- <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"++ // 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+ actualTarget = 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),+ );+ field.onChange(actualTarget);+ }}+ >+ <TabsList className="grid w-fit max-w-fit grid-flow-col">+ <TabsTrigger+ value="event"+ disabled={props.disabled || props.mode === "edit"}+ className="min-w-[100px]">- 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")}- />- ))}+ Live Observations [New]+ </TabsTrigger>+ {allowLegacy && (+ <TabsTrigger+ value="trace"+ disabled={props.disabled || props.mode === "edit"}+ className="min-w-[100px]"+ >+ Live Traces [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 */}+ {!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+ const actualTarget = 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 [Recommended]"}+ </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"}+ </TabsTrigger>+ </TabsList>+ </Tabs>+ {!props.disabled && (+ <FormDescription>+ Check with your technical team to see which version of the+ Langfuse SDK you are using.+ </FormDescription>+ )}+ </div>+ )}++ {!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>+ )}+ />)}- /><FormFieldcontrol={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)) {+ return getObservationFilterColumnsWithWarnings(+ allowPropagationFilters,+ );+ } else if (isTraceTarget(target)) {+ return tracesTableColsWithOptions(+ traceFilterOptions,+ evalTraceTableCols,+ );+ } else {+ // dataset or experiment+ return datasetFormFilterColsWithOptions(+ datasetFilterOptions,+ evalDatasetFormFilterCols,+ );+ }+ };++ 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,- )}+ columns={getFilterColumns()}filterState={field.value ?? []}onChange={(value: z.infer<typeof singleFilter>[],@@ -705,92 +978,75 @@ 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 && (+ {isTraceTarget(form.watch("target")) && !props.disabled && (<TracesPreviewprojectId={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>- )}- />-- <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>- )}- />+ {!props.hideAdvancedSettings && (+ <>+ <FormField+ control={form.control}+ name="sampling"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Sampling</FormLabel>+ <FormControl>+ <div className="max-w-[500px]">+ <Slider+ disabled={props.disabled}+ min={0}+ max={1}+ step={0.0001}+ value={[field.value]}+ onValueChange={(value) => field.onChange(value[0])}+ showInput={true}+ displayAsPercentage={true}+ />+ </div>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {isLegacyEvalTarget(form.watch("target")) && (+ <FormField+ control={form.control}+ name="delay"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Delay (seconds)</FormLabel>+ <FormControl>+ <Input {...field} type="number" min={0} />+ </FormControl>+ <FormDescription>+ Time between first Trace/Dataset run event and+ evaluation execution to ensure all data is available+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ </>+ )}</div></Card>)}@@ -798,7 +1054,7 @@ export const InnerEvaluatorForm = (props: {<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 && (+ {isTraceTarget(form.watch("target")) && !props.disabled && (<FormDescription>Preview of the evaluation prompt with the variables replaced withthe first matched trace data subject to the filters.@@ -824,13 +1080,13 @@ export const InnerEvaluatorForm = (props: {variableMapping={form.watch("mapping")}isLoading={isLoading}className={cn(- "min-h-48",+ "min-h-48 bg-muted/50",!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 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@@ -853,7 +1109,7 @@ export const InnerEvaluatorForm = (props: {title={"Evaluation Prompt"}json={props.evalTemplate.prompt ?? null}className={cn(- "min-h-48",+ "min-h-48 bg-muted/50",!props.shouldWrapVariables && "lg:w-2/3",)}codeClassName="flex-1"@@ -867,99 +1123,37 @@ export const InnerEvaluatorForm = (props: {!props.shouldWrapVariables && "lg:w-1/3",)}>- {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"+ {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}+ {"}}"}+ <DocPopupdescription={- "Langfuse object to retrieve the data from."+ "Variable in the template to be replaced with the mapped data."}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 (+ <FormField+ control={form.control}+ key={`${mappingField.id}-langfuseObject`}+ name={`mapping.${index}.langfuseObject`}+ render={({ field }) => (<div className="flex items-center gap-2"><VariableMappingDescription- title={"Object Name"}+ title="Object"description={- "Name of the Langfuse object to retrieve the data from."+ "Langfuse object to retrieve the data from."}href={"https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"@@ -967,189 +1161,398 @@ export const InnerEvaluatorForm = (props: {/><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>- ))}+ <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- key="custom"- value="custom"+ value={evalObject.id}+ key={evalObject.id}>- Enter name...+ {evalObject.display}</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) => (+ ),+ )}+ </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 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={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- key={name}- value={name}+ value={column.id}+ key={column.id}>- {name}+ {column.name}</SelectItem>))}- <SelectItem- key="custom"- value="custom"- >- Enter name...- </SelectItem>- </SelectContent>- </Select>- )}+ </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"}+ )}+ />+ {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>+ ))+ : // 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}+ {"}}"}+ <DocPopupdescription={- "Variable on the Langfuse object to insert into the template."+ "Variable in the template to be replaced with the mapped data."}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 }) => (+ {props.hideAdvancedSettings && (<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"- }+ title="Object"+ description="Type of object to retrieve the data from."+ 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 className="w-2/3">+ <Input+ value={+ isEventTarget(form.watch("target"))+ ? "Observation"+ : "Experiment item"+ }+ disabled+ />+ </div></div>)}- />- ) : undefined}- </Card>- ))}+ <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 !==+ "experiment_item_expected_output",+ )+ : 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={props.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`,+ ) === "experiment_item_expected_output") && (+ <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={props.disabled}+ placeholder="Optional"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ </div>+ )}+ />+ )}+ </Card>+ ))}</div></div><FormMessage />@@ -1161,12 +1564,17 @@ export const InnerEvaluatorForm = (props: {</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 ? (<Buttontype="submit"- loading={createJobMutation.isPending || updateJobMutation.isPending}+ loading={mutationIsLoading}className="mt-3 max-w-fit">{props.mode === "edit" ? "Update" : "Execute"}@@ -1181,27 +1589,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.tsxnew file mode 100644index 0000000000..b44efb19e3--- /dev/null+++ b/web/src/features/evals/components/legacy-eval-callout.tsx@@ -0,0 +1,74 @@+import { useState } from "react";+import { Callout } from "@/src/components/ui/callout";+import { Button } from "@/src/components/ui/button";+import Link from "next/link";+import { isLegacyEvalTarget } from "@/src/features/evals/utils/typeHelpers";+import { RemapEvalWizard } from "@/src/features/evals/components/remap-eval-wizard";+import { api } from "@/src/utils/api";++interface LegacyEvalCalloutProps {+ projectId: string;+ evalConfigId: string;+ targetObject: string;+}++export function LegacyEvalCallout({+ projectId,+ evalConfigId,+ targetObject,+}: LegacyEvalCalloutProps) {+ const [remapModalOpen, setRemapModalOpen] = useState(false);+ const utils = api.useUtils();++ 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={() => setRemapModalOpen(true)}+ 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>++ <RemapEvalWizard+ projectId={projectId}+ evalConfigId={evalConfigId}+ open={remapModalOpen}+ onOpenChange={setRemapModalOpen}+ onSuccess={() => {+ // Invalidate queries to refresh the table+ utils.evals.invalidate();+ }}+ />+ </>+ );+}diff --git a/web/src/features/evals/components/remap-eval-wizard.tsx b/web/src/features/evals/components/remap-eval-wizard.tsxnew file mode 100644index 0000000000..92826d99da--- /dev/null+++ b/web/src/features/evals/components/remap-eval-wizard.tsx@@ -0,0 +1,331 @@+import { useState, useMemo, useRef } from "react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { api } from "@/src/utils/api";+import { InnerEvaluatorForm } from "@/src/features/evals/components/inner-evaluator-form";+import {+ mapLegacyToModernTarget,+ isLegacyEvalTarget,+ isTraceTarget,+} 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";+import { useSynchronizedScroll } from "@/src/features/evals/hooks/useSynchronizedScroll";++interface RemapEvalWizardProps {+ projectId: string;+ evalConfigId: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onSuccess?: () => void;+}++type LegacyEvalAction = "keep-active" | "mark-inactive" | "delete";++export function RemapEvalWizard({+ projectId,+ evalConfigId,+ open,+ onOpenChange,+ onSuccess,+}: RemapEvalWizardProps) {+ const evalCapabilities = useEvalCapabilities(projectId);++ const [error, setError] = useState<string | null>(null);+ const [legacyAction, setLegacyAction] =+ useState<LegacyEvalAction>("mark-inactive");+ const leftScrollRef = useRef<HTMLDivElement>(null);+ const rightScrollRef = useRef<HTMLDivElement>(null);++ // Fetch old eval config+ const { data: oldConfig, isLoading: isLoadingConfig } =+ api.evals.configById.useQuery(+ { projectId, id: evalConfigId },+ { enabled: open },+ );++ // Fetch eval template+ const { data: evalTemplate, isLoading: isLoadingTemplate } =+ api.evals.templateById.useQuery(+ {+ projectId,+ id: oldConfig?.evalTemplateId ?? "",+ },+ { enabled: open && !!oldConfig?.evalTemplateId },+ );++ const utils = api.useUtils();++ // Update mutation to set old eval to INACTIVE+ const updateJobMutation = api.evals.updateEvalJob.useMutation({+ onSuccess: () => {+ utils.evals.invalidate();+ onOpenChange(false);+ onSuccess?.();+ },+ 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();+ onOpenChange(false);+ onSuccess?.();+ },+ 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]);++ // Validate that old config is actually legacy+ const isValidForRemapping = useMemo(() => {+ if (!oldConfig) return false;+ return isLegacyEvalTarget(oldConfig.targetObject);+ }, [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();+ onOpenChange(false);+ onSuccess?.();+ 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;++ // Synchronized scrolling between left (legacy) and right (new) config panels+ useSynchronizedScroll(leftScrollRef, rightScrollRef, [+ isLoading,+ oldConfig,+ evalTemplate,+ ]);++ if (!open) return null;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="flex h-[90vh] flex-col" size="xxl">+ <DialogHeader>+ <DialogTitle>Upgrade Evaluator</DialogTitle>+ <DialogDescription>+ 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.+ </DialogDescription>+ </DialogHeader>++ {isLoading ? (+ <div className="grid flex-1 grid-cols-2 gap-6 overflow-auto">+ <Skeleton className="h-full w-full" />+ <Skeleton className="h-full w-full" />+ </div>+ ) : !isValidForRemapping ? (+ <Alert variant="destructive">+ <AlertDescription>+ This eval configuration is not a legacy eval and does not need+ remapping.+ </AlertDescription>+ </Alert>+ ) : !oldConfig || !evalTemplate ? (+ <Alert variant="destructive">+ <AlertDescription>+ Failed to load eval configuration or template.+ </AlertDescription>+ </Alert>+ ) : (+ <div className="grid flex-1 grid-cols-[1fr_2px_1fr] overflow-hidden">+ {/* LEFT: Read-only old config */}+ <div className="flex flex-col space-y-4 overflow-hidden p-3">+ <div className="flex items-center gap-2 bg-background 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>+ <div ref={leftScrollRef} className="flex-1 overflow-auto">+ <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>+ </div>++ <Separator orientation="vertical" className="h-full" />++ {/* RIGHT: Editable new config form */}+ <div className="flex flex-col space-y-4 overflow-hidden p-3">+ <h3 className="bg-background pb-2 text-lg font-semibold">+ New Configuration{" "}+ {isTraceTarget(oldConfig.targetObject)+ ? "(runs on observations)"+ : ""}+ </h3>+ <div ref={rightScrollRef} className="flex-1 overflow-auto">+ <InnerEvaluatorForm+ projectId={projectId}+ evalTemplate={evalTemplate}+ useDialog={false}+ existingEvaluator={mappedConfig ?? undefined}+ onFormSuccess={handleFormSuccess}+ mode="create"+ hideTargetSection={false}+ hideTargetSelection={true}+ preventRedirect={true}+ hideAdvancedSettings={true}+ evalCapabilities={evalCapabilities}+ 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>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/features/evals/hooks/useEvalCapabilities.ts b/web/src/features/evals/hooks/useEvalCapabilities.tsnew file mode 100644index 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/useEvaluatorTarget.ts b/web/src/features/evals/hooks/useEvaluatorTarget.tsnew file mode 100644index 0000000000..e801ebc3e1--- /dev/null+++ b/web/src/features/evals/hooks/useEvaluatorTarget.ts@@ -0,0 +1,104 @@+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";++/**+ * 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 [userFacingTarget, setUserFacingTarget] = useState<+ "trace" | "event" | "offline-experiment"+ >("event");+ const [useOtelDataForExperiment, setUseOtelDataForExperiment] =+ useState(true);++ useEffect(() => {+ const currentTarget = targetObject ?? EvalTargetObject.EVENT;++ 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);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ 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/useSynchronizedScroll.ts b/web/src/features/evals/hooks/useSynchronizedScroll.tsnew file mode 100644index 0000000000..0ad7ebfbb1--- /dev/null+++ b/web/src/features/evals/hooks/useSynchronizedScroll.ts@@ -0,0 +1,52 @@+import { useEffect } from "react";++type ScrollableRef = { current: HTMLElement | null };++/**+ * Synchronizes vertical scrolling between two scrollable elements.+ * When either element scrolls, the other element's scroll position is updated to match.+ *+ * @param leftRef - Ref to the left scrollable element+ * @param rightRef - Ref to the right scrollable element+ * @param deps - Optional dependencies array for when to re-attach scroll listeners+ *+ * @example+ * ```tsx+ * const leftScrollRef = useRef<HTMLDivElement>(null);+ * const rightScrollRef = useRef<HTMLDivElement>(null);+ * useSynchronizedScroll(leftScrollRef, rightScrollRef);+ * ```+ */+export function useSynchronizedScroll(+ leftRef: ScrollableRef,+ rightRef: ScrollableRef,+ deps: unknown[] = [],+) {+ useEffect(() => {+ const leftDiv = leftRef.current;+ const rightDiv = rightRef.current;++ if (!leftDiv || !rightDiv) return;++ const handleLeftScroll = () => {+ if (rightDiv) {+ rightDiv.scrollTop = leftDiv.scrollTop;+ }+ };++ const handleRightScroll = () => {+ if (leftDiv) {+ leftDiv.scrollTop = rightDiv.scrollTop;+ }+ };++ leftDiv.addEventListener("scroll", handleLeftScroll);+ rightDiv.addEventListener("scroll", handleRightScroll);++ return () => {+ leftDiv.removeEventListener("scroll", handleLeftScroll);+ rightDiv.removeEventListener("scroll", handleRightScroll);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, deps);+}diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.tsindex 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 defaulttimeScope: 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.tsnew file mode 100644index 0000000000..d81b1ff9e1--- /dev/null+++ b/web/src/features/evals/utils/evaluator-constants.ts@@ -0,0 +1,18 @@+import { 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: col.id,+ name: col.name,+ ...(col.type ? { type: col.type } : {}),+ internal: `o."${col.id}"`,+ })),+ },+];diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.tsindex 0d68488693..741c10b95b 100644--- a/web/src/features/evals/utils/evaluator-form-utils.ts+++ b/web/src/features/evals/utils/evaluator-form-utils.ts@@ -3,12 +3,14 @@ import {singleFilter,type langfuseObjects,TimeScopeSchema,+ EvalTargetObject,} from "@langfuse/shared";import { wipVariableMapping } from "@langfuse/shared";-export const isTraceTarget = (target: string): boolean => target === "trace";+export const isTraceTarget = (target: string): boolean =>+ target === EvalTargetObject.TRACE;export const isTraceOrDatasetObject = (object: string): boolean =>- object === "trace" || object === "dataset_item";+ object === EvalTargetObject.TRACE || object === "dataset_item";export const evalConfigFormSchema = z.object({scoreName: z.string(),diff --git a/web/src/features/evals/utils/typeHelpers.ts b/web/src/features/evals/utils/typeHelpers.tsindex 6fe69e3f1e..ba3a1b4216 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,48 @@ 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 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.tsnew file mode 100644index 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/experiments/hooks/useEvaluatorDefaults.ts b/web/src/features/experiments/hooks/useEvaluatorDefaults.tsindex 2030c15a31..7e00512661 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 with langfuseObject (dataset evaluator schema)+ const variableMappings = createDefaultVariableMappings(template);- // Return the configured evaluator+ // Return the configured evaluator for dataset targetreturn {...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.tsindex 5f9da10843..5d321efa15 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: "experiment_item_expected_output" }],+ ["ground_truth", { selectedColumnId: "experiment_item_expected_output" }],+ ["reference", { selectedColumnId: "experiment_item_expected_output" }],+]);+/*** 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 || "experiment_item_expected_output",+ jsonSelector: defaultMapping.jsonSelector,+ };+ }++ return {+ templateVariable: variable,+ selectedColumnId: "experiment_item_expected_output",};});}diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsxindex 2ae255f4d6..8e7ba361a8 100644--- a/web/src/features/filters/components/filter-builder.tsx+++ b/web/src/features/filters/components/filter-builder.tsx@@ -56,6 +56,17 @@ 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 onChangeexport function PopoverFilterBuilder({columns,@@ -65,7 +76,7 @@ export function PopoverFilterBuilder({filterWithAI = false,buttonType = "default",}: {- columns: ColumnDefinition[];+ columns: ColumnDefinitionWithAlert[];filterState: FilterState;onChange:| Dispatch<SetStateAction<FilterState>>@@ -264,7 +275,7 @@ export function InlineFilterBuilder({columnsWithCustomSelect,filterWithAI = false,}: {- columns: ColumnDefinition[];+ columns: ColumnDefinitionWithAlert[];filterState: FilterState;onChange:| Dispatch<SetStateAction<FilterState>>@@ -324,6 +335,28 @@ 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({columns,filterState,@@ -332,7 +365,7 @@ function FilterBuilderForm({columnsWithCustomSelect = [],filterWithAI = false,}: {- columns: ColumnDefinition[];+ columns: ColumnDefinitionWithAlert[];filterState: WipFilterState;onChange: Dispatch<SetStateAction<WipFilterState>>;disabled?: boolean;@@ -551,41 +584,70 @@ 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: 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?.name,+ type: col?.type,+ operator: defaultOperator,+ value: undefined,+ key: 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>