Skip to content

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

feat(evals): single observation evals for prompt experiments (#11833)

Hassieb Pakzadafbcbaf9e90c
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index b5390a1ea8..4bf3e3124b 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -31,29 +31,40 @@ 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,
+ langfuseObject: langfuseObject.optional(),
selectedColumnId: z.string(),
jsonSelector: z.string().nullish(),
})
.refine(
- (value) => value.langfuseObject === "trace" || value.objectName !== null,
+ (value) =>
+ // Only validate objectName if langfuseObject is provided and requires it
+ !value.langfuseObject ||
+ value.langfuseObject === "trace" ||
+ value.langfuseObject === "dataset_item" ||
+ value.objectName !== null,
{
- message: "objectName is required for langfuseObjects other than trace",
+ message:
+ "objectName is required when langfuseObject is an observation type",
},
);
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,
+ langfuseObject: langfuseObject.optional(),
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 66d10c7ecc..9dfe2d74ac 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -27,6 +27,7 @@ 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 cf7e9ecb09..195efd3b82 100644
--- a/packages/shared/src/server/llm/getInternalTracingHandler.ts
+++ b/packages/shared/src/server/llm/getInternalTracingHandler.ts
@@ -1,7 +1,77 @@
import CallbackHandler from "langfuse-langchain";
-import { TraceSinkParams } from "./types";
+import { GenerationDetails, 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;
@@ -75,6 +145,22 @@ 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 2d6114651a..0016454e7d 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -509,6 +509,18 @@ 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.
@@ -524,4 +536,9 @@ 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 b05e76b399..fbe1196a68 100644
--- a/web/src/features/evals/components/inner-evaluator-form.tsx
+++ b/web/src/features/evals/components/inner-evaluator-form.tsx
@@ -27,6 +27,7 @@ import {
availableTraceEvalVariables,
datasetFormFilterColsWithOptions,
availableDatasetEvalVariables,
+ observationEvalVariableColumns,
type ObservationType,
LangfuseInternalTraceEnvironment,
} from "@langfuse/shared";
@@ -34,7 +35,11 @@ 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 {
+ type EvalTemplate,
+ wipVariableMapping,
+ variableMapping,
+} from "@langfuse/shared";
import { useRouter } from "next/router";
import { Slider } from "@/src/components/ui/slider";
import { Card } from "@/src/components/ui/card";
@@ -46,6 +51,7 @@ import { Checkbox } from "@/src/components/ui/checkbox";
import {
evalConfigFormSchema,
type EvalFormType,
+ isLegacyEvalTarget,
isTraceOrDatasetObject,
isTraceTarget,
type LangfuseObject,
@@ -207,9 +213,9 @@ export const InnerEvaluatorForm = (props: {
: [],
mapping: props.existingEvaluator?.variableMapping
? z
- .array(variableMapping)
+ .array(wipVariableMapping)
.parse(props.existingEvaluator.variableMapping)
- : z.array(variableMapping).parse(
+ : z.array(wipVariableMapping).parse(
props.evalTemplate
? props.evalTemplate.vars.map((v) => ({
templateVariable: v,
@@ -887,79 +893,18 @@ export const InnerEvaluatorForm = (props: {
}
/>
</div>
- <FormField
- control={form.control}
- key={`${mappingField.id}-langfuseObject`}
- name={`mapping.${index}.langfuseObject`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title="Object"
- description={
- "Langfuse object to retrieve the data from."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Select
- disabled={props.disabled}
- defaultValue={field.value}
- onValueChange={(value) => {
- field.onChange(value);
- form.setValue(
- `mapping.${index}.objectName`,
- undefined,
- );
- }}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {availableVariables.map((evalObject) => (
- <SelectItem
- value={evalObject.id}
- key={evalObject.id}
- >
- {evalObject.display}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
-
- {!isTraceOrDatasetObject(
- form.watch(`mapping.${index}.langfuseObject`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-objectName`}
- name={`mapping.${index}.objectName`}
- render={({ field }) => {
- const type = String(
- form.watch(`mapping.${index}.langfuseObject`),
- ).toUpperCase() as ObservationType;
- const nameOptions = Array.from(
- observationTypeToNames.get(type) ?? [],
- );
- const isCustomOption =
- field.value === "custom" ||
- (field.value &&
- !nameOptions.includes(field.value));
- return (
+ {isLegacyEvalTarget(form.watch("target")) ? (
+ <>
+ <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,187 +912,338 @@ 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) => (
+ <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>
+ ))}
<SelectItem
- key={name}
- value={name}
+ key="custom"
+ value="custom"
>
- {name}
+ Enter name...
</SelectItem>
- ))}
+ </SelectContent>
+ </Select>
+ )}
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ </div>
+ );
+ }}
+ />
+ ) : undefined}
+
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-selectedColumnId`}
+ name={`mapping.${index}.selectedColumnId`}
+ render={({ field }) => (
+ <div className="flex items-center gap-2">
+ <VariableMappingDescription
+ title={"Object Variable"}
+ description={
+ "Variable on the Langfuse object to insert into the template."
+ }
+ href={
+ "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
+ }
+ />
+ <FormItem className="w-2/3">
+ <FormControl>
+ <Select
+ disabled={props.disabled}
+ defaultValue={field.value ?? undefined}
+ onValueChange={(value) => {
+ const availableColumns =
+ availableVariables.find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )?.availableColumns;
+
+ const column = availableColumns?.find(
+ (column) => column.id === value,
+ );
+
+ field.onChange(column?.id);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Object type" />
+ </SelectTrigger>
+ <SelectContent>
+ {availableVariables
+ .find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )
+ ?.availableColumns.map((column) => (
<SelectItem
- key="custom"
- value="custom"
+ value={column.id}
+ key={column.id}
>
- Enter name...
+ {column.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
+ ))}
+ </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 ?? ""}
- onValueChange={field.onChange}
disabled={props.disabled}
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {nameOptions?.map((name) => (
+ 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) => (
<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"}
- description={
- "Variable on the Langfuse object to insert into the template."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Select
- disabled={props.disabled}
- defaultValue={field.value ?? undefined}
- onValueChange={(value) => {
- const availableColumns =
- availableVariables.find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )?.availableColumns;
-
- const column = availableColumns?.find(
- (column) => column.id === value,
- );
-
- field.onChange(column?.id);
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Object type" />
- </SelectTrigger>
- <SelectContent>
- {availableVariables
- .find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )
- ?.availableColumns.map((column) => (
- <SelectItem
- value={column.id}
- key={column.id}
- >
- {column.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- {fieldHasJsonSelectorOption(
- form.watch(`mapping.${index}.selectedColumnId`),
- ) ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-jsonSelector`}
- name={`mapping.${index}.jsonSelector`}
- render={({ field }) => (
- <div className="flex items-center gap-2">
- <VariableMappingDescription
- title={"JsonPath"}
- description={
- "Optional selection: Use JsonPath syntax to select from a JSON object stored on a trace. If not selected, we will pass the entire object into the prompt."
- }
- href={
- "https://langfuse.com/docs/evaluation/evaluation-methods/llm-as-a-judge"
- }
- />
- <FormItem className="w-2/3">
- <FormControl>
- <Input
- {...field}
- value={field.value ?? ""}
- disabled={props.disabled}
- placeholder="Optional"
+ )}
+ />
+ {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"
+ }
/>
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- )}
- />
- ) : undefined}
+ <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 e86806a596..834b8589dd 100644
--- a/web/src/features/evals/components/template-selector.tsx
+++ b/web/src/features/evals/components/template-selector.tsx
@@ -8,6 +8,7 @@ import {
AlertCircle,
ExternalLinkIcon,
} from "lucide-react";
+import { Badge } from "@/src/components/ui/badge";
import {
Popover,
PopoverContent,
@@ -44,6 +45,7 @@ type TemplateSelectorProps = {
disabled?: boolean;
activeTemplateIds?: string[];
inactiveTemplateIds?: string[];
+ evaluatorTargetObjects?: Record<string, string>;
onConfigureTemplate?: (templateId: string) => void;
onSelectEvaluator?: (templateId: string) => void;
onEvaluatorToggled?: () => void;
@@ -56,6 +58,7 @@ export const TemplateSelector = ({
evalTemplates,
activeTemplateIds,
inactiveTemplateIds,
+ evaluatorTargetObjects,
onConfigureTemplate,
onSelectEvaluator,
onEvaluatorToggled,
@@ -201,6 +204,9 @@ export const TemplateSelector = ({
latestTemplate.id,
);
const isInvalid = isTemplateInvalid(latestTemplate);
+ const isLegacy =
+ evaluatorTargetObjects?.[latestTemplate.id] ===
+ "dataset";
return (
<InputCommandItem
@@ -216,6 +222,11 @@ 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>
@@ -282,6 +293,9 @@ 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
@@ -300,6 +314,11 @@ 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 72d8bc15ca..a71baf2411 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -626,7 +626,12 @@ export const evalRouter = createTRPCRouter({
}),
jobConfigsByTarget: protectedProjectProcedure
- .input(z.object({ projectId: z.string(), targetObject: z.string() }))
+ .input(
+ z.object({
+ projectId: z.string(),
+ targetObject: z.array(z.string()),
+ }),
+ )
.query(async ({ input, ctx }) => {
throwIfNoProjectAccess({
session: ctx.session,
@@ -637,7 +642,7 @@ export const evalRouter = createTRPCRouter({
const evaluators = await ctx.prisma.jobConfiguration.findMany({
where: {
projectId: input.projectId,
- targetObject: input.targetObject,
+ targetObject: { in: 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 0d68488693..311dc663d1 100644
--- a/web/src/features/evals/utils/evaluator-form-utils.ts
+++ b/web/src/features/evals/utils/evaluator-form-utils.ts
@@ -10,6 +10,11 @@ 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 3a79b7cd6d..70d7ab5e86 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" },
+ { projectId, targetObject: ["dataset", "experiment"] },
{
enabled: hasEvalReadAccess && !!datasetId,
},
@@ -150,6 +150,7 @@ export const MultiStepExperimentForm = ({
const {
activeEvaluators,
pausedEvaluators,
+ evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -241,17 +242,8 @@ export const MultiStepExperimentForm = ({
);
// Callback for preprocessing evaluator form 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;
- };
+ // For experiment evaluators, we only run on new data (not historic)
+ const preprocessFormValues = (values: any) => values;
const onSubmit = async (data: CreateExperiment) => {
capture("dataset_run:new_form_submit");
@@ -392,6 +384,7 @@ 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 bc3ffb70dd..6487e3aa89 100644
--- a/web/src/features/experiments/components/steps/EvaluatorsStep.tsx
+++ b/web/src/features/experiments/components/steps/EvaluatorsStep.tsx
@@ -21,6 +21,7 @@ export const EvaluatorsStep: React.FC<EvaluatorsStepProps> = ({
evalTemplates,
activeEvaluators,
pausedEvaluators,
+ evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -50,6 +51,7 @@ 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 2030c15a31..ed55429a93 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 { createDefaultVariableMappings } from "../utils/evaluatorMappingUtils";
+import { createDefaultObservationVariableMappings } from "../utils/evaluatorMappingUtils";
import { type PartialConfig } from "@/src/features/evals/types";
export const CONFIG_BASE = {
- targetObject: EvalTargetObject.DATASET,
+ targetObject: EvalTargetObject.EXPERIMENT,
sampling: new Decimal(1),
delay: 30000,
timeScope: ["NEW"],
@@ -23,20 +23,22 @@ 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 for experiment target (observation-based)
+ const variableMappings = createDefaultObservationVariableMappings(template);
- // Return the configured evaluator
+ // Return the configured evaluator for experiment target
return {
...CONFIG_BASE,
evalTemplate: template,
scoreName: scoreName || template.name,
- variableMapping: alternatingMappings,
+ variableMapping: variableMappings,
filter: [
{
type: "stringOptions",
value: [datasetId],
- column: "Dataset",
+ // 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",
operator: "any of",
},
],
diff --git a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
index 803c1ae051..ccf9c9fb33 100644
--- a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
+++ b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts
@@ -7,7 +7,11 @@ import partition from "lodash/partition";
const partitionEvaluators = (
evaluators: RouterOutputs["evals"]["jobConfigsByTarget"] | undefined,
datasetId: string,
-): { activeEvaluators: string[]; pausedEvaluators: string[] } => {
+): {
+ activeEvaluators: string[];
+ pausedEvaluators: string[];
+ evaluatorTargetObjects: Record<string, string>;
+} => {
const filteredEvaluators =
evaluators?.filter(({ filter }) => {
if (filter?.length === 0) return true;
@@ -29,9 +33,16 @@ 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,
};
};
@@ -151,9 +162,10 @@ export function useExperimentEvaluatorData({
[prepareEvaluatorData],
);
- const { activeEvaluators, pausedEvaluators } = useMemo(() => {
- return partitionEvaluators(evaluatorsData, datasetId);
- }, [evaluatorsData, datasetId]);
+ const { activeEvaluators, pausedEvaluators, evaluatorTargetObjects } =
+ useMemo(() => {
+ return partitionEvaluators(evaluatorsData, datasetId);
+ }, [evaluatorsData, datasetId]);
return {
// State
@@ -161,6 +173,7 @@ 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 a4404230d6..f6cf26f970 100644
--- a/web/src/features/experiments/types/stepProps.ts
+++ b/web/src/features/experiments/types/stepProps.ts
@@ -78,6 +78,7 @@ 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 5f9da10843..53cbea6c5f 100644
--- a/web/src/features/experiments/utils/evaluatorMappingUtils.ts
+++ b/web/src/features/experiments/utils/evaluatorMappingUtils.ts
@@ -1,4 +1,7 @@
-import { type EvalTemplate } from "@langfuse/shared";
+import {
+ type EvalTemplate,
+ type ObservationVariableMapping,
+} from "@langfuse/shared";
// Define the type locally to match what's in @langfuse/shared
type VariableMapping = {
@@ -37,6 +40,29 @@ 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.
*
@@ -68,6 +94,38 @@ 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 2fcf33fb3b..d2037ecb61 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" },
+ { projectId, targetObject: ["dataset", "experiment"] },
{
enabled: hasEvalReadAccess && !!datasetId,
},
@@ -121,6 +121,7 @@ export default function Dataset() {
const {
activeEvaluators,
pausedEvaluators,
+ evaluatorTargetObjects,
selectedEvaluatorData,
showEvaluatorForm,
handleConfigureEvaluator,
@@ -135,20 +136,9 @@ export default function Dataset() {
refetchEvaluators: evaluators.refetch,
});
- // 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;
- }, []);
+ // Callback for preprocessing evaluator form values
+ // For experiment evaluators, we only run on new data (not historic)
+ const preprocessFormValues = useCallback((values: any) => values, []);
const datasetName = dataset.data?.name ?? "";
const segments = datasetName.split("/").filter((s) => s.trim());
@@ -215,6 +205,7 @@ 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 dd869cb71f..2de730b6e6 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -1074,7 +1074,10 @@ export async function extractVariablesFromTracingData({
.filter((obj) => obj.id !== "trace") // trace is handled separately above
.map((obj) => obj.id);
- if (observationTypes.includes(mapping.langfuseObject)) {
+ if (
+ mapping.langfuseObject &&
+ 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
new file mode 100644
index 0000000000..07acfd1492
--- /dev/null
+++ b/worker/src/features/experiments/__tests__/scheduleExperimentEvals.test.ts
@@ -0,0 +1,569 @@
+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 86a8cc3bda..ac5c92215b 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -6,6 +6,7 @@ import {
eventTypes,
ExperimentCreateEventSchema,
fetchLLMCompletion,
+ GenerationDetails,
getDatasetItems,
IngestionEventType,
LangfuseInternalTraceEnvironment,
@@ -30,6 +31,7 @@ import {
} from "@langfuse/shared";
import { randomUUID } from "crypto";
import { createW3CTraceId } from "../utils";
+import { scheduleExperimentObservationEvals } from "./scheduleExperimentEvals";
async function getExistingRunItemDatasetItemIds(
projectId: string,
@@ -123,6 +125,20 @@ 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 *
********************/
@@ -151,7 +167,7 @@ async function processLLMCall(
traceId: string,
datasetItem: DatasetItemDomain & { input: Prisma.JsonObject },
config: PromptExperimentConfig,
-): Promise<{ success: boolean }> {
+): Promise<{ success: boolean; generationDetails?: GenerationDetails }> {
let messages: ChatMessage[] = [];
// Extract and replace variables in prompt
try {
@@ -169,6 +185,8 @@ 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)}`,
@@ -182,6 +200,9 @@ async function processLLMCall(
experiment_run_name: config.experimentRunName,
},
prompt: config.prompt,
+ onGenerationComplete: (details) => {
+ generationDetails = details;
+ },
};
await fetchLLMCompletion({
@@ -199,7 +220,10 @@ async function processLLMCall(
traceSinkParams,
}).catch(); // catch errors and do not retry
- return { success: true };
+ return {
+ success: true,
+ generationDetails: generationDetails ?? undefined,
+ };
}
async function getItemsToProcess(
diff --git a/worker/src/features/experiments/scheduleExperimentEvals.ts b/worker/src/features/experiments/scheduleExperimentEvals.ts
new file mode 100644
index 0000000000..ccb3212cee
--- /dev/null
+++ b/worker/src/features/experiments/scheduleExperimentEvals.ts
@@ -0,0 +1,114 @@
+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
+ }
+}