Skip to content

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

chore: Revert "feat(evals): single observation evals for prompt experiments" (#11845)

marliessophie116c63e9fa8e
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 4bf3e3124b..b5390a1ea8 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -31,40 +31,29 @@ const langfuseObject = z.enum(langfuseObjects);
export type LangfuseEvaluationObject = z.infer<typeof langfuseObject>;
// variable mapping stored in the db for eval templates
-// langfuseObject is optional - it's only needed for trace/dataset targets
-// For observation-based evals (EVENT, EXPERIMENT), the observation is already selected
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.
objectName: z.string().nullish(),
- langfuseObject: langfuseObject.optional(),
+ langfuseObject: langfuseObject,
selectedColumnId: z.string(),
jsonSelector: z.string().nullish(),
})
.refine(
- (value) =>
- // Only validate objectName if langfuseObject is provided and requires it
- !value.langfuseObject ||
- value.langfuseObject === "trace" ||
- value.langfuseObject === "dataset_item" ||
- value.objectName !== null,
+ (value) => value.langfuseObject === "trace" || value.objectName !== null,
{
- message:
- "objectName is required when langfuseObject is an observation type",
+ message: "objectName is required for langfuseObjects other than trace",
},
);
export const variableMappingList = z.array(variableMapping);
-// WIP version for forms - langfuseObject optional to support both:
-// - Trace/Dataset evals: Include langfuseObject and objectName to specify which observation
-// - Event/Experiment evals: Omit them since the observation is already selected
export const wipVariableMapping = z.object({
templateVariable: z.string(),
objectName: z.string().nullish(),
- langfuseObject: langfuseObject.optional(),
+ langfuseObject: langfuseObject,
selectedColumnId: z.string().nullish(),
jsonSelector: z.string().nullish(),
});
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 9dfe2d74ac..66d10c7ecc 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -27,7 +27,6 @@ export * from "./llm/utils";
export * from "./llm/types";
export * from "./llm/compileChatMessages";
export * from "./llm/testModelCall";
-export * from "./llm/getInternalTracingHandler";
export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
export * from "./utils/billingCycleHelpers";
diff --git a/packages/shared/src/server/llm/getInternalTracingHandler.ts b/packages/shared/src/server/llm/getInternalTracingHandler.ts
index 195efd3b82..cf7e9ecb09 100644
--- a/packages/shared/src/server/llm/getInternalTracingHandler.ts
+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts
@@ -1,77 +1,7 @@
import CallbackHandler from "langfuse-langchain";
-import { GenerationDetails, TraceSinkParams } from "./types";
+import { TraceSinkParams } from "./types";
import { processEventBatch } from "../ingestion/processEventBatch";
import { logger } from "../logger";
-import { traceException } from "../instrumentation";
-
-/**
- * Extracts and merges generation details from a list of processed events.
- * Handles multiple generation-create and generation-update events with the same id.
- *
- * Events are merged following the "last non-null value wins" pattern:
- * - generation-create events contain: id, name, input, metadata
- * - generation-update events contain: output, usage, usageDetails
- *
- * @returns GenerationDetails or null if no generation events found
- */
-export function extractGenerationDetails(
- processedEvents: Array<{ type: string; body: Record<string, unknown> }>,
-): GenerationDetails | null {
- // 1. Filter to only generation events
- const generationEvents = processedEvents.filter(
- (event) =>
- event.type === "generation-create" || event.type === "generation-update",
- );
-
- if (generationEvents.length === 0) {
- return null;
- }
-
- // 2. Get the generation id from first event
- const generationId = generationEvents[0].body.id as string;
- if (!generationId) {
- return null;
- }
-
- // 3. Filter to events for this generation id only
- const eventsForGeneration = generationEvents.filter(
- (event) => event.body.id === generationId,
- );
-
- // 4. Merge event bodies (last non-null/non-undefined value wins)
- // Similar to IngestionService pattern but simplified for our use case
- const mergedBody = eventsForGeneration.reduce(
- (acc: Record<string, unknown>, event) => {
- for (const [key, value] of Object.entries(event.body)) {
- if (value !== undefined && value !== null) {
- // Special handling for metadata: deep merge
- if (
- key === "metadata" &&
- typeof value === "object" &&
- !Array.isArray(value)
- ) {
- acc[key] = {
- ...((acc[key] as Record<string, unknown>) || {}),
- ...(value as Record<string, unknown>),
- };
- } else {
- acc[key] = value;
- }
- }
- }
- return acc;
- },
- { id: generationId },
- );
-
- return {
- observationId: generationId,
- name: (mergedBody.name as string) || "generation",
- input: mergedBody.input,
- output: mergedBody.output,
- metadata: (mergedBody.metadata as Record<string, unknown>) || {},
- };
-}
export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {
handler: CallbackHandler;
@@ -145,22 +75,6 @@ export function getInternalTracingHandler(traceSinkParams: TraceSinkParams): {
isLangfuseInternal: true,
},
);
-
- // Extract generation details and invoke callback (if provided)
- if (traceSinkParams.onGenerationComplete) {
- try {
- const generationDetails = extractGenerationDetails(processedEvents);
- if (generationDetails) {
- traceSinkParams.onGenerationComplete(generationDetails);
- }
- } catch (extractionError) {
- // Don't fail the LLM call due to generation detail extraction errors
- traceException(extractionError);
- logger.error("Failed to extract generation details from events", {
- error: extractionError,
- });
- }
- }
} catch (e) {
logger.error("Failed to process traced events", { error: e });
}
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 0016454e7d..2d6114651a 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -509,18 +509,6 @@ export enum LangfuseInternalTraceEnvironment {
LLMJudge = "langfuse-llm-as-a-judge",
}
-/**
- * Details of a generation extracted from traced events.
- * Used to pass generation information from internal tracing to callbacks.
- */
-export type GenerationDetails = {
- observationId: string;
- name: string;
- input: unknown;
- output: unknown;
- metadata: Record<string, unknown>;
-};
-
export type TraceSinkParams = {
/**
* IMPORTANT: This controls into what project the resulting traces are ingested.
@@ -536,9 +524,4 @@ export type TraceSinkParams = {
name: string;
version: number;
};
- /**
- * Optional callback invoked after the generation events have been processed.
- * Called with merged generation details (from create + update events).
- */
- onGenerationComplete?: (details: GenerationDetails) => void;
};
diff --git a/web/src/features/evals/components/inner-evaluator-form.tsx b/web/src/features/evals/components/inner-evaluator-form.tsx
index fbe1196a68..b05e76b399 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -27,7 +27,6 @@ import {
availableTraceEvalVariables,
datasetFormFilterColsWithOptions,
availableDatasetEvalVariables,
- observationEvalVariableColumns,
type ObservationType,
LangfuseInternalTraceEnvironment,
} from "@langfuse/shared";
@@ -35,11 +34,7 @@ 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,
- wipVariableMapping,
- variableMapping,
-} from "@langfuse/shared";
+import { type EvalTemplate, variableMapping } from "@langfuse/shared";
import { useRouter } from "next/router";
import { Slider } from "@/src/components/ui/slider";
import { Card } from "@/src/components/ui/card";
@@ -51,7 +46,6 @@ import { Checkbox } from "@/src/components/ui/checkbox";
import {
evalConfigFormSchema,
type EvalFormType,
- isLegacyEvalTarget,
isTraceOrDatasetObject,
isTraceTarget,
type LangfuseObject,
@@ -213,9 +207,9 @@ export const InnerEvaluatorForm = (props: {
: [],
mapping: props.existingEvaluator?.variableMapping
? z
- .array(wipVariableMapping)
+ .array(variableMapping)
.parse(props.existingEvaluator.variableMapping)
- : z.array(wipVariableMapping).parse(
+ : z.array(variableMapping).parse(
props.evalTemplate
? props.evalTemplate.vars.map((v) => ({
templateVariable: v,
@@ -893,18 +887,79 @@ export const InnerEvaluatorForm = (props: {
}
/>
</div>
- {isLegacyEvalTarget(form.watch("target")) ? (
- <>
- <FormField
- control={form.control}
- key={`${mappingField.id}-langfuseObject`}
- name={`mapping.${index}.langfuseObject`}
- render={({ field }) => (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-langfuseObject`}
+ name={`mapping.${index}.langfuseObject`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title="Object"
+ description={
+ "Langfuse object to retrieve the data from."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={props.disabled}
+ defaultValue={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ form.setValue(
+ `mapping.${index}.objectName`,
+ undefined,
+ );
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {availableVariables.map((evalObject) => (
+ <SelectItem
+ value={evalObject.id}
+ key={evalObject.id}
+ >
+ {evalObject.display}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+
+ {!isTraceOrDatasetObject(
+ form.watch(`mapping.${index}.langfuseObject`),
+ ) ? (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-objectName`}
+ name={`mapping.${index}.objectName`}
+ render={({ field }) => {
+ const type = String(
+ form.watch(`mapping.${index}.langfuseObject`),
+ ).toUpperCase() as ObservationType;
+ const nameOptions = Array.from(
+ observationTypeToNames.get(type) ?? [],
+ );
+ const isCustomOption =
+ field.value === "custom" ||
+ (field.value &&
+ !nameOptions.includes(field.value));
+ return (
<div className="flex items-center gap-2">
<VariableMappingDescription
- title="Object"
+ title={"Object Name"}
description={
- "Langfuse object to retrieve the data from."
+ "Name of the Langfuse object to retrieve the data from."
}
href={
"https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
@@ -912,338 +967,187 @@ export const InnerEvaluatorForm = (props: {
/>
<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>
- )}
- />
-
- {form.watch(`mapping.${index}.langfuseObject`) &&
- !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>
- ))}
+ {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="custom"
- value="custom"
+ key={name}
+ value={name}
>
- Enter name...
+ {name}
</SelectItem>
- </SelectContent>
- </Select>
- )}
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- );
- }}
- />
- ) : undefined}
-
- <FormField
- control={form.control}
- key={`${mappingField.id}-selectedColumnId`}
- name={`mapping.${index}.selectedColumnId`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"Object Variable"}
- description={
- "Variable on the Langfuse object to insert into the template."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Select
- disabled={props.disabled}
- defaultValue={field.value ?? undefined}
- onValueChange={(value) => {
- const availableColumns =
- availableVariables.find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )?.availableColumns;
-
- const column = availableColumns?.find(
- (column) => column.id === value,
- );
-
- field.onChange(column?.id);
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Object type" />
- </SelectTrigger>
- <SelectContent>
- {availableVariables
- .find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )
- ?.availableColumns.map((column) => (
+ ))}
<SelectItem
- value={column.id}
- key={column.id}
+ key="custom"
+ value="custom"
>
- {column.name}
+ Enter name...
</SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- {fieldHasJsonSelectorOption(
- form.watch(`mapping.${index}.selectedColumnId`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-jsonSelector`}
- name={`mapping.${index}.jsonSelector`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"JsonPath"}
- description={
- "Optional selection: Use JsonPath syntax to select from a JSON object stored on a trace. If not selected, we will pass the entire object into the prompt."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Input
+ </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}
- placeholder="Optional"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- ) : undefined}
- </>
- ) : (
- <>
- {/* Simplified UI for modern eval targets (EVENT, EXPERIMENT) */}
- <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 observation 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>
- {observationEvalVariableColumns.map(
- (column) => (
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {nameOptions?.map((name) => (
<SelectItem
- value={column.id}
- key={column.id}
+ key={name}
+ value={name}
>
- {column.name}
+ {name}
</SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
+ ))}
+ <SelectItem
+ key="custom"
+ value="custom"
+ >
+ Enter name...
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ )}
</FormControl>
<FormMessage />
</FormItem>
</div>
- )}
- />
- {fieldHasJsonSelectorOption(
- form.watch(`mapping.${index}.selectedColumnId`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-jsonSelector`}
- name={`mapping.${index}.jsonSelector`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"JsonPath"}
- description={
- "Optional selection: Use JsonPath syntax to select from a JSON object. 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}
+
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-selectedColumnId`}
+ name={`mapping.${index}.selectedColumnId`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"Object Variable"}
+ description={
+ "Variable on the Langfuse object to insert into the template."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
/>
- ) : undefined}
- </>
- )}
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={props.disabled}
+ defaultValue={field.value ?? undefined}
+ onValueChange={(value) => {
+ const availableColumns =
+ availableVariables.find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )?.availableColumns;
+
+ const column = availableColumns?.find(
+ (column) => column.id === value,
+ );
+
+ field.onChange(column?.id);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Object type" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableVariables
+ .find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )
+ ?.availableColumns.map((column) => (
+ <SelectItem
+ value={column.id}
+ key={column.id}
+ >
+ {column.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+ {fieldHasJsonSelectorOption(
+ form.watch(`mapping.${index}.selectedColumnId`),
+ ) ? (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-jsonSelector`}
+ name={`mapping.${index}.jsonSelector`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"JsonPath"}
+ description={
+ "Optional selection: Use JsonPath syntax to select from a JSON object stored on a trace. If not selected, we will pass the entire object into the prompt."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ disabled={props.disabled}
+ placeholder="Optional"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ )}
+ />
+ ) : undefined}
</Card>
))}
</div>
diff --git a/web/src/features/evals/components/template-selector.tsx b/web/src/features/evals/components/template-selector.tsx
index 834b8589dd..e86806a596 100644
--- a/web/src/features/evals/components/template-selector.tsx
+++ b/web/src/features/evals/components/template-selector.tsx
@@ -8,7 +8,6 @@ import {
AlertCircle,
ExternalLinkIcon,
} from "lucide-react";
-import { Badge } from "@/src/components/ui/badge";
import {
Popover,
PopoverContent,
@@ -45,7 +44,6 @@ type TemplateSelectorProps = {
disabled?: boolean;
activeTemplateIds?: string[];
inactiveTemplateIds?: string[];
- evaluatorTargetObjects?: Record<string, string>;
onConfigureTemplate?: (templateId: string) => void;
onSelectEvaluator?: (templateId: string) => void;
onEvaluatorToggled?: () => void;
@@ -58,7 +56,6 @@ export const TemplateSelector = ({
evalTemplates,
activeTemplateIds,
inactiveTemplateIds,
- evaluatorTargetObjects,
onConfigureTemplate,
onSelectEvaluator,
onEvaluatorToggled,
@@ -204,9 +201,6 @@ export const TemplateSelector = ({
latestTemplate.id,
);
const isInvalid = isTemplateInvalid(latestTemplate);
- const isLegacy =
- evaluatorTargetObjects?.[latestTemplate.id] ===
- "dataset";
return (
<InputCommandItem
@@ -222,11 +216,6 @@ export const TemplateSelector = ({
<div className="mr-2 h-4 w-4" />
)}
{name}
- {isLegacy && (
- <Badge variant="outline" className="ml-2 text-xs">
- legacy
- </Badge>
- )}
{isInvalid && (
<Tooltip>
<TooltipTrigger asChild>
@@ -293,9 +282,6 @@ export const TemplateSelector = ({
const isActive = isTemplateActive(latestTemplate.id);
const isInactive = isTemplateInactive(latestTemplate.id);
const isInvalid = isTemplateInvalid(latestTemplate);
- const isLegacy =
- evaluatorTargetObjects?.[latestTemplate.id] ===
- "dataset";
return (
<InputCommandItem
@@ -314,11 +300,6 @@ export const TemplateSelector = ({
<MaintainerTooltip
maintainer={getMaintainer(latestTemplate)}
/>
- {isLegacy && (
- <Badge variant="outline" className="ml-2 text-xs">
- legacy
- </Badge>
- )}
{isInvalid && (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index a71baf2411..72d8bc15ca 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -626,12 +626,7 @@ export const evalRouter = createTRPCRouter({
}),
jobConfigsByTarget: protectedProjectProcedure
- .input(
- z.object({
- projectId: z.string(),
- targetObject: z.array(z.string()),
- }),
- )
+ .input(z.object({ projectId: z.string(), targetObject: z.string() }))
.query(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -642,7 +637,7 @@ export const evalRouter = createTRPCRouter({
const evaluators = await ctx.prisma.jobConfiguration.findMany({
where: {
projectId: input.projectId,
- targetObject: { in: input.targetObject },
+ targetObject: input.targetObject,
},
include: {
evalTemplate: true,
diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.ts
index 311dc663d1..0d68488693 100644
--- a/web/src/features/evals/utils/evaluator-form-utils.ts
+++ b/web/src/features/evals/utils/evaluator-form-utils.ts
@@ -10,11 +10,6 @@ export const isTraceTarget = (target: string): boolean => target === "trace";
export const isTraceOrDatasetObject = (object: string): boolean =>
object === "trace" || object === "dataset_item";
-// Legacy eval targets (TRACE, DATASET) use full variable mapping UI with object selector
-// Modern eval targets (EVENT, EXPERIMENT) use simplified UI with just column selection
-export const isLegacyEvalTarget = (target: string): boolean =>
- target === "trace" || target === "dataset";
-
export const evalConfigFormSchema = z.object({
scoreName: z.string(),
target: z.string(),
diff --git a/web/src/features/experiments/components/MultiStepExperimentForm.tsx b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
index 70d7ab5e86..3a79b7cd6d 100644
--- a/web/src/features/experiments/components/MultiStepExperimentForm.tsx
+++ b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
@@ -132,7 +132,7 @@ export const MultiStepExperimentForm = ({
const datasetId = form.watch("datasetId");
const evaluators = api.evals.jobConfigsByTarget.useQuery(
- { projectId, targetObject: ["dataset", "experiment"] },
+ { projectId, targetObject: "dataset" },
{
enabled: hasEvalReadAccess && !!datasetId,
},
@@ -150,7 +150,6 @@ export const MultiStepExperimentForm = ({
const {
activeEvaluators,
pausedEvaluators,
- evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -242,8 +241,17 @@ export const MultiStepExperimentForm = ({
);
// Callback for preprocessing evaluator form values
- // For experiment evaluators, we only run on new data (not historic)
- const preprocessFormValues = (values: any) => values;
+ const preprocessFormValues = (values: any) => {
+ const shouldRunOnHistoric = confirm(
+ "Do you also want to execute this evaluator on historic data? If not, click cancel.",
+ );
+
+ if (shouldRunOnHistoric && !values.timeScope.includes("EXISTING")) {
+ values.timeScope = [...values.timeScope, "EXISTING"];
+ }
+
+ return values;
+ };
const onSubmit = async (data: CreateExperiment) => {
capture("dataset_run:new_form_submit");
@@ -384,7 +392,6 @@ export const MultiStepExperimentForm = ({
const evaluatorState = {
activeEvaluators,
pausedEvaluators,
- evaluatorTargetObjects,
evalTemplates: evalTemplates.data?.templates ?? [],
activeEvaluatorNames,
selectedEvaluatorData,
diff --git a/web/src/features/experiments/components/steps/EvaluatorsStep.tsx b/web/src/features/experiments/components/steps/EvaluatorsStep.tsx
index 6487e3aa89..bc3ffb70dd 100644
--- a/web/src/features/experiments/components/steps/EvaluatorsStep.tsx
+++ b/web/src/features/experiments/components/steps/EvaluatorsStep.tsx
@@ -21,7 +21,6 @@ export const EvaluatorsStep: React.FC<EvaluatorsStepProps> = ({
evalTemplates,
activeEvaluators,
pausedEvaluators,
- evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -51,7 +50,6 @@ export const EvaluatorsStep: React.FC<EvaluatorsStepProps> = ({
onEvaluatorToggled={handleEvaluatorToggled}
activeTemplateIds={activeEvaluators}
inactiveTemplateIds={pausedEvaluators}
- evaluatorTargetObjects={evaluatorTargetObjects}
disabled={!hasEvalWriteAccess}
/>
) : (
diff --git a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
index ed55429a93..2030c15a31 100644
--- a/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
+++ b/web/src/features/experiments/hooks/useEvaluatorDefaults.ts
@@ -1,10 +1,10 @@
import { Decimal } from "decimal.js";
import { type EvalTemplate, EvalTargetObject } from "@langfuse/shared";
-import { createDefaultObservationVariableMappings } from "../utils/evaluatorMappingUtils";
+import { createDefaultVariableMappings } from "../utils/evaluatorMappingUtils";
import { type PartialConfig } from "@/src/features/evals/types";
export const CONFIG_BASE = {
- targetObject: EvalTargetObject.EXPERIMENT,
+ targetObject: EvalTargetObject.DATASET,
sampling: new Decimal(1),
delay: 30000,
timeScope: ["NEW"],
@@ -23,22 +23,20 @@ export function useEvaluatorDefaults() {
datasetId: string,
scoreName?: string,
): PartialConfig & { evalTemplate: EvalTemplate } => {
- // Create variable mappings for experiment target (observation-based)
- const variableMappings = createDefaultObservationVariableMappings(template);
+ // Create variable mappings that alternate between dataset_item and trace
+ const alternatingMappings = createDefaultVariableMappings(template);
- // Return the configured evaluator for experiment target
+ // Return the configured evaluator
return {
...CONFIG_BASE,
evalTemplate: template,
scoreName: scoreName || template.name,
- variableMapping: variableMappings,
+ variableMapping: alternatingMappings,
filter: [
{
type: "stringOptions",
value: [datasetId],
- // Use the column id (not display name) for EXPERIMENT target
- // This maps to observation.experiment_dataset_id in the filter service
- column: "experiment_dataset_id",
+ column: "Dataset",
operator: "any of",
},
],
diff --git a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
index ccf9c9fb33..803c1ae051 100644
--- a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
+++ b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
@@ -7,11 +7,7 @@ import partition from "lodash/partition";
const partitionEvaluators = (
evaluators: RouterOutputs["evals"]["jobConfigsByTarget"] | undefined,
datasetId: string,
-): {
- activeEvaluators: string[];
- pausedEvaluators: string[];
- evaluatorTargetObjects: Record<string, string>;
-} => {
+): { activeEvaluators: string[]; pausedEvaluators: string[] } => {
const filteredEvaluators =
evaluators?.filter(({ filter }) => {
if (filter?.length === 0) return true;
@@ -33,16 +29,9 @@ const partitionEvaluators = (
(evaluator) => evaluator.evalTemplateId,
);
- // Build a map of template ID to target object for displaying legacy badges
- const evaluatorTargetObjects: Record<string, string> = {};
- for (const evaluator of filteredEvaluators) {
- evaluatorTargetObjects[evaluator.evalTemplateId] = evaluator.targetObject;
- }
-
return {
activeEvaluators: activeIds,
pausedEvaluators: inactiveIds,
- evaluatorTargetObjects,
};
};
@@ -162,10 +151,9 @@ export function useExperimentEvaluatorData({
[prepareEvaluatorData],
);
- const { activeEvaluators, pausedEvaluators, evaluatorTargetObjects } =
- useMemo(() => {
- return partitionEvaluators(evaluatorsData, datasetId);
- }, [evaluatorsData, datasetId]);
+ const { activeEvaluators, pausedEvaluators } = useMemo(() => {
+ return partitionEvaluators(evaluatorsData, datasetId);
+ }, [evaluatorsData, datasetId]);
return {
// State
@@ -173,7 +161,6 @@ export function useExperimentEvaluatorData({
showEvaluatorForm,
activeEvaluators,
pausedEvaluators,
- evaluatorTargetObjects,
// Handlers
handleConfigureEvaluator,
diff --git a/web/src/features/experiments/types/stepProps.ts b/web/src/features/experiments/types/stepProps.ts
index f6cf26f970..a4404230d6 100644
--- a/web/src/features/experiments/types/stepProps.ts
+++ b/web/src/features/experiments/types/stepProps.ts
@@ -78,7 +78,6 @@ export type DatasetState = {
export type EvaluatorState = {
activeEvaluators: string[];
pausedEvaluators: string[];
- evaluatorTargetObjects: Record<string, string>;
evalTemplates: EvalTemplate[];
activeEvaluatorNames: string[];
selectedEvaluatorData: EvaluatorData | null;
diff --git a/web/src/features/experiments/utils/evaluatorMappingUtils.ts b/web/src/features/experiments/utils/evaluatorMappingUtils.ts
index 53cbea6c5f..5f9da10843 100644
--- a/web/src/features/experiments/utils/evaluatorMappingUtils.ts
+++ b/web/src/features/experiments/utils/evaluatorMappingUtils.ts
@@ -1,7 +1,4 @@
-import {
- type EvalTemplate,
- type ObservationVariableMapping,
-} from "@langfuse/shared";
+import { type EvalTemplate } from "@langfuse/shared";
// Define the type locally to match what's in @langfuse/shared
type VariableMapping = {
@@ -40,29 +37,6 @@ const defaultMappings = new Map<string, Partial<VariableMapping>>([
],
]);
-// Default mappings for observation-based evaluators (event/experiment)
-const observationDefaultMappings = new Map<
- string,
- { selectedColumnId: string; jsonSelector?: string }
->([
- // 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.
*
@@ -94,38 +68,6 @@ 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).
- * Unlike trace/dataset evals, these don't need langfuseObject or objectName since
- * the observation is already selected - we only need to specify which column to use.
- *
- * @param template - The evaluation template containing variables
- * @returns Array of observation variable mappings (simplified, no langfuseObject/objectName)
- */
-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(),
- );
-
- return {
- templateVariable: variable,
- selectedColumnId:
- defaultMapping?.selectedColumnId || "experiment_item_expected_output",
- jsonSelector: defaultMapping?.jsonSelector,
};
});
}
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
index d2037ecb61..2fcf33fb3b 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/index.tsx
@@ -110,7 +110,7 @@ export default function Dataset() {
});
const evaluators = api.evals.jobConfigsByTarget.useQuery(
- { projectId, targetObject: ["dataset", "experiment"] },
+ { projectId, targetObject: "dataset" },
{
enabled: hasEvalReadAccess && !!datasetId,
},
@@ -121,7 +121,6 @@ export default function Dataset() {
const {
activeEvaluators,
pausedEvaluators,
- evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -136,9 +135,20 @@ export default function Dataset() {
refetchEvaluators: evaluators.refetch,
});
- // Callback for preprocessing evaluator form values
- // For experiment evaluators, we only run on new data (not historic)
- const preprocessFormValues = useCallback((values: any) => values, []);
+ // This function will be passed to the EvaluatorForm to modify form values before submission
+ const preprocessFormValues = useCallback((values: any) => {
+ // Ask the user if they want to run on historic data
+ const shouldRunOnHistoric = confirm(
+ "Do you also want to execute this evaluator on historic data? If not, click cancel.",
+ );
+
+ // If the user confirms, include EXISTING in the timeScope
+ if (shouldRunOnHistoric && !values.timeScope.includes("EXISTING")) {
+ values.timeScope = [...values.timeScope, "EXISTING"];
+ }
+
+ return values;
+ }, []);
const datasetName = dataset.data?.name ?? "";
const segments = datasetName.split("/").filter((s) => s.trim());
@@ -205,7 +215,6 @@ export default function Dataset() {
onSelectEvaluator={handleSelectEvaluator}
activeTemplateIds={activeEvaluators}
inactiveTemplateIds={pausedEvaluators}
- evaluatorTargetObjects={evaluatorTargetObjects}
disabled={!hasEvalWriteAccess}
/>
</div>
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 2de730b6e6..dd869cb71f 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -1074,10 +1074,7 @@ export async function extractVariablesFromTracingData({
.filter((obj) => obj.id !== "trace") // trace is handled separately above
.map((obj) => obj.id);
- if (
- mapping.langfuseObject &&
- observationTypes.includes(mapping.langfuseObject)
- ) {
+ if (observationTypes.includes(mapping.langfuseObject)) {
const safeInternalColumn = availableTraceEvalVariables
.find((o) => o.id === mapping.langfuseObject)
?.availableColumns.find((col) => col.id === mapping.selectedColumnId);
diff --git a/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts b/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
deleted file mode 100644
index 07acfd1492..0000000000
--- a/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
+++ /dev/null
@@ -1,569 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
-import {
- extractGenerationDetails,
- LangfuseInternalTraceEnvironment,
- type GenerationDetails,
-} from "@langfuse/shared/src/server";
-import type { ObservationForEval } from "../../evaluation/observationEval";
-
-// Real events captured from an experiment run
-// These events show the pattern: multiple generation-create and generation-update events with the same id
-const realExperimentEvents = [
- {
- id: "669353e4-e6a5-451e-9eab-1b33c9e396d5",
- type: "trace-create",
- timestamp: "2026-01-31T06:58:02.221Z",
- body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
- timestamp: "2026-01-31T06:58:02.218Z",
- environment: "langfuse-prompt-experiment",
- name: "dataset-run-item-008e4",
- metadata: {
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- },
- input: [
- {
- content: "You are a euro capital guesser.",
- role: "system",
- },
- {
- content: "What is the capital of Germany?",
- role: "user",
- },
- ],
- },
- },
- {
- id: "632bcb55-2130-4b67-8a00-575106ab979e",
- type: "span-create",
- timestamp: "2026-01-31T06:58:02.221Z",
- body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
- startTime: "2026-01-31T06:58:02.218Z",
- environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- name: "dataset-run-item-008e4",
- metadata: {
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- },
- input: [
- {
- content: "You are a euro capital guesser.",
- role: "system",
- },
- {
- content: "What is the capital of Germany?",
- role: "user",
- },
- ],
- },
- },
- {
- id: "423fb5f6-1aa2-4285-ac05-03801ce32def",
- type: "generation-create",
- timestamp: "2026-01-31T06:58:02.222Z",
- body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
- startTime: "2026-01-31T06:58:02.220Z",
- environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- name: "ChatOpenAI",
- metadata: {
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
- },
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- input: [
- {
- content: "You are a euro capital guesser.",
- role: "system",
- },
- {
- content: "What is the capital of Germany?",
- role: "user",
- },
- ],
- model: "gpt-4.1",
- modelParameters: {},
- },
- },
- {
- id: "89688bd4-ec5c-4df3-830d-1588c6faa189",
- type: "generation-create",
- timestamp: "2026-01-31T06:58:02.230Z",
- body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
- startTime: "2026-01-31T06:58:02.220Z",
- environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- name: "ChatOpenAI",
- metadata: {
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
- },
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- input: [
- {
- content: "You are a euro capital guesser.",
- role: "system",
- },
- {
- content: "What is the capital of Germany?",
- role: "user",
- },
- ],
- model: "gpt-4.1",
- modelParameters: {},
- },
- },
- {
- id: "a7ec0f62-7e7b-4ed7-a179-099e588e4f88",
- type: "generation-update",
- timestamp: "2026-01-31T06:58:03.708Z",
- body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
- model: "gpt-4.1-2025-04-14",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- output: {
- content: "The capital of Germany is Berlin.",
- role: "assistant",
- },
- endTime: "2026-01-31T06:58:03.707Z",
- usage: {
- input: 26,
- output: 7,
- total: 33,
- input_audio: 0,
- input_cache_read: 0,
- output_audio: 0,
- output_reasoning: 0,
- },
- usageDetails: {
- input: 26,
- output: 7,
- total: 33,
- input_audio: 0,
- input_cache_read: 0,
- output_audio: 0,
- output_reasoning: 0,
- },
- },
- },
- {
- id: "2ae04b82-00bc-4dcb-a838-3857b87d5a48",
- type: "generation-update",
- timestamp: "2026-01-31T06:58:03.708Z",
- body: {
- id: "d6f103ed-6ef6-4f83-a520-ab746e717360",
- model: "gpt-4.1-2025-04-14",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- output: {
- content: "The capital of Germany is Berlin.",
- role: "assistant",
- },
- endTime: "2026-01-31T06:58:03.707Z",
- usage: {
- input: 26,
- output: 7,
- total: 33,
- input_audio: 0,
- input_cache_read: 0,
- output_audio: 0,
- output_reasoning: 0,
- },
- usageDetails: {
- input: 26,
- output: 7,
- total: 33,
- input_audio: 0,
- input_cache_read: 0,
- output_audio: 0,
- output_reasoning: 0,
- },
- },
- },
- {
- id: "8439a06a-4879-4b39-8014-1966c6a9b54d",
- type: "span-create",
- timestamp: "2026-01-31T06:58:03.709Z",
- body: {
- id: "8bd2ff9f-1d45-4240-9581-45a7190c77fd",
- startTime: "2026-01-31T06:58:03.708Z",
- environment: "langfuse-prompt-experiment",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- parentObservationId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- name: "StrOutputParser",
- metadata: {
- tags: ["seq:step:2"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- },
- input: "The capital of Germany is Berlin.",
- },
- },
- {
- id: "de27a791-209f-4008-bc16-617eb59c9914",
- type: "span-update",
- timestamp: "2026-01-31T06:58:03.709Z",
- body: {
- id: "8bd2ff9f-1d45-4240-9581-45a7190c77fd",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- output: "The capital of Germany is Berlin.",
- endTime: "2026-01-31T06:58:03.709Z",
- },
- },
- {
- id: "98f391e0-b74d-46c5-ae73-5899215b7915",
- type: "span-update",
- timestamp: "2026-01-31T06:58:03.710Z",
- body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- output: "The capital of Germany is Berlin.",
- endTime: "2026-01-31T06:58:03.709Z",
- },
- },
- {
- id: "f86aecdf-9a52-4c37-8ef1-0f5ab450eab1",
- type: "trace-create",
- timestamp: "2026-01-31T06:58:03.710Z",
- body: {
- id: "4a56b6d74bbdffd08b9a2485f3315eeb",
- timestamp: "2026-01-31T06:58:03.709Z",
- environment: "langfuse-prompt-experiment",
- output: "The capital of Germany is Berlin.",
- tags: [],
- },
- },
-];
-
-describe("extractGenerationDetails", () => {
- it("should extract and merge generation details from real experiment events", () => {
- const result = extractGenerationDetails(realExperimentEvents);
-
- expect(result).not.toBeNull();
- expect(result!.observationId).toBe("d6f103ed-6ef6-4f83-a520-ab746e717360");
- expect(result!.name).toBe("ChatOpenAI");
-
- // Input should come from generation-create events
- expect(result!.input).toEqual([
- { content: "You are a euro capital guesser.", role: "system" },
- { content: "What is the capital of Germany?", role: "user" },
- ]);
-
- // Output should come from generation-update events
- expect(result!.output).toEqual({
- content: "The capital of Germany is Berlin.",
- role: "assistant",
- });
-
- // Metadata should be merged from all generation events
- expect(result!.metadata).toEqual({
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
- });
- });
-
- it("should return null when no generation events are present", () => {
- const nonGenerationEvents = realExperimentEvents.filter(
- (e) => !e.type.startsWith("generation"),
- );
-
- const result = extractGenerationDetails(nonGenerationEvents);
-
- expect(result).toBeNull();
- });
-
- it("should return null for empty events array", () => {
- const result = extractGenerationDetails([]);
-
- expect(result).toBeNull();
- });
-
- it("should handle events without generation id", () => {
- const eventsWithoutId = [
- {
- type: "generation-create",
- body: { name: "test" }, // No id field
- },
- ];
-
- const result = extractGenerationDetails(eventsWithoutId);
-
- expect(result).toBeNull();
- });
-
- it("should merge metadata from multiple generation events", () => {
- const eventsWithDifferentMetadata = [
- {
- type: "generation-create",
- body: {
- id: "gen-1",
- name: "test",
- metadata: { key1: "value1" },
- },
- },
- {
- type: "generation-update",
- body: {
- id: "gen-1",
- metadata: { key2: "value2" },
- },
- },
- ];
-
- const result = extractGenerationDetails(eventsWithDifferentMetadata);
-
- expect(result!.metadata).toEqual({
- key1: "value1",
- key2: "value2",
- });
- });
-
- it("should use default name when name is not provided", () => {
- const eventsWithoutName = [
- {
- type: "generation-create",
- body: {
- id: "gen-1",
- // No name field
- },
- },
- ];
-
- const result = extractGenerationDetails(eventsWithoutName);
-
- expect(result!.name).toBe("generation");
- });
-});
-
-describe("buildObservationForEval", () => {
- // Helper function that mirrors the logic in scheduleExperimentObservationEvals
- function buildObservationForEval(params: {
- projectId: string;
- traceId: string;
- generationDetails: GenerationDetails;
- config: {
- runId: string;
- experimentName?: string;
- prompt?: { name: string; version: number };
- };
- datasetItem: {
- id: string;
- datasetId: string;
- expectedOutput?: unknown;
- };
- }): ObservationForEval {
- const { projectId, traceId, generationDetails, config, datasetItem } =
- params;
-
- return {
- // Identifiers
- span_id: generationDetails.observationId,
- trace_id: traceId,
- project_id: projectId,
-
- // Core properties
- type: "GENERATION",
- name: generationDetails.name || "generation",
- environment: LangfuseInternalTraceEnvironment.PromptExperiments,
- level: "DEFAULT",
-
- // Prompt info
- prompt_name: config.prompt?.name,
- prompt_version: config.prompt?.version,
-
- // Experiment fields - critical for matching
- experiment_id: config.runId,
- experiment_name: config.experimentName,
- experiment_dataset_id: datasetItem.datasetId,
- experiment_item_id: datasetItem.id,
- experiment_item_expected_output: datasetItem.expectedOutput
- ? JSON.stringify(datasetItem.expectedOutput)
- : null,
- experiment_item_root_span_id: generationDetails.observationId, // Same as span_id for root
-
- // Data fields
- input: generationDetails.input,
- output: generationDetails.output,
- metadata: generationDetails.metadata,
-
- // Empty defaults
- tags: [],
- provided_usage_details: {},
- provided_cost_details: {},
- usage_details: {},
- cost_details: {},
- tool_definitions: {},
- tool_calls: [],
- tool_call_names: [],
- };
- }
-
- it("should build correct ObservationForEval from real experiment events", () => {
- // Extract generation details from real events
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- // Build ObservationForEval
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "4a56b6d74bbdffd08b9a2485f3315eeb",
- generationDetails,
- config: {
- runId: "run-456",
- experimentName: "Prompt Capital guesser-v1 on dataset countries",
- prompt: { name: "Capital guesser", version: 1 },
- },
- datasetItem: {
- id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- datasetId: "cml1yj2ag0001xsej1fcv6vz8",
- expectedOutput: { capital: "Berlin" },
- },
- });
-
- // Verify identifiers
- expect(observation.span_id).toBe("d6f103ed-6ef6-4f83-a520-ab746e717360");
- expect(observation.trace_id).toBe("4a56b6d74bbdffd08b9a2485f3315eeb");
- expect(observation.project_id).toBe("project-123");
-
- // Verify core properties
- expect(observation.type).toBe("GENERATION");
- expect(observation.name).toBe("ChatOpenAI");
- expect(observation.environment).toBe(
- LangfuseInternalTraceEnvironment.PromptExperiments,
- );
- expect(observation.level).toBe("DEFAULT");
-
- // Verify prompt info
- expect(observation.prompt_name).toBe("Capital guesser");
- expect(observation.prompt_version).toBe(1);
-
- // Verify experiment fields (critical for filter matching)
- expect(observation.experiment_id).toBe("run-456");
- expect(observation.experiment_name).toBe(
- "Prompt Capital guesser-v1 on dataset countries",
- );
- expect(observation.experiment_dataset_id).toBe("cml1yj2ag0001xsej1fcv6vz8");
- expect(observation.experiment_item_id).toBe(
- "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- );
- expect(observation.experiment_item_expected_output).toBe(
- JSON.stringify({ capital: "Berlin" }),
- );
- // Root span ID should equal span_id for experiment evals
- expect(observation.experiment_item_root_span_id).toBe(observation.span_id);
-
- // Verify data fields
- expect(observation.input).toEqual([
- { content: "You are a euro capital guesser.", role: "system" },
- { content: "What is the capital of Germany?", role: "user" },
- ]);
- expect(observation.output).toEqual({
- content: "The capital of Germany is Berlin.",
- role: "assistant",
- });
-
- // Verify metadata includes experiment context
- expect(observation.metadata).toEqual({
- tags: ["seq:step:1"],
- dataset_id: "cml1yj2ag0001xsej1fcv6vz8",
- dataset_item_id: "f0c467a1-539b-4e25-b41b-8db3ae399ef4",
- experiment_name: "Prompt Capital guesser-v1 on dataset countries",
- experiment_run_name:
- "Prompt Capital guesser-v1 on dataset countries - 2026-01-31T06:57:38.646Z",
- ls_provider: "openai",
- ls_model_name: "gpt-4.1",
- ls_model_type: "chat",
- });
- });
-
- it("should set experiment_item_root_span_id equal to span_id for root observations", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: { runId: "run-789" },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- },
- });
-
- // This is critical for experiment eval filter matching
- // The filter checks: span_id === experiment_item_root_span_id
- expect(observation.experiment_item_root_span_id).toBe(observation.span_id);
- });
-
- it("should handle missing expectedOutput gracefully", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: { runId: "run-789" },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- expectedOutput: undefined, // No expected output
- },
- });
-
- expect(observation.experiment_item_expected_output).toBeNull();
- });
-
- it("should handle missing prompt info gracefully", () => {
- const generationDetails = extractGenerationDetails(realExperimentEvents)!;
-
- const observation = buildObservationForEval({
- projectId: "project-123",
- traceId: "trace-456",
- generationDetails,
- config: {
- runId: "run-789",
- // No prompt provided
- },
- datasetItem: {
- id: "item-1",
- datasetId: "dataset-1",
- },
- });
-
- expect(observation.prompt_name).toBeUndefined();
- expect(observation.prompt_version).toBeUndefined();
- });
-});
diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.ts
index ac5c92215b..86a8cc3bda 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -6,7 +6,6 @@ import {
eventTypes,
ExperimentCreateEventSchema,
fetchLLMCompletion,
- GenerationDetails,
getDatasetItems,
IngestionEventType,
LangfuseInternalTraceEnvironment,
@@ -31,7 +30,6 @@ import {
} from "@langfuse/shared";
import { randomUUID } from "crypto";
import { createW3CTraceId } from "../utils";
-import { scheduleExperimentObservationEvals } from "./scheduleExperimentEvals";
async function getExistingRunItemDatasetItemIds(
projectId: string,
@@ -125,20 +123,6 @@ async function processItem(
if (!llmResult.success) return { success: false };
- /********************
- * SCHEDULE EXPERIMENT OBSERVATION EVALS *
- ********************/
-
- if (llmResult.generationDetails) {
- await scheduleExperimentObservationEvals({
- projectId,
- traceId: newTraceId,
- datasetItem,
- config,
- generationDetails: llmResult.generationDetails,
- });
- }
-
/********************
* ASYNC RUN ITEM EVAL *
********************/
@@ -167,7 +151,7 @@ async function processLLMCall(
traceId: string,
datasetItem: DatasetItemDomain & { input: Prisma.JsonObject },
config: PromptExperimentConfig,
-): Promise<{ success: boolean; generationDetails?: GenerationDetails }> {
+): Promise<{ success: boolean }> {
let messages: ChatMessage[] = [];
// Extract and replace variables in prompt
try {
@@ -185,8 +169,6 @@ async function processLLMCall(
return { success: false };
}
- let generationDetails: GenerationDetails | null = null;
-
const traceSinkParams: TraceSinkParams = {
environment: LangfuseInternalTraceEnvironment.PromptExperiments,
traceName: `dataset-run-item-${runItemId.slice(0, 5)}`,
@@ -200,9 +182,6 @@ async function processLLMCall(
experiment_run_name: config.experimentRunName,
},
prompt: config.prompt,
- onGenerationComplete: (details) => {
- generationDetails = details;
- },
};
await fetchLLMCompletion({
@@ -220,10 +199,7 @@ async function processLLMCall(
traceSinkParams,
}).catch(); // catch errors and do not retry
- return {
- success: true,
- generationDetails: generationDetails ?? undefined,
- };
+ return { success: true };
}
async function getItemsToProcess(
diff --git a/worker/src/features/experiments/scheduleExperimentEvals.ts b/worker/src/features/experiments/scheduleExperimentEvals.ts
deleted file mode 100644
index ccb3212cee..0000000000
--- a/worker/src/features/experiments/scheduleExperimentEvals.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { DatasetItemDomain } from "@langfuse/shared";
-import { PromptExperimentConfig } from "./utils";
-import {
- GenerationDetails,
- LangfuseInternalTraceEnvironment,
-} from "@langfuse/shared/src/server";
-import {
- fetchObservationEvalConfigs,
- scheduleObservationEvals,
- createObservationEvalSchedulerDeps,
- type ObservationForEval,
-} from "../evaluation/observationEval";
-import { logger, traceException } from "@langfuse/shared/src/server";
-
-interface ScheduleExperimentEvalsParams {
- projectId: string;
- traceId: string;
- datasetItem: DatasetItemDomain;
- config: PromptExperimentConfig;
- generationDetails: GenerationDetails;
-}
-
-/**
- * Schedule observation evals for an experiment generation.
- *
- * This function is called after an experiment LLM call completes to schedule
- * any configured observation-level evals. It mirrors the eval scheduling that
- * happens in the OTEL ingestion queue for externally-ingested observations.
- *
- * @param params.projectId - The project ID
- * @param params.traceId - The trace ID for the experiment run
- * @param params.datasetItem - The dataset item being evaluated
- * @param params.config - The prompt experiment configuration
- * @param params.generationDetails - The generation details extracted from traced events
- */
-export async function scheduleExperimentObservationEvals(
- params: ScheduleExperimentEvalsParams,
-): Promise<void> {
- const { projectId, traceId, datasetItem, config, generationDetails } = params;
-
- try {
- // 1. Fetch experiment-targeted eval configs
- const configs = await fetchObservationEvalConfigs(projectId);
- if (configs.length === 0) return;
-
- // 2. Build ObservationForEval with experiment context
- // Note: metadata from generation events contains additional context
- // (dataset_id, dataset_item_id, experiment_name, experiment_run_name, etc.)
- const observation: ObservationForEval = {
- // Identifiers
- span_id: generationDetails.observationId,
- trace_id: traceId,
- project_id: projectId,
-
- // Core properties
- type: "GENERATION",
- name: generationDetails.name || "generation",
- environment: LangfuseInternalTraceEnvironment.PromptExperiments,
- level: "DEFAULT",
-
- // Prompt info
- prompt_name: config.prompt?.name,
- prompt_version: config.prompt?.version,
-
- // Experiment fields - critical for matching
- experiment_id: config.runId,
- experiment_name: config.experimentName,
- experiment_dataset_id: datasetItem.datasetId,
- experiment_item_id: datasetItem.id,
- experiment_item_expected_output: datasetItem.expectedOutput
- ? JSON.stringify(datasetItem.expectedOutput)
- : null,
- experiment_item_root_span_id: generationDetails.observationId, // Same as span_id for root
-
- // Data fields
- input: generationDetails.input,
- output: generationDetails.output,
- metadata: generationDetails.metadata, // Include metadata from merged generation events
-
- // Empty defaults
- tags: [],
- provided_usage_details: {},
- provided_cost_details: {},
- usage_details: {},
- cost_details: {},
- tool_definitions: {},
- tool_calls: [],
- tool_call_names: [],
- };
-
- // 3. Schedule evals
- const schedulerDeps = createObservationEvalSchedulerDeps();
- await scheduleObservationEvals({
- observation,
- configs,
- schedulerDeps,
- });
-
- logger.info("Scheduled experiment observation evals", {
- projectId,
- traceId,
- observationId: generationDetails.observationId,
- configCount: configs.length,
- });
- } catch (error) {
- traceException(error);
- logger.error("Failed to schedule experiment observation evals", {
- error,
- projectId,
- traceId,
- });
- // Don't rethrow - eval scheduling should not fail the experiment
- }
-}