🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(evals): add experiment item metadata mapping for experiment evaluators (#13702)
marliessophie5b121282cab2
diff --git a/fern/apis/server/definition/unstable/commons.yml b/fern/apis/server/definition/unstable/commons.ymlindex c17431cbd5..cd2afb0f4f 100644--- a/fern/apis/server/definition/unstable/commons.yml+++ b/fern/apis/server/definition/unstable/commons.yml@@ -25,7 +25,7 @@ types:Choose the target first, because it changes both the valid filter columns and the valid variable-mapping sources:- `observation` evaluates live-ingested observations such as generations, spans, and events.It supports mapping from `input`, `output`, and `metadata`.- - `experiment` evaluates live experiment executions and can additionally map `expected_output`.+ - `experiment` evaluates live experiment executions and can additionally map `expected_output` and `experiment_item_metadata`.It currently supports filtering by `datasetId`.Discover valid dataset IDs with `GET /api/public/v2/datasets`, then use the returned dataset `id` values in your filter.enum:@@ -52,18 +52,20 @@ types:Target-specific rules:- `target=observation` supports `input`, `output`, and `metadata`- - `target=experiment` supports `input`, `output`, `metadata`, and `expected_output`+ - `target=experiment` supports `input`, `output`, `metadata`, `expected_output`, and `experiment_item_metadata`Source semantics:- `input`: the observation or experiment input payload- `output`: the observation or experiment output payload- `metadata`: the metadata object for the target. Combine with `jsonPath` when you need one nested field instead of the whole object.- `expected_output`: the experiment item's expected output. Only valid for `target=experiment`.+ - `experiment_item_metadata`: the experiment item's metadata object. Only valid for `target=experiment`.enum:- input- output- metadata- expected_output+ - experiment_item_metadataEvaluatorModelConfig:docs: |@@ -437,7 +439,7 @@ types:Quick reference:- `target=observation`: `input`, `output`, `metadata`- - `target=experiment`: `input`, `output`, `metadata`, `expected_output`+ - `target=experiment`: `input`, `output`, `metadata`, `expected_output`, `experiment_item_metadata`jsonPath:type: optional<string>docs: |diff --git a/fern/apis/server/definition/unstable/evaluation-rules.yml b/fern/apis/server/definition/unstable/evaluation-rules.ymlindex 655ad24cf4..fbb8399a6d 100644--- a/fern/apis/server/definition/unstable/evaluation-rules.yml+++ b/fern/apis/server/definition/unstable/evaluation-rules.yml@@ -23,7 +23,7 @@ service:- Langfuse resolves that family to its latest version before saving the evaluation rule- for `target=experiment`, use dataset `id` values from `GET /api/public/v2/datasets` when filtering by `datasetId`- every evaluator prompt variable must be mapped exactly once- - `expected_output` mappings are only valid for `target=experiment`+ - `expected_output` and `experiment_item_metadata` mappings are only valid for `target=experiment`- if `enabled=true`, Langfuse validates that the referenced evaluator can currently run- at most 50 evaluation rules can be effectively active in one project at the same timediff --git a/packages/shared/src/features/evals/observationForEval.ts b/packages/shared/src/features/evals/observationForEval.tsindex e0c302f718..a33e649af1 100644--- a/packages/shared/src/features/evals/observationForEval.ts+++ b/packages/shared/src/features/evals/observationForEval.ts@@ -63,6 +63,7 @@ export const observationForEvalSchema = z.object({experiment_dataset_id: z.string().nullish(),experiment_item_id: z.string().nullish(),experiment_item_expected_output: z.string().nullish(),+ experiment_item_metadata: z.record(z.string(), z.unknown()).nullish(),experiment_item_root_span_id: z.string().nullish(),// Data - accepts any type (string, array, object) from different OTEL SDKs@@ -80,11 +81,23 @@ export function convertEventRecordToObservationForEval(record.metadata_names,record.metadata_values,);+ const experimentItemMetadata =+ record.experiment_item_metadata_names.length > 0+ ? record.experiment_item_metadata_names.reduce<+ Record<string, string | null | undefined>+ >((acc, name, i) => {+ if (!(name in acc)) {+ acc[name] = record.experiment_item_metadata_values[i];+ }+ return acc;+ }, {})+ : undefined;const toolCallNames = record.tool_call_names ?? [];return observationForEvalSchema.parse({...record,metadata,+ experiment_item_metadata: experimentItemMetadata,tool_call_count: toolCallNames.length,});}@@ -111,7 +124,11 @@ export type ObservationEvalFilterColumnInternal =export type ObservationEvalMappingColumnInternal = keyof Pick<ObservationForEval,- "input" | "output" | "metadata" | "experiment_item_expected_output"+ | "input"+ | "output"+ | "metadata"+ | "experiment_item_expected_output"+ | "experiment_item_metadata">;export interface ObservationEvalVariableColumn {@@ -126,14 +143,7 @@ export interface ObservationEvalVariableColumn {internal: ObservationEvalMappingColumnInternal;}-/**- * Columns available for variable extraction in observation-based evals.- * These are the fields that can be mapped to template variables.- *- * When configuring an eval, users can map these columns to template- * variables like {{input}}, {{output}}, {{expected_output}}, etc.- */-export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [+export const eventTargetEvalVariableColumns: ObservationEvalVariableColumn[] = [{id: "input",name: "Input",@@ -153,12 +163,35 @@ export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [type: "stringObject",internal: "metadata",},- {- id: "experimentItemExpectedOutput",- name: "Expected Output",- description: "Expected output from experiment item",- internal: "experiment_item_expected_output",- },+];++export const experimentTargetEvalVariableColumns: ObservationEvalVariableColumn[] =+ [+ ...eventTargetEvalVariableColumns,+ {+ id: "experimentItemExpectedOutput",+ name: "Expected Output",+ description: "Expected output from experiment item",+ internal: "experiment_item_expected_output",+ },+ {+ id: "experimentItemMetadata",+ name: "Experiment Item Metadata",+ description: "Metadata from experiment item",+ type: "stringObject",+ internal: "experiment_item_metadata",+ },+ ];++/**+ * Columns available for variable extraction in observation-based evals.+ * These are the fields that can be mapped to template variables.+ *+ * When configuring an eval, users can map these columns to template+ * variables like {{input}}, {{output}}, {{expected_output}}, etc.+ */+export const observationEvalVariableColumns: ObservationEvalVariableColumn[] = [+ ...experimentTargetEvalVariableColumns,];export const availableObservationEvalVariableColumns = [diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.tsindex befa6b3d02..ec0eb0449c 100644--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts@@ -389,6 +389,7 @@ const FIELD_SETS = {"experimentId","experimentItemRootSpanId","experimentItemExpectedOutput",+ "experimentItemMetadata",],// Experiment items field setdiff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 37be534ed6..4a6470bb1c 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -6189,7 +6189,8 @@ paths:- every evaluator prompt variable must be mapped exactly once- - `expected_output` mappings are only valid for `target=experiment`+ - `expected_output` and `experiment_item_metadata` mappings are only+ valid for `target=experiment`- if `enabled=true`, Langfuse validates that the referenced evaluatorcan currently run@@ -12169,7 +12170,7 @@ components:generations, spans, and events.It supports mapping from `input`, `output`, and `metadata`.- `experiment` evaluates live experiment executions and can additionally- map `expected_output`.+ map `expected_output` and `experiment_item_metadata`.It currently supports filtering by `datasetId`.Discover valid dataset IDs with `GET /api/public/v2/datasets`, then use the returned dataset `id` values in your filter.unstableEvaluationRuleStatus:@@ -12197,6 +12198,7 @@ components:- output- metadata- expected_output+ - experiment_item_metadatadescription: >-Source field used to populate a prompt variable.@@ -12208,8 +12210,8 @@ components:- `target=observation` supports `input`, `output`, and `metadata`- - `target=experiment` supports `input`, `output`, `metadata`, and- `expected_output`+ - `target=experiment` supports `input`, `output`, `metadata`,+ `expected_output`, and `experiment_item_metadata`Source semantics:@@ -12223,6 +12225,9 @@ components:- `expected_output`: the experiment item's expected output. Only validfor `target=experiment`.++ - `experiment_item_metadata`: the experiment item's metadata object.+ Only valid for `target=experiment`.unstableEvaluatorModelConfig:title: unstableEvaluatorModelConfigtype: object@@ -12763,7 +12768,7 @@ components:- `target=observation`: `input`, `output`, `metadata`- `target=experiment`: `input`, `output`, `metadata`,- `expected_output`+ `expected_output`, `experiment_item_metadata`jsonPath:type: stringnullable: truediff --git a/web/src/__tests__/server/event-query-builder.servertest.ts b/web/src/__tests__/server/event-query-builder.servertest.tsindex d9293c01b2..aa4d5fb9ae 100644--- a/web/src/__tests__/server/event-query-builder.servertest.ts+++ b/web/src/__tests__/server/event-query-builder.servertest.ts@@ -189,4 +189,16 @@ describe("EventsQueryBuilder", () => {},);});++ it("should include experiment item metadata in eval field set", () => {+ const query = new EventsQueryBuilder({+ projectId: "test-project",+ })+ .selectFieldSet("eval")+ .buildWithParams().query;++ expect(query).toContain(+ "mapFromArrays(e.experiment_item_metadata_names, e.experiment_item_metadata_values) as experiment_item_metadata",+ );+ });});diff --git a/web/src/features/evals/components/variable-mapping-card.tsx b/web/src/features/evals/components/variable-mapping-card.tsxindex 595b141230..c98f8765a9 100644--- a/web/src/features/evals/components/variable-mapping-card.tsx+++ b/web/src/features/evals/components/variable-mapping-card.tsx@@ -9,7 +9,8 @@ import {type availableDatasetEvalVariables,type availableTraceEvalVariables,type EvalTemplate,- observationEvalVariableColumns,+ eventTargetEvalVariableColumns,+ experimentTargetEvalVariableColumns,} from "@langfuse/shared";import { Card } from "@/src/components/ui/card";import { JSONView } from "@/src/components/ui/CodeJsonViewer";@@ -649,12 +650,8 @@ export const VariableMappingCard = ({// For observations (event), exclude experiment-specific fieldsconst availableColumns =form.watch("target") === EvalTargetObject.EVENT- ? observationEvalVariableColumns.filter(- (col) =>- col.id !==- "experimentItemExpectedOutput",- )- : observationEvalVariableColumns;+ ? eventTargetEvalVariableColumns+ : experimentTargetEvalVariableColumns;return (<div className="flex items-center gap-2">@@ -695,14 +692,9 @@ export const VariableMappingCard = ({);}}/>- {(form.watch(`mapping.${index}.selectedColumnId`) ===- "metadata" ||- form.watch(`mapping.${index}.selectedColumnId`) ===- "input" ||- form.watch(`mapping.${index}.selectedColumnId`) ===- "output" ||- form.watch(`mapping.${index}.selectedColumnId`) ===- "experimentItemExpectedOutput") && (+ {fieldHasJsonSelectorOption(+ form.watch(`mapping.${index}.selectedColumnId`),+ ) && (<FormFieldcontrol={form.control}key={`${mappingField.id}-jsonSelector`}diff --git a/web/src/features/evals/hooks/useEvaluatorTarget.ts b/web/src/features/evals/hooks/useEvaluatorTarget.tsindex 11964a62c2..5c5a24fddf 100644--- a/web/src/features/evals/hooks/useEvaluatorTarget.ts+++ b/web/src/features/evals/hooks/useEvaluatorTarget.ts@@ -3,6 +3,8 @@ import {EvalTargetObject,availableTraceEvalVariables,availableDatasetEvalVariables,+ eventTargetEvalVariableColumns,+ experimentTargetEvalVariableColumns,} from "@langfuse/shared";import {isTraceTarget,@@ -73,12 +75,25 @@ export const useEvaluatorTargetState = () => {const isObservationBased =isEventTarget(targetObject) || isExperimentTarget(targetObject);+ // Get valid column IDs for the target+ const validColumnIds = isEventTarget(targetObject)+ ? new Set(eventTargetEvalVariableColumns.map((c) => c.id))+ : isExperimentTarget(targetObject)+ ? new Set(experimentTargetEvalVariableColumns.map((c) => c.id))+ : null;+return currentMapping.map((field) => {+ // Reset selectedColumnId if invalid for the new target+ const selectedColumnId =+ validColumnIds && !validColumnIds.has(field.selectedColumnId ?? "")+ ? null+ : field.selectedColumnId;+if (isObservationBased) {// Placeholder langfuseObject (stripped in onSubmit)return {templateVariable: field.templateVariable,- selectedColumnId: field.selectedColumnId,+ selectedColumnId,jsonSelector: field.jsonSelector,langfuseObject: "event" as LangfuseObject,objectName: null,@@ -88,6 +103,7 @@ export const useEvaluatorTargetState = () => {// Proper langfuseObject for trace/datasetreturn {...field,+ selectedColumnId,langfuseObject: (isTraceTarget(targetObject)? "trace": "dataset_item") as LangfuseObject,diff --git a/web/src/features/evals/server/unstable-public-api/adapters.ts b/web/src/features/evals/server/unstable-public-api/adapters.tsindex 684e05474f..3ce17c7c66 100644--- a/web/src/features/evals/server/unstable-public-api/adapters.ts+++ b/web/src/features/evals/server/unstable-public-api/adapters.ts@@ -59,6 +59,7 @@ const PUBLIC_MAPPING_SOURCE_TO_INTERNAL_COLUMN: Record<output: "output",metadata: "metadata",expected_output: "experimentItemExpectedOutput",+ experiment_item_metadata: "experimentItemMetadata",};const INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE: Record<@@ -72,6 +73,8 @@ const INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE: Record<expectedOutput: "expected_output",experiment_item_expected_output: "expected_output",experimentItemExpectedOutput: "expected_output",+ experimentItemMetadata: "experiment_item_metadata",+ experiment_item_metadata: "experiment_item_metadata",};function getPublicFilterArraySchema(target: PublicEvaluationRuleTargetType) {diff --git a/web/src/features/evals/server/unstable-public-api/validation.ts b/web/src/features/evals/server/unstable-public-api/validation.tsindex ed61a2822b..dfab959d57 100644--- a/web/src/features/evals/server/unstable-public-api/validation.ts+++ b/web/src/features/evals/server/unstable-public-api/validation.ts@@ -73,7 +73,13 @@ const SUPPORTED_FILTER_COLUMNS_BY_TARGET = {const SUPPORTED_MAPPING_SOURCES_BY_TARGET = {observation: new Set(["input", "output", "metadata"]),- experiment: new Set(["input", "output", "metadata", "expected_output"]),+ experiment: new Set([+ "input",+ "output",+ "metadata",+ "expected_output",+ "experiment_item_metadata",+ ]),} as const satisfies Record<PublicEvaluationRuleTargetType, Set<string>>;export function validateEvaluationRuleFilters(params: {diff --git a/web/src/features/evals/utils/evaluator-form-utils.ts b/web/src/features/evals/utils/evaluator-form-utils.tsindex 7e85f8d2d9..a76e1aac32 100644--- a/web/src/features/evals/utils/evaluator-form-utils.ts+++ b/web/src/features/evals/utils/evaluator-form-utils.ts@@ -48,8 +48,10 @@ export const fieldHasJsonSelectorOption = (selectedColumnId === "metadata" ||selectedColumnId === "expected_output" ||selectedColumnId === "experiment_item_expected_output" ||+ selectedColumnId === "experiment_item_metadata" ||selectedColumnId === "expectedOutput" ||- selectedColumnId === "experimentItemExpectedOutput";+ selectedColumnId === "experimentItemExpectedOutput" ||+ selectedColumnId === "experimentItemMetadata";export const getTargetDisplayName = (target: string): string => {switch (target) {diff --git a/web/src/features/public-api/types/unstable-public-evals-contract.ts b/web/src/features/public-api/types/unstable-public-evals-contract.tsindex 0ee2691e6e..e703d529a1 100644--- a/web/src/features/public-api/types/unstable-public-evals-contract.ts+++ b/web/src/features/public-api/types/unstable-public-evals-contract.ts@@ -98,11 +98,16 @@ export const ExperimentEvaluationRuleMappingSource = z.enum(["output","metadata","expected_output",+ "experiment_item_metadata",]);function createMappingSchema<TSource extends z.ZodType<- "input" | "output" | "metadata" | "expected_output"+ | "input"+ | "output"+ | "metadata"+ | "expected_output"+ | "experiment_item_metadata">,>(sourceSchema: TSource) {return z.object({diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex af265d1334..5d49094417 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -454,6 +454,7 @@ export const getEventsStreamForEval = async (props: {experiment_id: string | null;experiment_item_root_span_id: string | null;experiment_item_expected_output: string | null;+ experiment_item_metadata: Record<string, unknown> | null;};const asyncGenerator = queryClickhouseStream<EvalEventRow>({diff --git a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.tsindex 0df35e408b..754fe18133 100644--- a/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/extractObservationVariables.test.ts@@ -58,6 +58,7 @@ describe("extractObservationVariables", () => {experiment_dataset_id: null,experiment_item_id: null,experiment_item_expected_output: "expected response",+ experiment_item_metadata: { cohort: "control", region: "eu" },// Data fieldsinput: JSON.stringify({@@ -252,6 +253,26 @@ describe("extractObservationVariables", () => {expect(result[0].var).toBe("expected");expect(result[0].value).toBe("expected response");});++ it("should extract experimentItemMetadata variable as JSON string", () => {+ const variableMapping: ObservationVariableMapping[] = [+ {+ templateVariable: "item_metadata",+ selectedColumnId: "experimentItemMetadata",+ },+ ];++ const result = extractObservationVariables({+ observation: mockObservation,+ variableMapping,+ });++ expect(result).toHaveLength(1);+ expect(result[0].var).toBe("item_metadata");+ expect(result[0].value).toBe(+ JSON.stringify(mockObservation.experiment_item_metadata),+ );+ });});describe("usage extraction", () => {@@ -336,6 +357,23 @@ describe("extractObservationVariables", () => {expect(result[0].value).toBe("I am fine, thank you!");});+ it("should apply JSON selector to extract nested field from experiment item metadata", () => {+ const variableMapping: ObservationVariableMapping[] = [+ {+ templateVariable: "cohort",+ selectedColumnId: "experimentItemMetadata",+ jsonSelector: "$.cohort",+ },+ ];++ const result = extractObservationVariables({+ observation: mockObservation,+ variableMapping,+ });++ expect(result[0].value).toBe("control");+ });+// OTel ingestion stringifies metadata.attributes.* values; ingestion stringifies the whole metadata.attributes objectit("should extract names from stringified metadata.attributes.tools array", () => {const observationWithStringifiedTools: ObservationForEval = {