🪢 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): support categorical llm-as-a-judge outputs (#12540)
hassiebbota7ccf50bb0a7
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex a4047860c0..36b442d7a3 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -935,7 +935,7 @@ model EvalTemplate {provider String?modelParams Json? @map("model_params")vars String[] @default([])- outputSchema Json @map("output_schema")+ outputDefinition Json @map("output_schema")JobConfiguration JobConfiguration[]JobExecution JobExecution[]diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex ede8c0a932..212295138a 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -314,7 +314,7 @@ async function main() {model: evalTemplate.model,vars: evalTemplate.vars,provider: evalTemplate.provider,- outputSchema: evalTemplate.outputSchema,+ outputDefinition: evalTemplate.outputDefinition,modelParams: evalTemplate.modelParams,},update: {},diff --git a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts b/packages/shared/scripts/seeder/utils/postgres-seed-constants.tsindex bc0ac39bda..161ec5b432 100644--- a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts+++ b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts@@ -692,7 +692,7 @@ export const SEED_EVALUATOR_TEMPLATES = [model: "gpt-3.5-turbo",vars: ["input", "output"],provider: "openai",- outputSchema: {+ outputDefinition: {score: "provide a score between 0 and 1",reasoning: "one sentence reasoning for the score",},diff --git a/packages/shared/src/features/evals/outputDefinition.ts b/packages/shared/src/features/evals/outputDefinition.tsnew file mode 100644index 0000000000..97960b322f--- /dev/null+++ b/packages/shared/src/features/evals/outputDefinition.ts@@ -0,0 +1,343 @@+import z from "zod/v4";+import { ScoreDataTypeEnum } from "../../domain/scores";++export const EvalOutputDataTypeSchema = z.enum([+ ScoreDataTypeEnum.NUMERIC,+ ScoreDataTypeEnum.CATEGORICAL,+]);+export type EvalOutputDataType = z.infer<typeof EvalOutputDataTypeSchema>;++// Legacy evaluator templates stored score/reasoning prompts directly as strings.+// Keep this permissive so older rows can still be parsed and normalized.+export const LegacyEvalOutputDefinitionSchema = z.object({+ reasoning: z.string().default(""),+ score: z.string().default(""),+});+export type LegacyEvalOutputDefinition = z.infer<+ typeof LegacyEvalOutputDefinitionSchema+>;++const EvalOutputFieldDefinitionSchema = z.object({+ description: z.string().trim().min(1),+});++export const MinimumCategoricalCategoryCount = 2;++export function getMinimumCategoricalCategoriesMessage() {+ return `Add at least ${MinimumCategoricalCategoryCount} categories`;+}++export type CategoricalCategoryRuleViolation =+ | {+ type: "minimum_count";+ minimumCount: number;+ }+ | {+ type: "duplicate_value";+ index: number;+ };++export function getCategoricalCategoryRuleViolations(categories: string[]) {+ const violations: CategoricalCategoryRuleViolation[] = [];++ if (categories.length < MinimumCategoricalCategoryCount) {+ violations.push({+ type: "minimum_count",+ minimumCount: MinimumCategoricalCategoryCount,+ });+ }++ const seenValues = new Set<string>();++ categories.forEach((category, index) => {+ const normalizedValue = category.trim();++ if (seenValues.has(normalizedValue)) {+ violations.push({+ type: "duplicate_value",+ index,+ });+ return;+ }++ seenValues.add(normalizedValue);+ });++ return violations;+}++const EvalCategoricalCategorySchema = z.string().trim().min(1);++export const NumericEvalOutputDefinitionV2Schema = z.object({+ version: z.literal(2),+ dataType: z.literal(ScoreDataTypeEnum.NUMERIC),+ reasoning: EvalOutputFieldDefinitionSchema,+ score: EvalOutputFieldDefinitionSchema,+});+export type NumericEvalOutputDefinitionV2 = z.infer<+ typeof NumericEvalOutputDefinitionV2Schema+>;++export const CategoricalEvalOutputDefinitionV2Schema = z+ .object({+ version: z.literal(2),+ dataType: z.literal(ScoreDataTypeEnum.CATEGORICAL),+ reasoning: EvalOutputFieldDefinitionSchema,+ score: z.object({+ description: z.string().trim().min(1),+ categories: z.array(EvalCategoricalCategorySchema),+ shouldAllowMultipleMatches: z.boolean().default(false),+ }),+ })+ .superRefine((value, ctx) => {+ getCategoricalCategoryRuleViolations(value.score.categories).forEach(+ (violation) => {+ switch (violation.type) {+ case "minimum_count":+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: getMinimumCategoricalCategoriesMessage(),+ path: ["score", "categories"],+ });+ return;+ case "duplicate_value":+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Categories must be unique",+ path: ["score", "categories", violation.index],+ });+ return;+ }+ },+ );+ });+export type CategoricalEvalOutputDefinitionV2 = z.infer<+ typeof CategoricalEvalOutputDefinitionV2Schema+>;++export const PersistedEvalOutputDefinitionSchema = z.union([+ LegacyEvalOutputDefinitionSchema,+ NumericEvalOutputDefinitionV2Schema,+ CategoricalEvalOutputDefinitionV2Schema,+]);+export type PersistedEvalOutputDefinition = z.infer<+ typeof PersistedEvalOutputDefinitionSchema+>;++export type ResolvedEvalOutputDefinition =+ | {+ dataType: typeof ScoreDataTypeEnum.NUMERIC;+ reasoningDescription: string;+ scoreDescription: string;+ }+ | {+ dataType: typeof ScoreDataTypeEnum.CATEGORICAL;+ reasoningDescription: string;+ scoreDescription: string;+ categories: string[];+ shouldAllowMultipleMatches: boolean;+ };++type RawEvalOutputResult = {+ score: number | string | string[];+ reasoning: string;+};++export type EvalOutputResult =+ | {+ dataType: typeof ScoreDataTypeEnum.NUMERIC;+ score: number;+ reasoning: string;+ }+ | {+ dataType: typeof ScoreDataTypeEnum.CATEGORICAL;+ matches: string[];+ reasoning: string;+ };++// Resolve the persisted evaluator output definition into one stable execution+// shape regardless of whether the source row is legacy or v2.+export function resolvePersistedEvalOutputDefinition(+ outputDefinition: PersistedEvalOutputDefinition,+): ResolvedEvalOutputDefinition {+ if (!("version" in outputDefinition)) {+ return {+ dataType: ScoreDataTypeEnum.NUMERIC,+ reasoningDescription: outputDefinition.reasoning,+ scoreDescription: outputDefinition.score,+ };+ }++ if (outputDefinition.dataType === ScoreDataTypeEnum.NUMERIC) {+ return {+ dataType: ScoreDataTypeEnum.NUMERIC,+ reasoningDescription: outputDefinition.reasoning.description,+ scoreDescription: outputDefinition.score.description,+ };+ }++ return {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoningDescription: outputDefinition.reasoning.description,+ scoreDescription: outputDefinition.score.description,+ categories: outputDefinition.score.categories,+ shouldAllowMultipleMatches:+ outputDefinition.score.shouldAllowMultipleMatches,+ };+}++export function createNumericEvalOutputDefinition(params: {+ reasoningDescription: string;+ scoreDescription: string;+}) {+ return NumericEvalOutputDefinitionV2Schema.parse({+ version: 2,+ dataType: ScoreDataTypeEnum.NUMERIC,+ reasoning: {+ description: params.reasoningDescription,+ },+ score: {+ description: params.scoreDescription,+ },+ });+}++export function createCategoricalEvalOutputDefinition(params: {+ reasoningDescription: string;+ scoreDescription: string;+ categories: string[];+ shouldAllowMultipleMatches?: boolean;+}) {+ return CategoricalEvalOutputDefinitionV2Schema.parse({+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: params.reasoningDescription,+ },+ score: {+ description: params.scoreDescription,+ categories: params.categories,+ shouldAllowMultipleMatches: params.shouldAllowMultipleMatches ?? false,+ },+ });+}++function buildResultSchemaForResolvedOutputDefinition(+ resolvedOutputDefinition: ResolvedEvalOutputDefinition,+) {+ if (resolvedOutputDefinition.dataType === ScoreDataTypeEnum.CATEGORICAL) {+ const [firstCategory, ...remainingCategories] =+ resolvedOutputDefinition.categories;++ if (!firstCategory) {+ throw new Error(+ "Categorical eval output definition requires at least one category",+ );+ }++ const categoricalValueSchema = z.enum([+ firstCategory,+ ...remainingCategories,+ ]);++ const scoreSchema = resolvedOutputDefinition.shouldAllowMultipleMatches+ ? z+ .array(categoricalValueSchema)+ .min(1)+ .max(remainingCategories.length + 1)+ .superRefine((categories, ctx) => {+ if (new Set(categories).size !== categories.length) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Score categories must be unique",+ });+ }+ })+ : categoricalValueSchema;++ return z.object({+ reasoning: z+ .string()+ .describe(resolvedOutputDefinition.reasoningDescription),+ score: scoreSchema.describe(resolvedOutputDefinition.scoreDescription),+ });+ }++ return z.object({+ reasoning: z+ .string()+ .describe(resolvedOutputDefinition.reasoningDescription),+ score: z.number().describe(resolvedOutputDefinition.scoreDescription),+ });+}++export function buildEvalOutputResultSchema(+ outputDefinition: PersistedEvalOutputDefinition,+) {+ return buildResultSchemaForResolvedOutputDefinition(+ resolvePersistedEvalOutputDefinition(outputDefinition),+ );+}++export type CompiledEvalOutputDefinition = ReturnType<+ typeof compilePersistedEvalOutputDefinition+>;++export function compilePersistedEvalOutputDefinition(+ outputDefinition: PersistedEvalOutputDefinition,+) {+ const resolvedOutputDefinition =+ resolvePersistedEvalOutputDefinition(outputDefinition);+ const outputResultSchema = buildResultSchemaForResolvedOutputDefinition(+ resolvedOutputDefinition,+ );++ return {+ resolvedOutputDefinition,+ outputResultSchema,+ };+}++function normalizeValidatedEvalOutputResult(+ result: RawEvalOutputResult,+ resolvedOutputDefinition: ResolvedEvalOutputDefinition,+): EvalOutputResult {+ if (resolvedOutputDefinition.dataType === ScoreDataTypeEnum.NUMERIC) {+ return {+ dataType: ScoreDataTypeEnum.NUMERIC,+ score: result.score as number,+ reasoning: result.reasoning,+ };+ }++ return {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ matches: Array.isArray(result.score)+ ? result.score+ : [result.score as string],+ reasoning: result.reasoning,+ };+}++export function validateEvalOutputResult(params: {+ response: unknown;+ compiledOutputDefinition: CompiledEvalOutputDefinition;+}):+ | { success: true; data: EvalOutputResult }+ | { success: false; error: string } {+ const result = params.compiledOutputDefinition.outputResultSchema.safeParse(+ params.response,+ );++ if (result.success) {+ return {+ success: true,+ data: normalizeValidatedEvalOutputResult(+ result.data as RawEvalOutputResult,+ params.compiledOutputDefinition.resolvedOutputDefinition,+ ),+ };+ }++ return { success: false, error: result.error.message };+}diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.tsindex 725bea7925..b9e0d4fce7 100644--- a/packages/shared/src/features/evals/types.ts+++ b/packages/shared/src/features/evals/types.ts@@ -165,11 +165,6 @@ export const availableDatasetEvalVariables = [...availableTraceEvalVariables,];-export const OutputSchema = z.object({- reasoning: z.string(),- score: z.string(),-});-export const DEFAULT_TRACE_JOB_DELAY = 10_000;export const JobTimeScopeZod = z.enum(["NEW", "EXISTING"]);diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 3e3961aa2a..f5ce9cd40c 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -31,6 +31,7 @@ export * from "./server/llm/types";// evalsexport * from "./features/evals/types";+export * from "./features/evals/outputDefinition";export * from "./features/evals/utilities";export * from "./features/evals/observationForEval";export * from "./features/evals/evalConfigBlocking";diff --git a/packages/shared/src/server/llm/testModelCall.ts b/packages/shared/src/server/llm/testModelCall.tsindex ce0fd37bb6..d83195c40b 100644--- a/packages/shared/src/server/llm/testModelCall.ts+++ b/packages/shared/src/server/llm/testModelCall.ts@@ -1,4 +1,3 @@-import { z as zodV3 } from "zod/v3";import {ChatMessageRole,ChatMessageType,@@ -8,16 +7,22 @@ import {import { fetchLLMCompletion } from "./fetchLLMCompletion";import z from "zod/v4";+type StructuredOutputSchema = NonNullable<+ Parameters<typeof fetchLLMCompletion>[0]["structuredOutputSchema"]+>;+export const testModelCall = async ({provider,model,apiKey,modelConfig,+ structuredOutputSchema,}: {provider: string;model: string;apiKey: z.infer<typeof LLMApiKeySchema>;modelConfig?: ModelConfig | null;+ structuredOutputSchema?: StructuredOutputSchema;}) => {await fetchLLMCompletion({streaming: false,@@ -36,9 +41,11 @@ export const testModelCall = async ({adapter: apiKey.adapter,...modelConfig,},- structuredOutputSchema: zodV3.object({- score: zodV3.string(),- reasoning: zodV3.string(),- }),+ structuredOutputSchema:+ structuredOutputSchema ??+ z.object({+ score: z.string(),+ reasoning: z.string(),+ }),});};diff --git a/web/src/__tests__/server/eval-template-output-definition.servertest.ts b/web/src/__tests__/server/eval-template-output-definition.servertest.tsnew file mode 100644index 0000000000..57c3aa766d--- /dev/null+++ b/web/src/__tests__/server/eval-template-output-definition.servertest.ts@@ -0,0 +1,135 @@+/** @jest-environment node */++import { CreateEvalTemplateInputSchema } from "@/src/features/evals/server/router";+import {+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ ScoreDataTypeEnum,+} from "@langfuse/shared";++describe("CreateEvalTemplateInputSchema", () => {+ const baseInput = {+ name: "Accuracy evaluator",+ projectId: "project-1",+ prompt: "Judge {{output}} against {{expected_output}}",+ provider: null,+ model: null,+ modelParams: null,+ vars: ["output", "expected_output"],+ };++ it("accepts versioned categorical output definitions", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Explain the selected category",+ categories: ["correct", "partial"],+ }),+ });++ expect(result.success).toBe(true);+ });++ it("accepts versioned categorical multi-match output definitions", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ });++ expect(result.success).toBe(true);+ });++ it("accepts versioned numeric output definitions", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: createNumericEvalOutputDefinition({+ scoreDescription: "Return a score between 0 and 1",+ reasoningDescription: "Explain the assigned score",+ }),+ });++ expect(result.success).toBe(true);+ });++ it("rejects duplicate categories", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "correct"],+ },+ },+ });++ expect(result.success).toBe(false);+ });++ it("rejects duplicate categories after trimming whitespace", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", " correct "],+ },+ },+ });++ expect(result.success).toBe(false);+ });++ it("rejects blank categorical entries", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", " "],+ },+ },+ });++ expect(result.success).toBe(false);+ });++ it("rejects categorical outputs with fewer than two categories", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct"],+ },+ },+ });++ expect(result.success).toBe(false);+ });+});diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.tsindex 5bfcd6cf35..284ed59409 100644--- a/web/src/__tests__/server/evals-trpc.servertest.ts+++ b/web/src/__tests__/server/evals-trpc.servertest.ts@@ -4,7 +4,12 @@ import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";-import { EvalTargetObject, EvaluatorBlockReason } from "@langfuse/shared";+import {+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ EvalTargetObject,+ EvaluatorBlockReason,+} from "@langfuse/shared";import type { Session } from "next-auth";const __orgIds: string[] = [];@@ -224,6 +229,77 @@ describe("evals trpc", () => {});});+ describe("evals.templateNames", () => {+ it("should return the latest template versions with output definitions", async () => {+ const { project, caller } = await prepare();++ await prisma.evalTemplate.create({+ data: {+ projectId: project.id,+ name: "numeric-template",+ version: 1,+ prompt: "Score this response",+ outputDefinition: createNumericEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "How good",+ }),+ },+ });++ const latestNumericTemplate = await prisma.evalTemplate.create({+ data: {+ projectId: project.id,+ name: "numeric-template",+ version: 2,+ prompt: "Score this response again",+ outputDefinition: createNumericEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "How good",+ }),+ },+ });++ const categoricalTemplate = await prisma.evalTemplate.create({+ data: {+ projectId: project.id,+ name: "categorical-template",+ version: 1,+ prompt: "Classify this response",+ outputDefinition: createCategoricalEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "Classification",+ categories: ["correct", "incorrect"],+ }),+ },+ });++ const response = await caller.evals.templateNames({+ projectId: project.id,+ page: 0,+ limit: 10,+ });++ expect(response.templates).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ latestId: latestNumericTemplate.id,+ name: "numeric-template",+ outputDefinition: expect.objectContaining({+ dataType: "NUMERIC",+ }),+ }),+ expect.objectContaining({+ latestId: categoricalTemplate.id,+ name: "categorical-template",+ outputDefinition: expect.objectContaining({+ dataType: "CATEGORICAL",+ }),+ }),+ ]),+ );+ });+ });+describe("evals.jobExecutionCountsByEvaluatorIds", () => {it("should lazily retrieve execution status counts grouped by evaluator id", async () => {const { project, caller } = await prepare();@@ -613,7 +689,7 @@ describe("evals trpc", () => {// model: "test-model",// modelParams: {},// vars: [],- // outputSchema: {+ // outputDefinition: {// score: "test-score",// reasoning: "test-reasoning",// },@@ -649,7 +725,7 @@ describe("evals trpc", () => {// model: "test-model",// modelParams: {},// vars: [],- // outputSchema: {+ // outputDefinition: {// score: "test-score",// reasoning: "test-reasoning",// },@@ -750,7 +826,7 @@ describe("evals trpc", () => {// model: "test-model",// modelParams: {},// vars: [],- // outputSchema: {+ // outputDefinition: {// score: "test-score",// reasoning: "test-reasoning",// },diff --git a/web/src/components/ui/form.tsx b/web/src/components/ui/form.tsxindex a5eea4cf7a..ed77f488e7 100644--- a/web/src/components/ui/form.tsx+++ b/web/src/components/ui/form.tsx@@ -144,7 +144,10 @@ const FormMessage = React.forwardRef<React.HTMLAttributes<HTMLParagraphElement>>(({ className, children, ...props }, ref) => {const { error, formMessageId } = useFormField();- const body = error ? String(error.message) : children;+ const body =+ typeof error?.message === "string" && error.message.length > 0+ ? error.message+ : children;if (!body) {return null;diff --git a/web/src/features/evals/components/eval-log.tsx b/web/src/features/evals/components/eval-log.tsxindex aea809b79a..25e58b551e 100644--- a/web/src/features/evals/components/eval-log.tsx+++ b/web/src/features/evals/components/eval-log.tsx@@ -1,6 +1,9 @@import { StatusBadge } from "@/src/components/layouts/status-badge";import { DataTable } from "@/src/components/table/data-table";-import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";+import {+ type CustomHeights,+ useRowHeightLocalStorage,+} from "@/src/components/table/data-table-row-height-switch";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import {DataTableControlsProvider,@@ -23,7 +26,7 @@ import { useQueryParams, withDefault, NumberParam } from "use-query-params";export type JobExecutionRow = {status: string;scoreName?: string;- scoreValue?: number;+ scoreValue?: number | string;scoreComment?: string;scoreMetadata?: Prisma.JsonValue;startTime?: string;@@ -36,6 +39,12 @@ export type JobExecutionRow = {error?: string;};+const evalLogRowHeights: CustomHeights = {+ s: "h-8",+ m: "h-24",+ l: "h-64",+};+export default function EvalLogTable({projectId,jobConfigurationId,@@ -74,7 +83,12 @@ export default function EvalLogTable({id: "status",cell: (row) => {const status = row.getValue();- return <StatusBadge type={status.toLowerCase()} />;+ return (+ <StatusBadge+ className="w-fit self-start"+ type={status.toLowerCase()}+ />+ );},}),columnHelper.accessor("startTime", {@@ -101,7 +115,10 @@ export default function EvalLogTable({if (value === undefined) {return undefined;}- return value % 1 === 0 ? value : value.toFixed(4);+ if (typeof value === "number") {+ return value % 1 === 0 ? value : value.toFixed(4);+ }+ return value;},}),columnHelper.accessor("scoreComment", {@@ -218,7 +235,8 @@ export default function EvalLogTable({return {status: jobConfig.status,scoreName: jobConfig.score?.name ?? undefined,- scoreValue: jobConfig.score?.value ?? undefined,+ scoreValue:+ jobConfig.score?.stringValue ?? jobConfig.score?.value ?? undefined,scoreComment: jobConfig.score?.comment ?? undefined,scoreMetadata: jobConfig.score?.metadata ?? undefined,startTime: jobConfig.startTime?.toLocaleString() ?? undefined,@@ -282,6 +300,8 @@ export default function EvalLogTable({onColumnVisibilityChange={setColumnVisibility}columnOrder={columnOrder}onColumnOrderChange={setColumnOrder}+ customRowHeights={evalLogRowHeights}+ rowHeight={rowHeight}/></div></ResizableFilterLayout>diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsxindex e7e0353d3a..26812c78df 100644--- a/web/src/features/evals/components/eval-templates-table.tsx+++ b/web/src/features/evals/components/eval-templates-table.tsx@@ -1,6 +1,7 @@import { DataTable } from "@/src/components/table/data-table";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { type LangfuseColumnDef } from "@/src/components/table/types";+import { type CustomHeights } from "@/src/components/table/data-table-row-height-switch";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { type RouterOutputs, api } from "@/src/utils/api";import { safeExtract } from "@/src/utils/map-utils";@@ -35,9 +36,13 @@ import { MaintainerTooltip } from "@/src/features/evals/components/maintainer-toimport { ActionButton } from "@/src/components/ActionButton";import { useEntitlementLimit } from "@/src/features/entitlements/hooks";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { Badge } from "@/src/components/ui/badge";+import { getTemplateResultType } from "@/src/features/evals/utils/template-output";+import { type EvalTemplate } from "@langfuse/shared";export type EvalsTemplateRow = {name: string;+ resultType: string;maintainer: string;latestCreatedAt?: Date;latestVersion?: number;@@ -48,6 +53,15 @@ export type EvalsTemplateRow = {model?: string;};+const getMaintainerLabel = (maintainer: string) =>+ maintainer.replace(/ maintained$/, "");++const templateTableRowHeights: CustomHeights = {+ s: "h-8",+ m: "h-8",+ l: "h-8",+};+export default function EvalsTemplateTable({projectId,}: {@@ -164,29 +178,48 @@ export default function EvalsTemplateTable({return name ? <TableIdOrName value={name} /> : undefined;},}),+ columnHelper.accessor("resultType", {+ id: "resultType",+ header: "Score Result Type",+ size: 120,+ cell: (row) => {+ const resultType = row.getValue();++ return (+ <Badge className="w-fit self-start" variant="outline-solid">+ {resultType}+ </Badge>+ );+ },+ }),columnHelper.accessor("maintainer", {id: "maintainer",header: "Maintainer",size: 150,cell: (row) => {return (- <div className="flex justify-center">+ <div className="flex items-center gap-2"><MaintainerTooltip maintainer={row.getValue()} />+ <span className="text-muted-foreground">+ {getMaintainerLabel(row.getValue())}+ </span></div>);},}),columnHelper.accessor("latestCreatedAt", {- header: "Last Edit",+ header: "Last Edited",id: "latestCreatedAt",+ size: 80,cell: (row) => {return row.getValue()?.toLocaleDateString();},}),columnHelper.accessor("usageCount", {- header: "Usage count",+ header: "Usage Count",id: "usageCount",enableHiding: true,+ size: 80,cell: (row) => {const count = row.getValue();return !!count ? count : null;@@ -196,6 +229,7 @@ export default function EvalsTemplateTable({header: "Latest Version",id: "latestVersion",enableHiding: true,+ size: 80,cell: (row) => {return row.getValue();},@@ -313,6 +347,7 @@ export default function EvalsTemplateTable({): EvalsTemplateRow => {return {name: template.name,+ resultType: getTemplateResultType(template.outputDefinition),maintainer: getMaintainer(template),latestCreatedAt: template.latestCreatedAt,latestVersion: template.version,@@ -325,48 +360,54 @@ export default function EvalsTemplateTable({return (<>- <DataTableToolbar- columns={columns}- columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}- searchConfig={{- metadataSearchFields: ["Name"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: false,- setSearchType: undefined,- searchType: undefined,- }}- />- <DataTable- tableName={"evalTemplates"}- columns={columns}- peekView={peekConfig}- data={- templates.isLoading- ? { isLoading: true, isError: false }- : templates.isError- ? {- isLoading: false,- isError: true,- error: templates.error.message,- }- : {- isLoading: false,- isError: false,- data: safeExtract(templates.data, "templates", []).map((t) =>- convertToTableRow(t),- ),- }- }- pagination={{- totalCount,- onChange: setPaginationState,- state: paginationState,- }}- columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}- />+ <div className="flex h-full w-full flex-col">+ <DataTableToolbar+ columns={columns}+ columnVisibility={columnVisibility}+ setColumnVisibility={setColumnVisibility}+ searchConfig={{+ metadataSearchFields: ["Name"],+ updateQuery: setSearchQuery,+ currentQuery: searchQuery ?? undefined,+ tableAllowsFullTextSearch: false,+ setSearchType: undefined,+ searchType: undefined,+ }}+ />+ <div className="flex flex-1 flex-col overflow-hidden">+ <DataTable+ tableName={"evalTemplates"}+ columns={columns}+ peekView={peekConfig}+ rowHeight="m"+ customRowHeights={templateTableRowHeights}+ data={+ templates.isLoading+ ? { isLoading: true, isError: false }+ : templates.isError+ ? {+ isLoading: false,+ isError: true,+ error: templates.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: safeExtract(templates.data, "templates", []).map(+ (t) => convertToTableRow(t),+ ),+ }+ }+ pagination={{+ totalCount,+ onChange: setPaginationState,+ state: paginationState,+ }}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={setColumnVisibility}+ />+ </div>+ </div><TablePeekView peekView={peekConfig} /><Dialogopen={!!editTemplateId && template.isSuccess}@@ -419,10 +460,8 @@ export default function EvalsTemplateTable({name: `${cloneTemplate.data.name} (project-level)`,prompt: cloneTemplate.data.prompt,vars: cloneTemplate.data.vars,- outputSchema: cloneTemplate.data.outputSchema as {- score: string;- reasoning: string;- },+ outputDefinition: cloneTemplate.data+ .outputDefinition as EvalTemplate["outputDefinition"],provider: cloneTemplate.data.provider,model: cloneTemplate.data.model,modelParams: cloneTemplate.data.modelParams as any,diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsxindex 4f75ad90b3..87e409d25b 100644--- a/web/src/features/evals/components/template-form.tsx+++ b/web/src/features/evals/components/template-form.tsx@@ -1,5 +1,5 @@import { useEffect, useState } from "react";-import { useForm } from "react-hook-form";+import { useFieldArray, useForm } from "react-hook-form";import { z } from "zod/v4";import { Input } from "@/src/components/ui/input";import { Button } from "@/src/components/ui/button";@@ -14,21 +14,34 @@ import {} from "@/src/components/ui/form";import { api } from "@/src/utils/api";import { zodResolver } from "@hookform/resolvers/zod";-import { extractVariables, getIsCharOrUnderscore } from "@langfuse/shared";+import {+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ EvalOutputDataTypeSchema,+ getCategoricalCategoryRuleViolations,+ getMinimumCategoricalCategoriesMessage,+ MinimumCategoricalCategoryCount,+ type PersistedEvalOutputDefinition,+ PersistedEvalOutputDefinitionSchema,+ ScoreDataTypeEnum,+ extractVariables,+ getIsCharOrUnderscore,+ resolvePersistedEvalOutputDefinition,+} from "@langfuse/shared";import router from "next/router";import { type EvalTemplate } from "@langfuse/shared";import { ModelParameters } from "@/src/components/ModelParameters";-import {- OutputSchema,- type ModelParams,- ZodModelConfig,-} from "@langfuse/shared";+import { type ModelParams, ZodModelConfig } from "@langfuse/shared";import { PromptVariableListPreview } from "@/src/features/prompts/components/PromptVariableListPreview";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { getFinalModelParams } from "@/src/utils/getFinalModelParams";import { useModelParams } from "@/src/features/playground/page/hooks/useModelParams";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { EvalReferencedEvaluators } from "@/src/features/evals/types";+import {+ getDefaultOutputDefinitionFormValues,+ shouldReplaceDefaultOutputDefinitionField,+} from "@/src/features/evals/utils/template-form-defaults";import { CodeMirrorEditor } from "@/src/components/editor";import { Card, CardContent } from "@/src/components/ui/card";import { type RouterInput } from "@/src/utils/types";@@ -36,8 +49,15 @@ import { useEvaluationModel } from "@/src/features/evals/hooks/useEvaluationModeimport { Checkbox } from "@/src/components/ui/checkbox";import { ManageDefaultEvalModel } from "@/src/features/evals/components/manage-default-eval-model";import { DialogFooter, DialogBody } from "@/src/components/ui/dialog";-import { AlertCircle } from "lucide-react";+import { AlertCircle, PlusIcon, Trash } from "lucide-react";import { useValidateCustomModel } from "@/src/features/evals/hooks/useValidateCustomModel";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";type PartialEvalTemplate = Omit<EvalTemplate,@@ -58,7 +78,7 @@ export const EvalTemplateForm = (props: {cloneSourceId?: string | null;}) => {return (- <div className="w-full">+ <div className="max-w-6xl"><InnerEvalTemplateFormkey={props.existingEvalTemplate?.id ?? "new"}{...props}@@ -74,10 +94,8 @@ export const EvalTemplateForm = (props: {name: props.existingEvalTemplate.name,prompt: props.existingEvalTemplate.prompt,vars: props.existingEvalTemplate.vars,- outputSchema: props.existingEvalTemplate.outputSchema as {- score: string;- reasoning: string;- },+ outputDefinition: props.existingEvalTemplate+ .outputDefinition as PersistedEvalOutputDefinition,selectedModel: props.existingEvalTemplate.provider? {provider: props.existingEvalTemplate.provider as string,@@ -102,43 +120,102 @@ const selectedModelSchema = z.object({modelParams: ZodModelConfig,});-const formSchema = z.object({- name: z.string().min(1, "Enter a name"),- prompt: z- .string()- .min(1, "Enter a prompt")- .refine((val) => {- const variables = extractVariables(val);- const matches = variables.map((variable) => {- // check regex here- if (variable.match(/^[A-Za-z_]+$/)) {- return true;- }- return false;- });- return !matches.includes(false);- }, "Variables must only contain letters and underscores (_)"),-- variables: z.array(- z.string().min(1, "Variables must have at least one character"),- ),- outputScore: z.string().min(1, "Enter a score function"),- outputReasoning: z.string().min(1, "Enter a reasoning function"),- referencedEvaluators: z- .enum(EvalReferencedEvaluators)- .optional()- .default(EvalReferencedEvaluators.PERSIST),- shouldUseDefaultModel: z.boolean().default(true),+const categoricalOptionSchema = z.object({+ value: z.string().trim().min(1, "Enter a category value"),});+const formSchema = z+ .object({+ name: z.string().min(1, "Enter a name"),+ prompt: z+ .string()+ .min(1, "Enter a prompt")+ .refine((val) => {+ const variables = extractVariables(val);+ const matches = variables.map((variable) => {+ // check regex here+ if (variable.match(/^[A-Za-z_]+$/)) {+ return true;+ }+ return false;+ });+ return !matches.includes(false);+ }, "Variables must only contain letters and underscores (_)"),++ variables: z.array(+ z.string().min(1, "Variables must have at least one character"),+ ),+ scoreDataType: EvalOutputDataTypeSchema.default(ScoreDataTypeEnum.NUMERIC),+ scoreDescription: z.string().min(1, "Enter a score function"),+ reasoningDescription: z.string().min(1, "Enter a reasoning function"),+ categories: z.array(categoricalOptionSchema).default([]),+ shouldAllowMultipleMatches: z.boolean().default(false),+ referencedEvaluators: z+ .enum(EvalReferencedEvaluators)+ .optional()+ .default(EvalReferencedEvaluators.PERSIST),+ shouldUseDefaultModel: z.boolean().default(true),+ })+ .superRefine((value, ctx) => {+ if (value.scoreDataType !== ScoreDataTypeEnum.CATEGORICAL) {+ return;+ }++ getCategoricalCategoryRuleViolations(+ value.categories.map((category) => category.value),+ ).forEach((violation) => {+ switch (violation.type) {+ case "minimum_count":+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: getMinimumCategoricalCategoriesMessage(),+ path: ["categories"],+ });+ return;+ case "duplicate_value":+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Categories must be unique",+ path: ["categories", violation.index, "value"],+ });+ return;+ }+ });+ });++const toOutputDefinitionFormValues = (+ outputDefinition?: PersistedEvalOutputDefinition,+) => {+ if (!outputDefinition) {+ return getDefaultOutputDefinitionFormValues();+ }++ const resolvedOutputDefinition = resolvePersistedEvalOutputDefinition(+ PersistedEvalOutputDefinitionSchema.parse(outputDefinition),+ );++ return {+ scoreDataType: resolvedOutputDefinition.dataType,+ reasoningDescription: resolvedOutputDefinition.reasoningDescription,+ scoreDescription: resolvedOutputDefinition.scoreDescription,+ shouldAllowMultipleMatches:+ resolvedOutputDefinition.dataType === ScoreDataTypeEnum.CATEGORICAL+ ? resolvedOutputDefinition.shouldAllowMultipleMatches+ : false,+ categories:+ resolvedOutputDefinition.dataType === ScoreDataTypeEnum.CATEGORICAL+ ? resolvedOutputDefinition.categories.map((category) => ({+ value: category,+ }))+ : [],+ };+};+export type EvalTemplateFormPreFill = {name: string;prompt: string;vars: string[];- outputSchema: {- score: string;- reasoning: string;- };+ outputDefinition: PersistedEvalOutputDefinition;selectedModel?: {provider: string;model: string;@@ -200,6 +277,10 @@ export const InnerEvalTemplateForm = (props: {props.preFilledFormValues?.selectedModel,);+ const outputDefinitionFormValues = toOutputDefinitionFormValues(+ props.preFilledFormValues?.outputDefinition,+ );+// updates the form based on the pre-filled data// either form update or from langfuse-generated templateconst form = useForm({@@ -210,17 +291,64 @@ export const InnerEvalTemplateForm = (props: {props.existingEvalTemplateName ?? props.preFilledFormValues?.name ?? "",prompt: props.preFilledFormValues?.prompt ?? undefined,variables: props.preFilledFormValues?.vars ?? [],- outputReasoning: props.preFilledFormValues- ? OutputSchema.parse(props.preFilledFormValues?.outputSchema).reasoning- : "One sentence reasoning for the score",- outputScore: props.preFilledFormValues- ? OutputSchema.parse(props.preFilledFormValues?.outputSchema).score- : "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive.",+ scoreDataType: outputDefinitionFormValues.scoreDataType,+ reasoningDescription: outputDefinitionFormValues.reasoningDescription,+ scoreDescription: outputDefinitionFormValues.scoreDescription,+ categories: outputDefinitionFormValues.categories,+ shouldAllowMultipleMatches:+ outputDefinitionFormValues.shouldAllowMultipleMatches,shouldUseDefaultModel: isExistingUsingDefault,},});+ const {+ fields: categoryFields,+ append,+ remove,+ replace,+ } = useFieldArray({+ control: form.control,+ name: "categories",+ });+const useDefaultModel = form.watch("shouldUseDefaultModel");+ const scoreDataType = form.watch("scoreDataType");+ const isCategoricalOutput = scoreDataType === ScoreDataTypeEnum.CATEGORICAL;+ const shouldAllowMultipleMatches = form.watch("shouldAllowMultipleMatches");+ const categoriesError = form.formState.errors.categories;+ const categoriesErrorMessage =+ typeof categoriesError?.message === "string"+ ? categoriesError.message+ : typeof categoriesError?.root?.message === "string"+ ? categoriesError.root.message+ : undefined;++ const applyDefaultOutputDefinitionCopy = (params: {+ scoreDataType:+ | typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.CATEGORICAL;+ shouldAllowMultipleMatches: boolean;+ }) => {+ const defaults = getDefaultOutputDefinitionFormValues(params);++ if (+ shouldReplaceDefaultOutputDefinitionField({+ currentValue: form.getValues("reasoningDescription"),+ field: "reasoningDescription",+ })+ ) {+ form.setValue("reasoningDescription", defaults.reasoningDescription);+ }++ if (+ shouldReplaceDefaultOutputDefinitionField({+ currentValue: form.getValues("scoreDescription"),+ field: "scoreDescription",+ })+ ) {+ form.setValue("scoreDescription", defaults.scoreDescription);+ }+ };const extractedVariables = form.watch("prompt")? extractVariables(form.watch("prompt")).filter(getIsCharOrUnderscore)@@ -274,6 +402,19 @@ export const InnerEvalTemplateForm = (props: {: "eval_templates:new_form_submit",);+ const outputDefinition =+ values.scoreDataType === ScoreDataTypeEnum.CATEGORICAL+ ? createCategoricalEvalOutputDefinition({+ scoreDescription: values.scoreDescription,+ reasoningDescription: values.reasoningDescription,+ categories: values.categories.map((category) => category.value),+ shouldAllowMultipleMatches: values.shouldAllowMultipleMatches,+ })+ : createNumericEvalOutputDefinition({+ scoreDescription: values.scoreDescription,+ reasoningDescription: values.reasoningDescription,+ });+const evalTemplate = {name: values.name,projectId: props.projectId,@@ -287,10 +428,7 @@ export const InnerEvalTemplateForm = (props: {? undefined: getFinalModelParams(modelParams),vars: extractedVariables ?? [],- outputSchema: {- score: values.outputScore,- reasoning: values.outputReasoning,- },+ outputDefinition,referencedEvaluators: values.referencedEvaluators,sourceTemplateId: props.cloneSourceId ?? undefined,};@@ -474,7 +612,170 @@ export const InnerEvalTemplateForm = (props: {<FormFieldcontrol={form.control}- name="outputReasoning"+ name="scoreDataType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Score type</FormLabel>+ <FormDescription>+ Choose whether the evaluator should return a numeric score or+ one of a fixed set of categories.+ </FormDescription>+ <Select+ value={field.value}+ disabled={!props.isEditing}+ onValueChange={(value) => {+ const nextScoreDataType = value as+ | typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.CATEGORICAL;+ const shouldEnableMultipleMatches =+ nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL+ ? form.getValues("shouldAllowMultipleMatches")+ : false;++ field.onChange(nextScoreDataType);++ if (+ nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL &&+ (form.getValues("categories") ?? []).length === 0+ ) {+ replace(+ Array.from(+ { length: MinimumCategoricalCategoryCount },+ () => ({ value: "" }),+ ),+ );+ }++ if (nextScoreDataType !== ScoreDataTypeEnum.CATEGORICAL) {+ form.setValue("shouldAllowMultipleMatches", false);+ }++ applyDefaultOutputDefinitionCopy({+ scoreDataType: nextScoreDataType,+ shouldAllowMultipleMatches:+ shouldEnableMultipleMatches ?? false,+ });+ }}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select a score type" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value={ScoreDataTypeEnum.NUMERIC}>+ Numeric+ </SelectItem>+ <SelectItem value={ScoreDataTypeEnum.CATEGORICAL}>+ Categorical+ </SelectItem>+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />++ {isCategoricalOutput ? (+ <FormField+ control={form.control}+ name="categories"+ render={() => (+ <FormItem>+ <div>+ <FormLabel>Categories</FormLabel>+ <FormDescription>+ Add the allowed category values the model may return.+ Categories must be exhaustive. If you need a catch-all+ outcome (e.g. 'No match'), add it explicitly as+ one of the categories.+ </FormDescription>+ </div>+ <div className="space-y-3">+ {categoryFields.map((field, index) => (+ <div+ key={field.id}+ className="grid gap-3 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_auto]"+ >+ <FormField+ control={form.control}+ name={`categories.${index}.value`}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="text-muted-foreground text-xs">+ Category+ </FormLabel>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <div className="flex items-end">+ <Button+ type="button"+ variant="ghost"+ size="icon"+ disabled={!props.isEditing}+ onClick={() => remove(index)}+ >+ <Trash className="text-muted-foreground h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}+ </div>+ <Button+ type="button"+ variant="outline"+ className="text-muted-foreground"+ disabled={!props.isEditing}+ onClick={() => append({ value: "" })}+ >+ <PlusIcon className="mr-1.5 h-4 w-4" />+ Add category+ </Button>+ <FormField+ control={form.control}+ name="shouldAllowMultipleMatches"+ render={({ field }) => (+ <FormItem className="mt-3 flex flex-row items-center space-y-0 space-x-3">+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={(checked) => {+ field.onChange(checked);+ applyDefaultOutputDefinitionCopy({+ scoreDataType: ScoreDataTypeEnum.CATEGORICAL,+ shouldAllowMultipleMatches: Boolean(checked),+ });+ }}+ disabled={!props.isEditing}+ />+ </FormControl>+ <div className="space-y-0.5 leading-none">+ <FormLabel>Allow multiple matches</FormLabel>+ <FormDescription>+ Lets the model return more than one category. One+ score will be created for each selected match.+ </FormDescription>+ </div>+ </FormItem>+ )}+ />+ {categoriesErrorMessage ? (+ <p className="text-destructive text-sm font-medium">+ {categoriesErrorMessage}+ </p>+ ) : null}+ </FormItem>+ )}+ />+ ) : null}+ <FormField+ control={form.control}+ name="reasoningDescription"render={({ field }) => (<FormItem><FormLabel>Score reasoning prompt</FormLabel>@@ -493,13 +794,20 @@ export const InnerEvalTemplateForm = (props: {<FormFieldcontrol={form.control}- name="outputScore"+ name="scoreDescription"render={({ field }) => (<FormItem>- <FormLabel>Score range prompt</FormLabel>+ <FormLabel>+ {isCategoricalOutput+ ? "Category selection prompt"+ : "Score output prompt"}+ </FormLabel><FormDescription>- Define how the LLM should return the evaluation score in- natural language. Needs to yield a numeric value.+ {isCategoricalOutput+ ? shouldAllowMultipleMatches+ ? "Define how the LLM should choose one or more categories from the list below."+ : "Define how the LLM should choose exactly one category from the list below."+ : "Define how the LLM should return the evaluation score in natural language. Needs to yield a numeric value."}</FormDescription><FormControl><Input {...field} />@@ -519,7 +827,7 @@ export const InnerEvalTemplateForm = (props: {<Buttontype="submit"loading={createEvalTemplateMutation.isPending}- className="max-w-fit"+ className="w-full">Save</Button>diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.tsindex e99bbc1703..d3208a94d2 100644--- a/web/src/features/evals/server/router.ts+++ b/web/src/features/evals/server/router.ts@@ -7,6 +7,7 @@ import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAcimport { auditLog } from "@/src/features/audit-logs/auditLog";import {DEFAULT_TRACE_JOB_DELAY,+ compilePersistedEvalOutputDefinition,ZodModelConfig,deriveEvaluatorDisplayStateFromExecutionCounts,type OrderByState,@@ -23,6 +24,7 @@ import {orderBy,jsonSchema,EvalTargetObject,+ PersistedEvalOutputDefinitionSchema,} from "@langfuse/shared";import {getQueue,@@ -93,13 +95,13 @@ const ConfigWithTemplateSchema = z.object({model: z.string().nullable(),modelParams: jsonSchema.nullable(),vars: z.array(z.string()),- outputSchema: jsonSchema,+ outputDefinition: jsonSchema,version: z.number(),}).nullish(),});-type ConfigWithTemplate = z.infer<typeof ConfigWithTemplateSchema>;+type EvalJobConfigWithTemplate = z.infer<typeof ConfigWithTemplateSchema>;/*** Use this function when pulling a list of evaluators from the database before using in the application to ensure type safety.@@ -110,7 +112,7 @@ type ConfigWithTemplate = z.infer<typeof ConfigWithTemplateSchema>;const filterAndValidateDbEvaluatorList = (evaluators: JobConfiguration[],onParseError?: (error: z.ZodError) => void,-): ConfigWithTemplate[] =>+): EvalJobConfigWithTemplate[] =>evaluators.reduce((acc, ts) => {const result = ConfigWithTemplateSchema.safeParse(ts);if (result.success) {@@ -120,9 +122,9 @@ const filterAndValidateDbEvaluatorList = (onParseError?.(result.error);}return acc;- }, [] as ConfigWithTemplate[]);+ }, [] as EvalJobConfigWithTemplate[]);-export const CreateEvalTemplate = z.object({+export const CreateEvalTemplateInputSchema = z.object({name: z.string().min(1),projectId: z.string(),prompt: z.string(),@@ -130,10 +132,7 @@ export const CreateEvalTemplate = z.object({model: z.string().nullish(),modelParams: ZodModelConfig.nullish(),vars: z.array(z.string()),- outputSchema: z.object({- score: z.string(),- reasoning: z.string(),- }),+ outputDefinition: PersistedEvalOutputDefinitionSchema,cloneSourceId: z.string().optional(),referencedEvaluators: z.enum(EvalReferencedEvaluators)@@ -171,7 +170,7 @@ const UpdateEvalJobSchema = z.object({timeScope: TimeScopeSchema.optional(),});-const validateEvalTemplateActivation = async ({+const validateEvalTemplateCanRun = async ({prisma,projectId,evalTemplateId,@@ -209,11 +208,19 @@ const validateEvalTemplateActivation = async ({}try {+ const parsedOutputDefinition = PersistedEvalOutputDefinitionSchema.parse(+ template.outputDefinition,+ );+ const compiledOutputDefinition = compilePersistedEvalOutputDefinition(+ parsedOutputDefinition,+ );+await testModelCall({provider: modelConfig.config.provider,model: modelConfig.config.model,apiKey: modelConfig.config.apiKey,modelConfig: modelConfig.config.modelParams,+ structuredOutputSchema: compiledOutputDefinition.outputResultSchema,});} catch (err) {const message = err instanceof Error ? err.message : "Unknown error";@@ -494,6 +501,7 @@ export const evalRouter = createTRPCRouter({partner?: string;provider?: string;model?: string;+ outputDefinition: unknown;}>>`WITH latest_templates AS (@@ -506,6 +514,7 @@ export const evalRouter = createTRPCRouter({et.partner,et.version,et.created_at,+ et.output_schema,(SELECT COUNT(jc.id)FROM job_configurations jc@@ -534,6 +543,7 @@ export const evalRouter = createTRPCRouter({project_id as "projectId",version,created_at as "latestCreatedAt",+ output_schema as "outputDefinition",COALESCE(usage_count, 0)::int as "usageCount"FROMlatest_templates@@ -805,7 +815,7 @@ export const evalRouter = createTRPCRouter({return { id: job.id };}),createTemplate: protectedProjectProcedure- .input(CreateEvalTemplate)+ .input(CreateEvalTemplateInputSchema).mutation(async ({ input, ctx }) => {throwIfNoProjectAccess({session: ctx.session,@@ -834,6 +844,9 @@ export const evalRouter = createTRPCRouter({model: modelConfig.config.model,apiKey: modelConfig.config.apiKey,modelConfig: input.modelParams,+ structuredOutputSchema: compilePersistedEvalOutputDefinition(+ input.outputDefinition,+ ).outputResultSchema,});} catch (err) {const message = err instanceof Error ? err.message : "Unknown error";@@ -888,7 +901,7 @@ export const evalRouter = createTRPCRouter({model: input.model,modelParams: input.modelParams ?? undefined,vars: input.vars,- outputSchema: input.outputSchema,+ outputDefinition: input.outputDefinition,},});@@ -1030,7 +1043,7 @@ export const evalRouter = createTRPCRouter({newStatus === JobConfigState.ACTIVE &&filteredEvaluators.length > 0) {- await validateEvalTemplateActivation({+ await validateEvalTemplateCanRun({prisma: ctx.prisma,projectId,evalTemplateId,@@ -1157,7 +1170,7 @@ export const evalRouter = createTRPCRouter({});}- await validateEvalTemplateActivation({+ await validateEvalTemplateCanRun({prisma: ctx.prisma,projectId,evalTemplateId: existingJob.evalTemplateId,diff --git a/web/src/features/evals/utils/template-form-defaults.ts b/web/src/features/evals/utils/template-form-defaults.tsnew file mode 100644index 0000000000..24f2022ee7--- /dev/null+++ b/web/src/features/evals/utils/template-form-defaults.ts@@ -0,0 +1,75 @@+import { ScoreDataTypeEnum } from "@langfuse/shared";++export const numericOutputDefinitionDefaults = {+ scoreDataType: ScoreDataTypeEnum.NUMERIC,+ reasoningDescription: "Explain the assigned score in one concise sentence.",+ scoreDescription:+ "Return a numeric score between 0 and 1, where 0 is the worst outcome and 1 is the best outcome.",+ categories: [] as Array<{ value: string }>,+ shouldAllowMultipleMatches: false,+};++export const categoricalSingleOutputDefinitionDefaults = {+ scoreDataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoningDescription: "Explain why the selected category is the best match.",+ scoreDescription: "Choose exactly one category from the provided list.",+ categories: [] as Array<{ value: string }>,+ shouldAllowMultipleMatches: false,+};++export const categoricalMultiOutputDefinitionDefaults = {+ scoreDataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoningDescription: "Explain why each selected category applies.",+ scoreDescription:+ "Choose one or more categories from the provided list. Only return categories that clearly apply.",+ categories: [] as Array<{ value: string }>,+ shouldAllowMultipleMatches: true,+};++export const getDefaultOutputDefinitionFormValues = (params?: {+ scoreDataType?:+ | typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.CATEGORICAL;+ shouldAllowMultipleMatches?: boolean;+}) => {+ if (params?.scoreDataType === ScoreDataTypeEnum.CATEGORICAL) {+ return params.shouldAllowMultipleMatches+ ? categoricalMultiOutputDefinitionDefaults+ : categoricalSingleOutputDefinitionDefaults;+ }++ return numericOutputDefinitionDefaults;+};++const defaultReasoningDescriptions = new Set(+ [+ numericOutputDefinitionDefaults.reasoningDescription,+ categoricalSingleOutputDefinitionDefaults.reasoningDescription,+ categoricalMultiOutputDefinitionDefaults.reasoningDescription,+ "One sentence reasoning for the score",+ ].map((value) => value.trim()),+);++const defaultScoreDescriptions = new Set(+ [+ numericOutputDefinitionDefaults.scoreDescription,+ categoricalSingleOutputDefinitionDefaults.scoreDescription,+ categoricalMultiOutputDefinitionDefaults.scoreDescription,+ "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive.",+ ].map((value) => value.trim()),+);++export const shouldReplaceDefaultOutputDefinitionField = (params: {+ currentValue?: string;+ field: "reasoningDescription" | "scoreDescription";+}) => {+ const trimmedValue = params.currentValue?.trim() ?? "";++ if (!trimmedValue) {+ return true;+ }++ return params.field === "reasoningDescription"+ ? defaultReasoningDescriptions.has(trimmedValue)+ : defaultScoreDescriptions.has(trimmedValue);+};diff --git a/web/src/features/evals/utils/template-output.clienttest.ts b/web/src/features/evals/utils/template-output.clienttest.tsnew file mode 100644index 0000000000..fcac93feb1--- /dev/null+++ b/web/src/features/evals/utils/template-output.clienttest.ts@@ -0,0 +1,43 @@+import {+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+} from "@langfuse/shared";+import { getTemplateResultType } from "./template-output";++describe("getTemplateResultType", () => {+ it("returns Numeric for numeric output definitions", () => {+ expect(+ getTemplateResultType(+ createNumericEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "How good",+ }),+ ),+ ).toBe("Numeric");+ });++ it("returns Categorical for categorical output definitions", () => {+ expect(+ getTemplateResultType(+ createCategoricalEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "Classification",+ categories: ["correct", "incorrect"],+ }),+ ),+ ).toBe("Categorical");+ });++ it("returns Numeric for legacy output definitions", () => {+ expect(+ getTemplateResultType({+ reasoning: "Why",+ score: "How good",+ }),+ ).toBe("Numeric");+ });++ it("returns Unknown for invalid output definitions", () => {+ expect(getTemplateResultType({ foo: "bar" })).toBe("Unknown");+ });+});diff --git a/web/src/features/evals/utils/template-output.ts b/web/src/features/evals/utils/template-output.tsnew file mode 100644index 0000000000..a61fabeed4--- /dev/null+++ b/web/src/features/evals/utils/template-output.ts@@ -0,0 +1,32 @@+import {+ PersistedEvalOutputDefinitionSchema,+ resolvePersistedEvalOutputDefinition,+ ScoreDataTypeEnum,+} from "@langfuse/shared";++export const getTemplateResultType = (outputDefinition: unknown) => {+ if (typeof outputDefinition !== "object" || outputDefinition === null) {+ return "Unknown";+ }++ const hasStructuredOutputMarkers =+ "version" in outputDefinition || "dataType" in outputDefinition;+ const hasLegacyOutputMarkers =+ "reasoning" in outputDefinition || "score" in outputDefinition;++ if (!hasStructuredOutputMarkers && !hasLegacyOutputMarkers) {+ return "Unknown";+ }++ const parsedOutputDefinition =+ PersistedEvalOutputDefinitionSchema.safeParse(outputDefinition);++ if (!parsedOutputDefinition.success) {+ return "Unknown";+ }++ return resolvePersistedEvalOutputDefinition(parsedOutputDefinition.data)+ .dataType === ScoreDataTypeEnum.CATEGORICAL+ ? "Categorical"+ : "Numeric";+};diff --git a/web/src/features/evals/utils/typeHelpers.ts b/web/src/features/evals/utils/typeHelpers.tsindex 19ed78d446..42686da16b 100644--- a/web/src/features/evals/utils/typeHelpers.ts+++ b/web/src/features/evals/utils/typeHelpers.ts@@ -1,5 +1,4 @@import {- type EvalTemplate,EvalTargetObject,type EvalTargetObject as EvalTargetObjectType,} from "@langfuse/shared";@@ -10,12 +9,10 @@ const getPartnerName = (partner: string) => {return partnerIdentifierToName.get(partner) ?? "Unknown";};-export const getMaintainer = (- evalTemplate: Partial<EvalTemplate> & {- partner?: string | null;- projectId: string | null;- },-) => {+export const getMaintainer = (evalTemplate: {+ partner?: string | null;+ projectId: string | null;+}) => {if (evalTemplate.projectId === null) {if (evalTemplate.partner) {return `${getPartnerName(evalTemplate.partner)} maintained`;diff --git a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts b/web/src/features/experiments/hooks/useExperimentEvaluatorData.tsindex 8ef4c4f170..7026910dab 100644--- a/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts+++ b/web/src/features/experiments/hooks/useExperimentEvaluatorData.ts@@ -104,8 +104,8 @@ export function useExperimentEvaluatorData({...config,evalTemplate: {...config.evalTemplate,- outputSchema: config.evalTemplate- .outputSchema as EvalTemplate["outputSchema"],+ outputDefinition: config.evalTemplate+ .outputDefinition as EvalTemplate["outputDefinition"],},} as PartialConfig & { evalTemplate: EvalTemplate };diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.tsindex bed1e7029b..633b97678d 100644--- a/worker/src/__tests__/batchAction.test.ts+++ b/worker/src/__tests__/batchAction.test.ts@@ -259,7 +259,7 @@ describe("select all test suite", () => {model: "gpt-3.5-turbo",provider: "openai",modelParams: {},- outputSchema: {+ outputDefinition: {reasoning: "Please explain your reasoning",score: "Please provide a score between 0 and 1",},@@ -454,7 +454,7 @@ describe("select all test suite", () => {model: "gpt-3.5-turbo",provider: "openai",modelParams: {},- outputSchema: {+ outputDefinition: {reasoning: "Please explain your reasoning",score: "Please provide a score between 0 and 1",},diff --git a/worker/src/__tests__/evalService.filtering.test.ts b/worker/src/__tests__/evalService.filtering.test.tsindex 5fd4bc1cff..ed2dec330c 100644--- a/worker/src/__tests__/evalService.filtering.test.ts+++ b/worker/src/__tests__/evalService.filtering.test.ts@@ -127,7 +127,7 @@ const test = baseTest.extend<{provider: "openai",modelParams: { temperature: 0 },vars: [],- outputSchema: {+ outputDefinition: {type: "object",properties: { score: { type: "number" } },},diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex 5010c4bdcf..755351a215 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -2931,7 +2931,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;prompt: "Please evaluate: {{input}}",version: 1,vars: ["input"],- outputSchema: {+ outputDefinition: {score: "score",reasoning: "reasoning",},@@ -3006,6 +3006,108 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;}, 15_000);});+ describe("legacy eval output definition backward compatibility", () => {+ test("executes a legacy numeric outputDefinition template", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const traceId = randomUUID();+ const jobExecutionId = randomUUID();+ const templateId = randomUUID();++ vi.mocked(fetchLLMCompletion).mockResolvedValueOnce({+ score: 0,+ reasoning: "The response is safe and not toxic.",+ });++ await upsertTrace({+ id: traceId,+ project_id: projectId,+ user_id: "a",+ input: JSON.stringify({ input: "This is a great prompt" }),+ output: JSON.stringify({ output: "This is a great response" }),+ timestamp: convertDateToClickhouseDateTime(new Date()),+ created_at: convertDateToClickhouseDateTime(new Date()),+ updated_at: convertDateToClickhouseDateTime(new Date()),+ });++ await prisma.evalTemplate.create({+ data: {+ id: templateId,+ name: "legacy-output-definition-template",+ projectId,+ model: "gpt-3.5-turbo",+ provider: "openai",+ prompt: "Please evaluate toxicity {{input}} {{output}}",+ version: 1,+ vars: ["input", "output"],+ outputDefinition: {+ score: "Please provide a score between 0 and 1",+ reasoning: "Please explain your reasoning",+ },+ },+ });++ const jobConfiguration = await prisma.jobConfiguration.create({+ data: {+ id: randomUUID(),+ projectId,+ filter: JSON.parse("[]"),+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("1"),+ targetObject: EvalTargetObject.TRACE,+ scoreName: "legacy-score",+ variableMapping: JSON.parse("[]"),+ status: "ACTIVE",+ evalTemplateId: templateId,+ },+ });++ await prisma.jobExecution.create({+ data: {+ id: jobExecutionId,+ projectId,+ jobConfigurationId: jobConfiguration.id,+ jobInputTraceId: traceId,+ jobTemplateId: templateId,+ status: "PENDING",+ startTime: new Date(),+ },+ });++ await kyselyPrisma.$kysely+ .insertInto("llm_api_keys")+ .values({+ id: randomUUID(),+ project_id: projectId,+ secret_key: encrypt(String(OPENAI_API_KEY)),+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ custom_models: [],+ display_secret_key: "123456",+ })+ .execute();++ await evaluate({+ event: {+ projectId,+ jobExecutionId,+ },+ });++ const updatedJobExecution = await prisma.jobExecution.findUnique({+ where: {+ id: jobExecutionId,+ projectId,+ },+ });++ expect(updatedJobExecution?.status).toBe("COMPLETED");+ expect(updatedJobExecution?.jobOutputScoreId).toBeTruthy();+ expect(updatedJobExecution?.executionTraceId).toBeTruthy();+ expect(updatedJobExecution?.endTime).not.toBeNull();+ }, 20_000);+ });+describe("internal trace environment filtering", () => {test("does not create eval jobs for trace-upsert with LLMJudge environment", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.tsindex 78a7aff991..188c5bfd2e 100644--- a/worker/src/__tests__/llmConnections.test.ts+++ b/worker/src/__tests__/llmConnections.test.ts@@ -4,7 +4,15 @@ import {type CompletionWithReasoning,} from "@langfuse/shared/src/server";import { encrypt } from "@langfuse/shared/encryption";-import { ChatMessageType, LLMAdapter } from "@langfuse/shared";+import {+ buildEvalOutputResultSchema,+ ChatMessageType,+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ type PersistedEvalOutputDefinition,+ LLMAdapter,+ type ModelParams,+} from "@langfuse/shared";import { z } from "zod/v4";/**@@ -14,7 +22,7 @@ import { z } from "zod/v4";* Each adapter is tested with:* 1. Simple completion* 2. Streaming completion- * 3. Structured output (using eval schema: {score: number, reasoning: string})+ * 3. Structured output (legacy eval schema, v2 numeric schema, v2 categorical schema)* 4. Tool calling** Required environment variables (tests will FAIL if not set):@@ -30,12 +38,112 @@ import { z } from "zod/v4";* - LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY*/-// Eval schema matching production usage-const evalOutputSchema = z.object({+type TestLLMConnection = {+ secretKey: string;+ extraHeaders?: string | null;+ baseURL?: string | null;+ config?: Record<string, string> | null;+};++const numericEvalResponseSchema = z.object({score: z.number(),- reasoning: z.string(),+ reasoning: z.string().min(1),+});++const categoricalScoreValues = ["correct", "incorrect"] as const;+const categoricalEvalResponseSchema = z.object({+ score: z.enum(categoricalScoreValues),+ reasoning: z.string().min(1),});+type EvalStructuredOutputTestCase = {+ name: string;+ prompt: string;+ outputDefinition: PersistedEvalOutputDefinition;+ responseSchema: z.ZodTypeAny;+ assertParsed?: (data: { score: number | string; reasoning: string }) => void;+};++const evalStructuredOutputTestCases: EvalStructuredOutputTestCase[] = [+ {+ name: "structured output - legacy eval schema",+ prompt:+ "Evaluate whether the answer '2 + 2 = 4' is correct. Return a numeric score from 0 to 100 and explain the score.",+ outputDefinition: {+ score:+ "Return a numeric score from 0 to 100, where 100 means the answer is completely correct.",+ reasoning: "Explain briefly why you chose that score.",+ },+ responseSchema: numericEvalResponseSchema,+ },+ {+ name: "structured output - v2 numeric eval schema",+ prompt:+ "Evaluate whether the answer '2 + 2 = 4' is correct. Return a numeric score from 0 to 100 and explain the score.",+ outputDefinition: createNumericEvalOutputDefinition({+ scoreDescription:+ "Return a numeric score from 0 to 100, where 100 means the answer is completely correct.",+ reasoningDescription: "Explain briefly why you chose that score.",+ }),+ responseSchema: numericEvalResponseSchema,+ },+ {+ name: "structured output - v2 categorical eval schema",+ prompt:+ "Judge whether the answer '2 + 2 = 5' is correct. Select the best matching category and explain the choice.",+ outputDefinition: createCategoricalEvalOutputDefinition({+ scoreDescription:+ "Select 'correct' when the answer is mathematically accurate, otherwise select 'incorrect'.",+ reasoningDescription: "Explain briefly why you selected that category.",+ categories: ["correct", "incorrect"],+ }),+ responseSchema: categoricalEvalResponseSchema,+ assertParsed: (data) => {+ expect(data.score).toBe("incorrect");+ },+ },+];++function registerEvalStructuredOutputTests(params: {+ checkEnv: () => void;+ getModelParams: () => ModelParams;+ getLLMConnection: () => TestLLMConnection;+ timeoutMs: number;+}) {+ evalStructuredOutputTestCases.forEach((testCase) => {+ test(+ testCase.name,+ async () => {+ params.checkEnv();++ const completion = await fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: testCase.prompt,+ type: ChatMessageType.PublicAPICreated,+ },+ ],+ modelParams: params.getModelParams(),+ structuredOutputSchema: buildEvalOutputResultSchema(+ testCase.outputDefinition,+ ),+ llmConnection: params.getLLMConnection(),+ });++ const parsed = testCase.responseSchema.safeParse(completion);+ expect(parsed.success).toBe(true);+ if (parsed.success) {+ expect(parsed.data.reasoning.trim().length).toBeGreaterThan(0);+ testCase.assertParsed?.(parsed.data);+ }+ },+ params.timeoutMs,+ );+ });+}+// Common tool definition for tool calling testsconst weatherTool = {name: "get_weather",@@ -131,40 +239,20 @@ describe("LLM Connection Tests", () => {expect(fullResponse).toContain("4");}, 30_000);- test("structured output - eval schema", async () => {- checkEnvVar();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "openai",- adapter: LLMAdapter.OpenAI,- model: MODEL,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: {- secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!),- },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 30_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVar,+ getModelParams: () => ({+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: MODEL,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_OPENAI_KEY!),+ }),+ timeoutMs: 30_000,+ });test("tool calling", async () => {checkEnvVar();@@ -281,42 +369,20 @@ describe("LLM Connection Tests", () => {expect(fullResponse).toContain("4");}, 30_000);- test("structured output - eval schema", async () => {- checkEnvVar();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "anthropic",- adapter: LLMAdapter.Anthropic,- model: MODEL,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: {- secretKey: encrypt(- process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!,- ),- },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 30_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVar,+ getModelParams: () => ({+ provider: "anthropic",+ adapter: LLMAdapter.Anthropic,+ model: MODEL,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_ANTHROPIC_KEY!),+ }),+ timeoutMs: 30_000,+ });test("tool calling", async () => {checkEnvVar();@@ -445,41 +511,21 @@ describe("LLM Connection Tests", () => {expect(fullResponse).toContain("4");}, 60_000);- test("structured output - eval schema", async () => {- checkEnvVars();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "azure",- adapter: LLMAdapter.Azure,- model: process.env.LANGFUSE_LLM_CONNECTION_AZURE_MODEL!,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: {- secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!),- baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,- },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 60_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVars,+ getModelParams: () => ({+ provider: "azure",+ adapter: LLMAdapter.Azure,+ model: process.env.LANGFUSE_LLM_CONNECTION_AZURE_MODEL!,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_AZURE_KEY!),+ baseURL: process.env.LANGFUSE_LLM_CONNECTION_AZURE_BASE_URL!,+ }),+ timeoutMs: 60_000,+ });test("tool calling", async () => {checkEnvVars();@@ -625,38 +671,21 @@ describe("LLM Connection Tests", () => {}, 30_000);// Flaky- test("structured output - eval schema", async () => {- checkEnvVars();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "bedrock",- adapter: LLMAdapter.Bedrock,- model: MODEL,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: { secretKey: encrypt(getApiKey()), config: getConfig() },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 30_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVars,+ getModelParams: () => ({+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ model: MODEL,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(getApiKey()),+ config: getConfig(),+ }),+ timeoutMs: 30_000,+ });test("tool calling", async () => {checkEnvVars();@@ -773,41 +802,21 @@ describe("LLM Connection Tests", () => {expect(fullResponse).toContain("4");}, 30_000);- test("structured output - eval schema", async () => {- checkEnvVar();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "google-vertex-ai",- adapter: LLMAdapter.VertexAI,- model: MODEL,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: {- secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),- config: null,- },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 30_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVar,+ getModelParams: () => ({+ provider: "google-vertex-ai",+ adapter: LLMAdapter.VertexAI,+ model: MODEL,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!),+ config: null,+ }),+ timeoutMs: 30_000,+ });test("tool calling", async () => {checkEnvVar();@@ -998,42 +1007,22 @@ describe("LLM Connection Tests", () => {expect(fullResponse).toContain("4");}, 30_000);- test("structured output - eval schema", async () => {- checkEnvVar();-- const completion = await fetchLLMCompletion({- streaming: false,- messages: [- {- role: "user",- content:- "Evaluate the quality of this response: 'The answer is 42.' Provide a score from 0-100 and reasoning.",- type: ChatMessageType.PublicAPICreated,- },- ],- modelParams: {- provider: "google-ai-studio",- adapter: LLMAdapter.GoogleAIStudio,- model: MODEL,- temperature: 0,- max_tokens: 200,- },- structuredOutputSchema: evalOutputSchema,- llmConnection: {- secretKey: encrypt(- process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,- ),- },- });-- const parsed = evalOutputSchema.safeParse(completion);- expect(parsed.success).toBe(true);- if (parsed.success) {- expect(typeof parsed.data.score).toBe("number");- expect(typeof parsed.data.reasoning).toBe("string");- expect(parsed.data.reasoning.length).toBeGreaterThan(0);- }- }, 30_000);+ registerEvalStructuredOutputTests({+ checkEnv: checkEnvVar,+ getModelParams: () => ({+ provider: "google-ai-studio",+ adapter: LLMAdapter.GoogleAIStudio,+ model: MODEL,+ temperature: 0,+ max_tokens: 200,+ }),+ getLLMConnection: () => ({+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY!,+ ),+ }),+ timeoutMs: 30_000,+ });test("tool calling", async () => {checkEnvVar();diff --git a/worker/src/constants/managed-evaluators.json b/worker/src/constants/managed-evaluators.jsonindex 053fa2dad5..22b5f823bf 100644--- a/worker/src/constants/managed-evaluators.json+++ b/worker/src/constants/managed-evaluators.json@@ -5,7 +5,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Hallucination","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -17,7 +17,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Helpfulness","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -29,7 +29,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Relevance","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -41,7 +41,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Toxicity","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -53,7 +53,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Correctness","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -65,7 +65,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Contextrelevance","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -77,7 +77,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Contextcorrectness","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -89,7 +89,7 @@"updated_at": "2025-05-12T10:15:07.670Z","name": "Conciseness","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -102,7 +102,7 @@"name": "Answer Correctness","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -115,7 +115,7 @@"name": "Answer Relevance","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -128,7 +128,7 @@"name": "Answer Critic","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -141,7 +141,7 @@"name": "Context Precision","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Give verdict as '1' if useful and '0' if not","reasoning": "One sentence reasoning for the score"},@@ -154,7 +154,7 @@"name": "Context Recall","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -167,7 +167,7 @@"name": "Faithfulness","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -180,7 +180,7 @@"name": "Goal Accuracy","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -193,7 +193,7 @@"name": "Simple Criteria","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. Score 0 if false or negative and 1 if true or positive","reasoning": "One sentence reasoning for the score"},@@ -206,7 +206,7 @@"name": "SQL Semantic Equivalence","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1 based on the equivalence of the two SQL queries","reasoning": "One sentence reasoning for the score"},@@ -219,7 +219,7 @@"name": "Topic Adherence Classification","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1, 1 if the topic falls into any of the given reference topics, 0 otherwise","reasoning": "One sentence reasoning for the score"},@@ -232,7 +232,7 @@"name": "Topic Adherence Refusal","partner": "ragas","version": 1,- "outputSchema": {+ "outputDefinition": {"score": "Score between 0 and 1. 1 if the AI refused to answer the question about the topic, 0 otherwise","reasoning": "One sentence reasoning for the score"},diff --git a/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts b/worker/src/features/evaluation/__tests__/productionDeps.integration.test.tsindex 19f06c80b5..f993f85140 100644--- a/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts+++ b/worker/src/features/evaluation/__tests__/productionDeps.integration.test.ts@@ -113,6 +113,57 @@ describe("Production Dependency Factories Integration Tests", () => {expect(dbRecord?.jobInputTraceId).toBe(traceId);expect(dbRecord?.jobInputObservationId).toBe(observationId);expect(dbRecord?.status).toBe("PENDING");+ expect(dbRecord?.startTime).toBeInstanceOf(Date);+ }, 15_000);++ it("should preserve the original start time on upsert updates", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ const jobConfig = await prisma.jobConfiguration.create({+ data: {+ id: randomUUID(),+ projectId,+ filter: [],+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("1"),+ targetObject: EvalTargetObject.EVENT,+ scoreName: "test-score",+ variableMapping: [],+ },+ });++ const jobExecutionId = randomUUID();+ const originalStartTime = new Date("2026-01-01T12:00:00.000Z");++ await prisma.jobExecution.create({+ data: {+ id: jobExecutionId,+ projectId,+ jobConfigurationId: jobConfig.id,+ jobInputTraceId: randomUUID(),+ jobInputObservationId: randomUUID(),+ status: "PENDING",+ startTime: originalStartTime,+ },+ });++ await deps.upsertJobExecution({+ id: jobExecutionId,+ projectId,+ jobConfigurationId: jobConfig.id,+ jobInputTraceId: randomUUID(),+ jobInputObservationId: randomUUID(),+ jobTemplateId: null,+ status: "COMPLETED",+ });++ const updatedRecord = await prisma.jobExecution.findUnique({+ where: { id: jobExecutionId },+ });++ expect(updatedRecord?.status).toBe("COMPLETED");+ expect(updatedRecord?.startTime).toEqual(originalStartTime);}, 15_000);});diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.tsindex b7fd677aa4..080c190fec 100644--- a/worker/src/features/evaluation/evalExecutionDeps.ts+++ b/worker/src/features/evaluation/evalExecutionDeps.ts@@ -10,9 +10,13 @@ import {ScoreEventType,} from "@langfuse/shared/src/server";import { env } from "../../env";-import { buildEvalScoreSchema, buildEvalMessages } from "./evalExecutionUtils";+import { buildEvalMessages } from "./evalRuntime";import { getEvalS3StorageClient } from "./s3StorageClient";+type StructuredOutputSchema = NonNullable<+ Parameters<typeof fetchLLMCompletion>[0]["structuredOutputSchema"]+>;+/*** Result of fetching model configuration.*/@@ -41,7 +45,7 @@ export type ModelConfigResult =export interface LLMCallParams {messages: ReturnType<typeof buildEvalMessages>;modelConfig: Extract<ModelConfigResult, { valid: true }>["config"];- structuredOutputSchema: ReturnType<typeof buildEvalScoreSchema>;+ structuredOutputSchema: StructuredOutputSchema;traceSinkParams: {targetProjectId: string;traceId: string;diff --git a/worker/src/features/evaluation/evalExecutionUtils.test.ts b/worker/src/features/evaluation/evalExecutionUtils.test.tsdeleted file mode 100644index 7457b8f7ba..0000000000--- a/worker/src/features/evaluation/evalExecutionUtils.test.ts+++ /dev/null@@ -1,390 +0,0 @@-import { describe, expect, it } from "vitest";-import {- compileEvalPrompt,- buildEvalScoreSchema,- buildExecutionMetadata,- buildEvalMessages,- buildScoreEvent,- getEnvironmentFromVariables,- validateLLMResponse,- evalTemplateOutputSchema,-} from "./evalExecutionUtils";-import { type ExtractedVariable } from "./evalService";-import { ChatMessageRole } from "@langfuse/shared";-import { ChatMessageType } from "@langfuse/shared/src/server";--describe("evalExecutionUtils", () => {- describe("compileEvalPrompt", () => {- it("should compile template with variables", () => {- const params = {- templatePrompt: "Evaluate {{input}} and compare to {{output}}",- variables: [- { var: "input", value: "user question" },- { var: "output", value: "model response" },- ] as ExtractedVariable[],- };-- const result = compileEvalPrompt(params);- expect(result).toBe(- "Evaluate user question and compare to model response",- );- });-- it("should handle empty variables array", () => {- const params = {- templatePrompt: "Plain text without variables",- variables: [] as ExtractedVariable[],- };-- const result = compileEvalPrompt(params);- expect(result).toBe("Plain text without variables");- });-- it("should handle variables with special characters", () => {- const params = {- templatePrompt: "Input: {{input}}",- variables: [- { var: "input", value: "text with \"quotes\" and 'apostrophes'" },- ] as ExtractedVariable[],- };-- const result = compileEvalPrompt(params);- expect(result).toBe("Input: text with \"quotes\" and 'apostrophes'");- });-- it("should handle JSON values in variables", () => {- const params = {- templatePrompt: "Data: {{data}}",- variables: [- { var: "data", value: '{"key": "value", "count": 42}' },- ] as ExtractedVariable[],- };-- const result = compileEvalPrompt(params);- expect(result).toBe('Data: {"key": "value", "count": 42}');- });- });-- describe("buildEvalScoreSchema", () => {- it("should build schema with descriptions", () => {- const outputSchema = {- score: "A number between 0 and 1 indicating accuracy",- reasoning: "Explanation of the score",- };-- const schema = buildEvalScoreSchema(outputSchema);-- // Validate schema shape- expect(schema.shape.score).toBeDefined();- expect(schema.shape.reasoning).toBeDefined();- });-- it("should validate correct response", () => {- const outputSchema = {- score: "Score between 0 and 1",- reasoning: "The reasoning",- };-- const schema = buildEvalScoreSchema(outputSchema);- const result = schema.safeParse({- score: 0.75,- reasoning: "Good accuracy overall",- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.score).toBe(0.75);- expect(result.data.reasoning).toBe("Good accuracy overall");- }- });-- it("should reject invalid response - missing score", () => {- const outputSchema = {- score: "Score between 0 and 1",- reasoning: "The reasoning",- };-- const schema = buildEvalScoreSchema(outputSchema);- const result = schema.safeParse({- reasoning: "Missing score",- });-- expect(result.success).toBe(false);- });-- it("should reject invalid response - string score", () => {- const outputSchema = {- score: "Score between 0 and 1",- reasoning: "The reasoning",- };-- const schema = buildEvalScoreSchema(outputSchema);- const result = schema.safeParse({- score: "0.75",- reasoning: "Score is string",- });-- expect(result.success).toBe(false);- });- });-- describe("buildExecutionMetadata", () => {- it("should include all provided fields", () => {- const params = {- jobExecutionId: "exec-123",- jobConfigurationId: "config-456",- targetTraceId: "trace-789",- targetObservationId: "obs-abc",- targetDatasetItemId: "dataset-def",- };-- const result = buildExecutionMetadata(params);-- expect(result).toEqual({- job_execution_id: "exec-123",- job_configuration_id: "config-456",- target_trace_id: "trace-789",- target_observation_id: "obs-abc",- target_dataset_item_id: "dataset-def",- });- });-- it("should exclude null/undefined fields", () => {- const params = {- jobExecutionId: "exec-123",- jobConfigurationId: "config-456",- targetTraceId: null,- targetObservationId: undefined,- targetDatasetItemId: null,- };-- const result = buildExecutionMetadata(params);-- expect(result).toEqual({- job_execution_id: "exec-123",- job_configuration_id: "config-456",- });- expect(Object.keys(result)).not.toContain("target_trace_id");- expect(Object.keys(result)).not.toContain("target_observation_id");- expect(Object.keys(result)).not.toContain("target_dataset_item_id");- });- });-- describe("buildEvalMessages", () => {- it("should build user message array", () => {- const prompt = "Evaluate this response";-- const result = buildEvalMessages(prompt);-- expect(result).toHaveLength(1);- expect(result[0]).toEqual({- type: ChatMessageType.User,- role: ChatMessageRole.User,- content: "Evaluate this response",- });- });-- it("should handle multiline prompts", () => {- const prompt = "First line\nSecond line\nThird line";-- const result = buildEvalMessages(prompt);-- expect(result[0].content).toBe("First line\nSecond line\nThird line");- });- });-- describe("buildScoreEvent", () => {- it("should build complete score event", () => {- const params = {- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: null,- scoreName: "accuracy",- value: 0.85,- reasoning: "High accuracy observed",- environment: "production",- executionTraceId: "exec-trace-abc",- metadata: { job_execution_id: "exec-123" },- };-- const result = buildScoreEvent(params);-- expect(result.id).toBe("event-123");- expect(result.type).toBe("score-create");- expect(result.body.id).toBe("score-456");- expect(result.body.traceId).toBe("trace-789");- expect(result.body.observationId).toBeNull();- expect(result.body.name).toBe("accuracy");- expect(result.body.value).toBe(0.85);- expect(result.body.comment).toBe("High accuracy observed");- expect(result.body.source).toBe("EVAL");- expect(result.body.environment).toBe("production");- expect(result.body.executionTraceId).toBe("exec-trace-abc");- expect(result.body.metadata).toEqual({ job_execution_id: "exec-123" });- expect(result.body.dataType).toBe("NUMERIC");- });-- it("should include observation ID when provided", () => {- const params = {- eventId: "event-123",- scoreId: "score-456",- traceId: "trace-789",- observationId: "obs-abc",- scoreName: "relevance",- value: 0.9,- reasoning: "Highly relevant",- environment: "default",- executionTraceId: "exec-trace-def",- metadata: {},- };-- const result = buildScoreEvent(params);-- expect(result.body.observationId).toBe("obs-abc");- });- });-- describe("getEnvironmentFromVariables", () => {- it("should return environment from variable that has it", () => {- const variables: ExtractedVariable[] = [- { var: "input", value: "test" },- { var: "output", value: "result", environment: "production" },- { var: "context", value: "extra" },- ];-- const result = getEnvironmentFromVariables(variables);-- expect(result).toBe("production");- });-- it("should return first environment when multiple exist", () => {- const variables: ExtractedVariable[] = [- { var: "input", value: "test", environment: "staging" },- { var: "output", value: "result", environment: "production" },- ];-- const result = getEnvironmentFromVariables(variables);-- expect(result).toBe("staging");- });-- it("should return undefined when no environment exists", () => {- const variables: ExtractedVariable[] = [- { var: "input", value: "test" },- { var: "output", value: "result" },- ];-- const result = getEnvironmentFromVariables(variables);-- expect(result).toBeUndefined();- });-- it("should return undefined for empty array", () => {- const result = getEnvironmentFromVariables([]);-- expect(result).toBeUndefined();- });- });-- describe("validateLLMResponse", () => {- it("should validate correct response", () => {- const schema = buildEvalScoreSchema({- score: "Score 0-1",- reasoning: "Why",- });-- const result = validateLLMResponse({- response: { score: 0.8, reasoning: "Good" },- schema,- });-- expect(result.success).toBe(true);- if (result.success) {- expect(result.data.score).toBe(0.8);- expect(result.data.reasoning).toBe("Good");- }- });-- it("should return error for invalid response", () => {- const schema = buildEvalScoreSchema({- score: "Score 0-1",- reasoning: "Why",- });-- const result = validateLLMResponse({- response: { score: "invalid", reasoning: "Test" },- schema,- });-- expect(result.success).toBe(false);- if (!result.success) {- expect(result.error).toBeDefined();- }- });-- it("should return error for null response", () => {- const schema = buildEvalScoreSchema({- score: "Score 0-1",- reasoning: "Why",- });-- const result = validateLLMResponse({- response: null,- schema,- });-- expect(result.success).toBe(false);- });-- it("should return error for missing fields", () => {- const schema = buildEvalScoreSchema({- score: "Score 0-1",- reasoning: "Why",- });-- const result = validateLLMResponse({- response: { score: 0.5 },- schema,- });-- expect(result.success).toBe(false);- });- });-- describe("evalTemplateOutputSchema", () => {- it("should validate correct output schema", () => {- const result = evalTemplateOutputSchema.safeParse({- score: "A number between 0 and 1",- reasoning: "Explanation of the score",- });-- expect(result.success).toBe(true);- });-- it("should reject schema missing score", () => {- const result = evalTemplateOutputSchema.safeParse({- reasoning: "Only reasoning",- });-- expect(result.success).toBe(false);- });-- it("should reject schema missing reasoning", () => {- const result = evalTemplateOutputSchema.safeParse({- score: "Only score",- });-- expect(result.success).toBe(false);- });-- it("should reject non-string score", () => {- const result = evalTemplateOutputSchema.safeParse({- score: 0.5,- reasoning: "Explanation",- });-- expect(result.success).toBe(false);- });- });-});diff --git a/worker/src/features/evaluation/evalExecutionUtils.ts b/worker/src/features/evaluation/evalExecutionUtils.tsdeleted file mode 100644index a770e5b950..0000000000--- a/worker/src/features/evaluation/evalExecutionUtils.ts+++ /dev/null@@ -1,180 +0,0 @@-import { z } from "zod/v4";-import { z as zodV3 } from "zod/v3";-import { ScoreSourceEnum, ChatMessageRole } from "@langfuse/shared";-import {- ChatMessageType,- eventTypes,- ScoreEventType,-} from "@langfuse/shared/src/server";-import { compileTemplateString } from "../utils";-import { ExtractedVariable } from "./observationEval/extractObservationVariables";--/**- * Output schema for eval templates - defines the expected LLM response structure.- */-export const evalTemplateOutputSchema = z.object({- score: z.string(),- reasoning: z.string(),-});--export type EvalTemplateOutputSchema = z.infer<typeof evalTemplateOutputSchema>;--/**- * Parameters for compiling an eval prompt.- */-export interface CompileEvalPromptParams {- templatePrompt: string;- variables: ExtractedVariable[];-}--/**- * Compiles an eval prompt template by substituting variables.- *- * @param params - The template prompt and variables to substitute- * @returns The compiled prompt string- */-export function compileEvalPrompt(params: CompileEvalPromptParams): string {- const variableMap = Object.fromEntries(- params.variables.map(({ var: key, value }) => [key, value]),- );-- return compileTemplateString(params.templatePrompt, variableMap);-}--/**- * Builds a Zod v3 schema for validating LLM structured output.- * Uses Zod v3 because the LLM completion service requires it.- *- * @param outputSchema - The parsed output schema from the eval template- * @returns A Zod v3 schema for validating LLM responses- */-export function buildEvalScoreSchema(outputSchema: EvalTemplateOutputSchema) {- return zodV3.object({- reasoning: zodV3.string().describe(outputSchema.reasoning),- score: zodV3.number().describe(outputSchema.score),- });-}--/**- * Builds execution metadata for tracking and debugging.- *- * @param params - Job execution identifiers- * @returns Record of non-null metadata entries- */-export function buildExecutionMetadata(params: {- jobExecutionId: string;- jobConfigurationId: string;- targetTraceId?: string | null;- targetObservationId?: string | null;- targetDatasetItemId?: string | null;-}): Record<string, string> {- return Object.fromEntries(- Object.entries({- job_execution_id: params.jobExecutionId,- job_configuration_id: params.jobConfigurationId,- target_trace_id: params.targetTraceId,- target_observation_id: params.targetObservationId,- target_dataset_item_id: params.targetDatasetItemId,- }).filter(([, v]) => v != null),- ) as Record<string, string>;-}--/**- * Builds the LLM chat messages for eval execution.- *- * @param prompt - The compiled prompt string- * @returns Array of chat messages for the LLM call- */-export function buildEvalMessages(prompt: string) {- return [- {- type: ChatMessageType.User,- role: ChatMessageRole.User,- content: prompt,- } as const,- ];-}--/**- * Parameters for building a score event.- */-export interface BuildScoreEventParams {- eventId: string;- scoreId: string;- traceId: string | null;- observationId: string | null;- scoreName: string;- value: number;- reasoning: string;- environment: string;- executionTraceId: string;- metadata: Record<string, string>;-}--/**- * Builds a score event for S3 upload and ingestion queue.- *- * @param params - Score event parameters- * @returns A score event ready for persistence- */-export function buildScoreEvent(params: BuildScoreEventParams): ScoreEventType {- return {- id: params.eventId,- timestamp: new Date().toISOString(),- type: eventTypes.SCORE_CREATE,- body: {- id: params.scoreId,- traceId: params.traceId,- observationId: params.observationId,- name: params.scoreName,- value: params.value,- comment: params.reasoning,- source: ScoreSourceEnum.EVAL,- environment: params.environment,- executionTraceId: params.executionTraceId,- metadata: params.metadata,- dataType: "NUMERIC",- },- };-}--/**- * Extracts the environment from extracted variables.- * The environment is included on the first variable that has it set.- *- * @param variables - Array of extracted variables- * @returns The environment string or undefined- */-export function getEnvironmentFromVariables(- variables: ExtractedVariable[],-): string | undefined {- return variables.find((v) => v.environment)?.environment;-}--/**- * Parameters for validating LLM response.- */-export interface ValidateLLMResponseParams {- response: unknown;- schema: ReturnType<typeof buildEvalScoreSchema>;-}--/**- * Validates and parses the LLM response against the score schema.- *- * @param params - The raw LLM response and schema to validate against- * @returns Parsed response with score and reasoning, or error- */-export function validateLLMResponse(- params: ValidateLLMResponseParams,-):- | { success: true; data: { score: number; reasoning: string } }- | { success: false; error: string } {- const result = params.schema.safeParse(params.response);-- if (result.success) {- return { success: true, data: result.data };- }-- return { success: false, error: result.error.message };-}diff --git a/worker/src/features/evaluation/evalRuntime.ts b/worker/src/features/evaluation/evalRuntime.tsnew file mode 100644index 0000000000..24f61f902e--- /dev/null+++ b/worker/src/features/evaluation/evalRuntime.ts@@ -0,0 +1,50 @@+import { ChatMessageRole, ChatMessageType } from "@langfuse/shared";+import { compileTemplateString } from "../utils";+import { ExtractedVariable } from "./observationEval/extractObservationVariables";++export interface CompileEvalPromptParams {+ templatePrompt: string;+ variables: ExtractedVariable[];+}++export function compileEvalPrompt(params: CompileEvalPromptParams): string {+ const variableMap = Object.fromEntries(+ params.variables.map(({ var: key, value }) => [key, value]),+ );++ return compileTemplateString(params.templatePrompt, variableMap);+}++export function buildEvalExecutionMetadata(params: {+ jobExecutionId: string;+ jobConfigurationId: string;+ targetTraceId?: string | null;+ targetObservationId?: string | null;+ targetDatasetItemId?: string | null;+}): Record<string, string> {+ return Object.fromEntries(+ Object.entries({+ job_execution_id: params.jobExecutionId,+ job_configuration_id: params.jobConfigurationId,+ target_trace_id: params.targetTraceId,+ target_observation_id: params.targetObservationId,+ target_dataset_item_id: params.targetDatasetItemId,+ }).filter(([, value]) => value != null),+ ) as Record<string, string>;+}++export function buildEvalMessages(prompt: string) {+ return [+ {+ type: ChatMessageType.User,+ role: ChatMessageRole.User,+ content: prompt,+ } as const,+ ];+}++export function getEnvironmentFromVariables(+ variables: ExtractedVariable[],+): string | undefined {+ return variables.find((variable) => variable.environment)?.environment;+}diff --git a/worker/src/features/evaluation/evalScoreEvent.ts b/worker/src/features/evaluation/evalScoreEvent.tsnew file mode 100644index 0000000000..b569c191a1--- /dev/null+++ b/worker/src/features/evaluation/evalScoreEvent.ts@@ -0,0 +1,170 @@+import { randomUUID } from "crypto";+import {+ type EvalOutputResult,+ ScoreDataTypeEnum,+ ScoreSourceEnum,+} from "@langfuse/shared";+import { eventTypes, ScoreEventType } from "@langfuse/shared/src/server";++type BuildScoreEventBase = {+ eventId: string;+ scoreId: string;+ traceId: string | null;+ observationId: string | null;+ scoreName: string;+ reasoning: string;+ environment: string;+ executionTraceId: string;+ metadata: Record<string, string>;+};++export type BuildScoreEventParams = BuildScoreEventBase &+ (+ | {+ dataType: typeof ScoreDataTypeEnum.NUMERIC;+ scoreValue: number;+ }+ | {+ dataType: typeof ScoreDataTypeEnum.CATEGORICAL;+ scoreValue: string;+ }+ );++type BuildScoreWritePayloadParams =+ | Omit<+ Extract<+ BuildScoreEventParams,+ { dataType: typeof ScoreDataTypeEnum.NUMERIC }+ >,+ "eventId"+ >+ | Omit<+ Extract<+ BuildScoreEventParams,+ { dataType: typeof ScoreDataTypeEnum.CATEGORICAL }+ >,+ "eventId"+ >;++function createScoreEventEnvelope(params: {+ eventId: string;+ body: ScoreEventType["body"];+}): ScoreEventType {+ return {+ id: params.eventId,+ timestamp: new Date().toISOString(),+ type: eventTypes.SCORE_CREATE,+ body: params.body,+ };+}++export type EvalScoreWritePayload = {+ eventId: string;+ scoreId: string;+ event: ScoreEventType;+};++export function buildScoreEvent(params: BuildScoreEventParams): ScoreEventType {+ const bodyBase = {+ id: params.scoreId,+ traceId: params.traceId,+ observationId: params.observationId,+ name: params.scoreName,+ comment: params.reasoning,+ source: ScoreSourceEnum.EVAL,+ environment: params.environment,+ executionTraceId: params.executionTraceId,+ metadata: params.metadata,+ };++ if (params.dataType === ScoreDataTypeEnum.CATEGORICAL) {+ return createScoreEventEnvelope({+ eventId: params.eventId,+ body: {+ ...bodyBase,+ value: params.scoreValue,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ },+ });+ }++ return createScoreEventEnvelope({+ eventId: params.eventId,+ body: {+ ...bodyBase,+ value: params.scoreValue,+ dataType: ScoreDataTypeEnum.NUMERIC,+ },+ });+}++function buildScoreWritePayload(+ params: BuildScoreWritePayloadParams,+): EvalScoreWritePayload {+ const eventId = randomUUID();++ if (params.dataType === ScoreDataTypeEnum.CATEGORICAL) {+ return {+ eventId,+ scoreId: params.scoreId,+ event: buildScoreEvent({+ ...params,+ eventId,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ scoreValue: params.scoreValue,+ }),+ };+ }++ return {+ eventId,+ scoreId: params.scoreId,+ event: buildScoreEvent({+ ...params,+ eventId,+ dataType: ScoreDataTypeEnum.NUMERIC,+ scoreValue: params.scoreValue,+ }),+ };+}++export function buildEvalScoreWritePayloads(params: {+ outputResult: EvalOutputResult;+ primaryScoreId: string;+ traceId: string | null;+ observationId: string | null;+ scoreName: string;+ environment: string;+ executionTraceId: string;+ metadata: Record<string, string>;+}): EvalScoreWritePayload[] {+ const commonParams = {+ traceId: params.traceId,+ observationId: params.observationId,+ scoreName: params.scoreName,+ reasoning: params.outputResult.reasoning,+ environment: params.environment,+ executionTraceId: params.executionTraceId,+ metadata: params.metadata,+ };++ if (params.outputResult.dataType === ScoreDataTypeEnum.NUMERIC) {+ return [+ buildScoreWritePayload({+ ...commonParams,+ scoreId: params.primaryScoreId,+ scoreValue: params.outputResult.score,+ dataType: ScoreDataTypeEnum.NUMERIC,+ }),+ ];+ }++ return params.outputResult.matches.map((scoreValue, index) =>+ buildScoreWritePayload({+ ...commonParams,+ scoreId: index === 0 ? params.primaryScoreId : randomUUID(),+ scoreValue,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ }),+ );+}diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex 5ba2316298..885e894376 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -42,6 +42,7 @@ import {} from "./traceFilterUtils";import {Prisma,+ compilePersistedEvalOutputDefinition,singleFilter,variableMappingList,evalDatasetFormFilterCols,@@ -57,6 +58,9 @@ import {getEvaluatorBlockMetadata,getBlockReasonForInvalidModelConfig,isJobConfigExecutable,+ PersistedEvalOutputDefinitionSchema,+ ScoreDataTypeEnum,+ validateEvalOutputResult,} from "@langfuse/shared";import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";import { createW3CTraceId } from "../utils";@@ -65,14 +69,11 @@ import { UnrecoverableError } from "../../errors/UnrecoverableError";import { ObservationNotFoundError } from "../../errors/ObservationNotFoundError";import {compileEvalPrompt,- buildEvalScoreSchema,- buildExecutionMetadata,buildEvalMessages,- buildScoreEvent,+ buildEvalExecutionMetadata,getEnvironmentFromVariables,- evalTemplateOutputSchema,- validateLLMResponse,-} from "./evalExecutionUtils";+} from "./evalRuntime";+import { buildEvalScoreWritePayloads } from "./evalScoreEvent";import {type EvalExecutionDeps,createProductionEvalExecutionDeps,@@ -781,18 +782,29 @@ export async function executeLLMAsJudgeEvaluation({`Compiled prompt for job ${jobExecutionId}: ${prompt.slice(0, 200)}...`,);- // Parse and validate output schema- const parsedOutputSchema = evalTemplateOutputSchema.safeParse(- template.outputSchema,- );+ // Parse and validate output definition+ const parsedOutputDefinition =+ PersistedEvalOutputDefinitionSchema.safeParse(+ template.outputDefinition,+ );- if (!parsedOutputSchema.success) {+ if (!parsedOutputDefinition.success) {throw new UnrecoverableError(- "Output schema not found or invalid in evaluation template",+ "Output definition not found or invalid in evaluation template",);}- const evalScoreSchema = buildEvalScoreSchema(parsedOutputSchema.data);+ const compiledOutputDefinition = compilePersistedEvalOutputDefinition(+ parsedOutputDefinition.data,+ );++ span.setAttribute("eval.job_configuration.id", config.id);+ span.setAttribute("eval.template.version", template.version);+ span.setAttribute("eval.score.name", config.scoreName);+ span.setAttribute(+ "eval.score.data_type",+ compiledOutputDefinition.resolvedOutputDefinition.dataType,+ );// Get model configurationconst modelConfig = await deps.fetchModelConfig({@@ -831,11 +843,11 @@ export async function executeLLMAsJudgeEvaluation({// Prepare LLM callconst messages = buildEvalMessages(prompt);- const scoreId = randomUUID();- span.setAttribute("eval.score.id", scoreId);+ const primaryScoreId = randomUUID();+ span.setAttribute("eval.score.id", primaryScoreId);const executionTraceId = createW3CTraceId(jobExecutionId);- const executionMetadata = buildExecutionMetadata({+ const executionMetadata = buildEvalExecutionMetadata({jobExecutionId,jobConfigurationId: job.jobConfigurationId,targetTraceId: job.jobInputTraceId,@@ -847,6 +859,14 @@ export async function executeLLMAsJudgeEvaluation({const llmOutput = await instrumentAsync({ name: "eval.call-llm" },async (llmSpan) => {+ llmSpan.setAttribute("eval.job_configuration.id", config.id);+ llmSpan.setAttribute("eval.template.id", template.id);+ llmSpan.setAttribute("eval.template.version", template.version);+ llmSpan.setAttribute("eval.score.name", config.scoreName);+ llmSpan.setAttribute(+ "eval.score.data_type",+ compiledOutputDefinition.resolvedOutputDefinition.dataType,+ );llmSpan.setAttribute("eval.model.provider",modelConfig.config.provider,@@ -861,7 +881,8 @@ export async function executeLLMAsJudgeEvaluation({return await deps.callLLM({messages,modelConfig: modelConfig.config,- structuredOutputSchema: evalScoreSchema,+ structuredOutputSchema:+ compiledOutputDefinition.outputResultSchema,traceSinkParams: {targetProjectId: projectId,traceId: executionTraceId,@@ -869,7 +890,7 @@ export async function executeLLMAsJudgeEvaluation({environment: LangfuseInternalTraceEnvironment.LLMJudge,metadata: {...executionMetadata,- score_id: scoreId,+ score_id: primaryScoreId,},},});@@ -899,9 +920,9 @@ export async function executeLLMAsJudgeEvaluation({},);- const parsedLLMOutput = validateLLMResponse({+ const parsedLLMOutput = validateEvalOutputResult({response: llmOutput,- schema: evalScoreSchema,+ compiledOutputDefinition,});if (!parsedLLMOutput.success) {@@ -911,45 +932,55 @@ export async function executeLLMAsJudgeEvaluation({}logger.debug(- `Job ${jobExecutionId} received LLM output: score=${parsedLLMOutput.data.score}`,+ `Job ${jobExecutionId} received LLM output: ${+ parsedLLMOutput.data.dataType === ScoreDataTypeEnum.NUMERIC+ ? `score=${parsedLLMOutput.data.score}`+ : `matches=${parsedLLMOutput.data.matches.join(",")}`+ }`,);- // Build and persist score- const eventId = randomUUID();- const scoreEvent = buildScoreEvent({- eventId,- scoreId,+ const scoreWritePayloads = buildEvalScoreWritePayloads({+ outputResult: parsedLLMOutput.data,+ primaryScoreId,traceId: job.jobInputTraceId,observationId: job.jobInputObservationId,scoreName: config.scoreName,- value: parsedLLMOutput.data.score,- reasoning: parsedLLMOutput.data.reasoning,environment,executionTraceId,metadata: executionMetadata,});+ span.setAttribute("eval.score.count", scoreWritePayloads.length);+// Write score to S3 and enqueue for ingestiontry {- await deps.uploadScore({- projectId,- scoreId,- eventId,- event: scoreEvent,- });+ await Promise.all(+ scoreWritePayloads.map(async ({ scoreId, eventId, event }) => {+ await deps.uploadScore({+ projectId,+ scoreId,+ eventId,+ event,+ });- await deps.enqueueScoreIngestion({- projectId,- scoreId,- eventId,- });+ await deps.enqueueScoreIngestion({+ projectId,+ scoreId,+ eventId,+ });+ }),+ );} catch (e) {logger.error(`Failed to persist score: ${e}`, e);traceException(e);- throw new Error(`Failed to write score ${scoreId} into IngestionQueue`);+ throw new Error(+ `Failed to write score ${primaryScoreId} into IngestionQueue`,+ );}- logger.debug(`Persisted score ${scoreId} for job ${jobExecutionId}`);+ logger.debug(+ `Persisted ${scoreWritePayloads.length} score(s) for job ${jobExecutionId}`,+ );// Update job execution statusawait deps.updateJobExecution({@@ -958,13 +989,17 @@ export async function executeLLMAsJudgeEvaluation({data: {status: JobExecutionStatus.COMPLETED,endTime: new Date(),- jobOutputScoreId: scoreId,+ jobOutputScoreId: primaryScoreId,executionTraceId,},});logger.debug(- `Eval job ${job.id} completed with score ${parsedLLMOutput.data.score}`,+ `Eval job ${job.id} completed with ${+ parsedLLMOutput.data.dataType === ScoreDataTypeEnum.NUMERIC+ ? `score ${parsedLLMOutput.data.score}`+ : `matches ${parsedLLMOutput.data.matches.join(",")}`+ }`,);},);diff --git a/worker/src/features/evaluation/evaluationHelpers.test.ts b/worker/src/features/evaluation/evaluationHelpers.test.tsnew file mode 100644index 0000000000..1330b52607--- /dev/null+++ b/worker/src/features/evaluation/evaluationHelpers.test.ts@@ -0,0 +1,788 @@+import { describe, expect, it } from "vitest";+import {+ compilePersistedEvalOutputDefinition,+ buildEvalOutputResultSchema,+ ChatMessageRole,+ ChatMessageType,+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ PersistedEvalOutputDefinitionSchema,+ ScoreDataTypeEnum,+ validateEvalOutputResult,+} from "@langfuse/shared";+import { type ExtractedVariable } from "./observationEval/extractObservationVariables";+import {+ buildEvalExecutionMetadata,+ buildEvalMessages,+ compileEvalPrompt,+ getEnvironmentFromVariables,+} from "./evalRuntime";+import { buildEvalScoreWritePayloads, buildScoreEvent } from "./evalScoreEvent";++describe("evaluation helpers", () => {+ describe("compileEvalPrompt", () => {+ it("should compile template with variables", () => {+ const params = {+ templatePrompt: "Evaluate {{input}} and compare to {{output}}",+ variables: [+ { var: "input", value: "user question" },+ { var: "output", value: "model response" },+ ] as ExtractedVariable[],+ };++ const result = compileEvalPrompt(params);+ expect(result).toBe(+ "Evaluate user question and compare to model response",+ );+ });++ it("should handle empty variables array", () => {+ const params = {+ templatePrompt: "Plain text without variables",+ variables: [] as ExtractedVariable[],+ };++ const result = compileEvalPrompt(params);+ expect(result).toBe("Plain text without variables");+ });++ it("should handle variables with special characters", () => {+ const params = {+ templatePrompt: "Input: {{input}}",+ variables: [+ { var: "input", value: "text with \"quotes\" and 'apostrophes'" },+ ] as ExtractedVariable[],+ };++ const result = compileEvalPrompt(params);+ expect(result).toBe("Input: text with \"quotes\" and 'apostrophes'");+ });++ it("should handle JSON values in variables", () => {+ const params = {+ templatePrompt: "Data: {{data}}",+ variables: [+ { var: "data", value: '{"key": "value", "count": 42}' },+ ] as ExtractedVariable[],+ };++ const result = compileEvalPrompt(params);+ expect(result).toBe('Data: {"key": "value", "count": 42}');+ });+ });++ describe("buildEvalOutputResultSchema", () => {+ it("should build numeric response schema with descriptions", () => {+ const schema = buildEvalOutputResultSchema(+ createNumericEvalOutputDefinition({+ scoreDescription: "A number between 0 and 1 indicating accuracy",+ reasoningDescription: "Explanation of the score",+ }),+ );++ expect(schema.shape.score).toBeDefined();+ expect(schema.shape.reasoning).toBeDefined();+ });++ it("should validate correct response", () => {+ const schema = buildEvalOutputResultSchema(+ createNumericEvalOutputDefinition({+ scoreDescription: "Score between 0 and 1",+ reasoningDescription: "The reasoning",+ }),+ );+ const result = schema.safeParse({+ score: 0.75,+ reasoning: "Good accuracy overall",+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.score).toBe(0.75);+ expect(result.data.reasoning).toBe("Good accuracy overall");+ }+ });++ it("should reject invalid response - missing score", () => {+ const schema = buildEvalOutputResultSchema(+ createNumericEvalOutputDefinition({+ scoreDescription: "Score between 0 and 1",+ reasoningDescription: "The reasoning",+ }),+ );+ const result = schema.safeParse({+ reasoning: "Missing score",+ });++ expect(result.success).toBe(false);+ });++ it("should reject invalid response - string score", () => {+ const schema = buildEvalOutputResultSchema(+ createNumericEvalOutputDefinition({+ scoreDescription: "Score between 0 and 1",+ reasoningDescription: "The reasoning",+ }),+ );+ const result = schema.safeParse({+ score: "0.75",+ reasoning: "Score is string",+ });++ expect(result.success).toBe(false);+ });++ it("should validate categorical responses against allowed values", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Explain the selected category",+ categories: ["correct", "partial"],+ }),+ );++ expect(+ schema.safeParse({+ score: "correct",+ reasoning: "The answer is fully supported.",+ }).success,+ ).toBe(true);++ expect(+ schema.safeParse({+ score: "incorrect",+ reasoning: "The answer is unsupported.",+ }).success,+ ).toBe(false);+ });++ it("should reject categorical arrays when only a single match is allowed", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Explain the selected category",+ categories: ["correct", "partial"],+ }),+ );++ expect(+ schema.safeParse({+ score: ["correct", "partial"],+ reasoning: "This should fail because only one category is allowed.",+ }).success,+ ).toBe(false);+ });++ it("should validate categorical multi-match responses against allowed values", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ );++ expect(+ schema.safeParse({+ score: ["correct", "partial"],+ reasoning: "The answer is partly right and partly complete.",+ }).success,+ ).toBe(true);++ expect(+ schema.safeParse({+ score: ["correct", "correct"],+ reasoning: "Duplicate categories should be rejected.",+ }).success,+ ).toBe(false);+ });++ it("should reject duplicate categorical multi-match values", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ );++ expect(+ schema.safeParse({+ score: ["correct", "correct"],+ reasoning: "This should be invalid.",+ }).success,+ ).toBe(false);+ });++ it("should reject categorical scalars when multiple matches are required to be returned as an array", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ );++ expect(+ schema.safeParse({+ score: "correct",+ reasoning: "This should fail because multi-match uses an array.",+ }).success,+ ).toBe(false);+ });++ it("should reject empty categorical multi-match arrays", () => {+ const schema = buildEvalOutputResultSchema(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ );++ expect(+ schema.safeParse({+ score: [],+ reasoning: "At least one category is required.",+ }).success,+ ).toBe(false);+ });+ });++ describe("buildEvalExecutionMetadata", () => {+ it("should include all provided fields", () => {+ const params = {+ jobExecutionId: "exec-123",+ jobConfigurationId: "config-456",+ targetTraceId: "trace-789",+ targetObservationId: "obs-abc",+ targetDatasetItemId: "dataset-def",+ };++ const result = buildEvalExecutionMetadata(params);++ expect(result).toEqual({+ job_execution_id: "exec-123",+ job_configuration_id: "config-456",+ target_trace_id: "trace-789",+ target_observation_id: "obs-abc",+ target_dataset_item_id: "dataset-def",+ });+ });++ it("should exclude null/undefined fields", () => {+ const params = {+ jobExecutionId: "exec-123",+ jobConfigurationId: "config-456",+ targetTraceId: null,+ targetObservationId: undefined,+ targetDatasetItemId: null,+ };++ const result = buildEvalExecutionMetadata(params);++ expect(result).toEqual({+ job_execution_id: "exec-123",+ job_configuration_id: "config-456",+ });+ expect(Object.keys(result)).not.toContain("target_trace_id");+ expect(Object.keys(result)).not.toContain("target_observation_id");+ expect(Object.keys(result)).not.toContain("target_dataset_item_id");+ });+ });++ describe("buildEvalMessages", () => {+ it("should build user message array", () => {+ const prompt = "Evaluate this response";++ const result = buildEvalMessages(prompt);++ expect(result).toHaveLength(1);+ expect(result[0]).toEqual({+ type: ChatMessageType.User,+ role: ChatMessageRole.User,+ content: "Evaluate this response",+ });+ });++ it("should handle multiline prompts", () => {+ const prompt = "First line\nSecond line\nThird line";++ const result = buildEvalMessages(prompt);++ expect(result[0].content).toBe("First line\nSecond line\nThird line");+ });+ });++ describe("buildScoreEvent", () => {+ it("should build complete score event", () => {+ const params = {+ eventId: "event-123",+ scoreId: "score-456",+ traceId: "trace-789",+ observationId: null,+ scoreName: "accuracy",+ scoreValue: 0.85,+ reasoning: "High accuracy observed",+ environment: "production",+ executionTraceId: "exec-trace-abc",+ metadata: { job_execution_id: "exec-123" },+ dataType: ScoreDataTypeEnum.NUMERIC,+ };++ const result = buildScoreEvent(params);++ expect(result.id).toBe("event-123");+ expect(result.type).toBe("score-create");+ expect(result.body.id).toBe("score-456");+ expect(result.body.traceId).toBe("trace-789");+ expect(result.body.observationId).toBeNull();+ expect(result.body.name).toBe("accuracy");+ expect(result.body.value).toBe(0.85);+ expect(result.body.comment).toBe("High accuracy observed");+ expect(result.body.source).toBe("EVAL");+ expect(result.body.environment).toBe("production");+ expect(result.body.executionTraceId).toBe("exec-trace-abc");+ expect(result.body.metadata).toEqual({ job_execution_id: "exec-123" });+ expect(result.body.dataType).toBe("NUMERIC");+ });++ it("should include observation ID when provided", () => {+ const params = {+ eventId: "event-123",+ scoreId: "score-456",+ traceId: "trace-789",+ observationId: "obs-abc",+ scoreName: "relevance",+ scoreValue: 0.9,+ reasoning: "Highly relevant",+ environment: "default",+ executionTraceId: "exec-trace-def",+ metadata: {},+ dataType: ScoreDataTypeEnum.NUMERIC,+ };++ const result = buildScoreEvent(params);++ expect(result.body.observationId).toBe("obs-abc");+ });++ it("should build categorical score events", () => {+ const result = buildScoreEvent({+ eventId: "event-123",+ scoreId: "score-456",+ traceId: "trace-789",+ observationId: null,+ scoreName: "factuality",+ scoreValue: "correct",+ reasoning: "The answer is fully supported.",+ environment: "production",+ executionTraceId: "exec-trace-abc",+ metadata: { job_execution_id: "exec-123" },+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ });++ expect(result.body.value).toBe("correct");+ expect(result.body.dataType).toBe("CATEGORICAL");+ });+ });++ describe("buildEvalScoreWritePayloads", () => {+ it("should build a single numeric score payload", () => {+ const result = buildEvalScoreWritePayloads({+ outputResult: {+ dataType: ScoreDataTypeEnum.NUMERIC,+ score: 0.85,+ reasoning: "High accuracy observed",+ },+ primaryScoreId: "score-123",+ traceId: "trace-456",+ observationId: null,+ scoreName: "accuracy",+ environment: "production",+ executionTraceId: "exec-trace-789",+ metadata: { job_execution_id: "job-1" },+ });++ expect(result).toHaveLength(1);+ expect(result[0]).toEqual({+ eventId: expect.any(String),+ scoreId: "score-123",+ event: expect.objectContaining({+ body: expect.objectContaining({+ value: 0.85,+ dataType: ScoreDataTypeEnum.NUMERIC,+ }),+ }),+ });+ });++ it("should build one categorical payload per match while preserving shared metadata", () => {+ const result = buildEvalScoreWritePayloads({+ outputResult: {+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ matches: ["correct", "partial"],+ reasoning: "Both categories apply",+ },+ primaryScoreId: "score-123",+ traceId: "trace-456",+ observationId: "obs-789",+ scoreName: "accuracy",+ environment: "production",+ executionTraceId: "exec-trace-789",+ metadata: { job_execution_id: "job-1" },+ });++ expect(result).toHaveLength(2);+ expect(result[0].scoreId).toBe("score-123");+ expect(result[1].scoreId).not.toBe("score-123");+ expect(result[0].event.body.value).toBe("correct");+ expect(result[1].event.body.value).toBe("partial");+ expect(result[0].event.body.comment).toBe("Both categories apply");+ expect(result[1].event.body.comment).toBe("Both categories apply");+ expect(result[0].event.body.metadata).toEqual({+ job_execution_id: "job-1",+ });+ expect(result[1].event.body.metadata).toEqual({+ job_execution_id: "job-1",+ });+ });+ });++ describe("getEnvironmentFromVariables", () => {+ it("should return environment from variable that has it", () => {+ const variables: ExtractedVariable[] = [+ { var: "input", value: "test" },+ { var: "output", value: "result", environment: "production" },+ { var: "context", value: "extra" },+ ];++ const result = getEnvironmentFromVariables(variables);++ expect(result).toBe("production");+ });++ it("should return first environment when multiple exist", () => {+ const variables: ExtractedVariable[] = [+ { var: "input", value: "test", environment: "staging" },+ { var: "output", value: "result", environment: "production" },+ ];++ const result = getEnvironmentFromVariables(variables);++ expect(result).toBe("staging");+ });++ it("should return undefined when no environment exists", () => {+ const variables: ExtractedVariable[] = [+ { var: "input", value: "test" },+ { var: "output", value: "result" },+ ];++ const result = getEnvironmentFromVariables(variables);++ expect(result).toBeUndefined();+ });++ it("should return undefined for empty array", () => {+ const result = getEnvironmentFromVariables([]);++ expect(result).toBeUndefined();+ });+ });++ describe("validateEvalOutputResult", () => {+ it("should validate correct response", () => {+ const outputDefinition = createNumericEvalOutputDefinition({+ scoreDescription: "Score 0-1",+ reasoningDescription: "Why",+ });+ const result = validateEvalOutputResult({+ response: { score: 0.8, reasoning: "Good" },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data).toEqual({+ dataType: ScoreDataTypeEnum.NUMERIC,+ score: 0.8,+ reasoning: "Good",+ });+ }+ });++ it("should return error for invalid response", () => {+ const outputDefinition = createNumericEvalOutputDefinition({+ scoreDescription: "Score 0-1",+ reasoningDescription: "Why",+ });++ const result = validateEvalOutputResult({+ response: { score: "invalid", reasoning: "Test" },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(false);+ if (!result.success) {+ expect(result.error).toBeDefined();+ }+ });++ it("should return error for null response", () => {+ const outputDefinition = createNumericEvalOutputDefinition({+ scoreDescription: "Score 0-1",+ reasoningDescription: "Why",+ });++ const result = validateEvalOutputResult({+ response: null,+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(false);+ });++ it("should return error for missing fields", () => {+ const outputDefinition = createNumericEvalOutputDefinition({+ scoreDescription: "Score 0-1",+ reasoningDescription: "Why",+ });++ const result = validateEvalOutputResult({+ response: { score: 0.5 },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(false);+ });++ it("should normalize categorical responses to a matches array", () => {+ const outputDefinition = createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Why",+ categories: ["correct", "incorrect"],+ });++ const result = validateEvalOutputResult({+ response: { score: "correct", reasoning: "Supported by the context" },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data).toEqual({+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ matches: ["correct"],+ reasoning: "Supported by the context",+ });+ }+ });++ it("should validate categorical multi-match responses", () => {+ const outputDefinition = createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Why",+ categories: ["correct", "incorrect"],+ shouldAllowMultipleMatches: true,+ });++ const result = validateEvalOutputResult({+ response: {+ score: ["correct", "incorrect"],+ reasoning: "Both labels apply in this synthetic test.",+ },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data).toEqual({+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ matches: ["correct", "incorrect"],+ reasoning: "Both labels apply in this synthetic test.",+ });+ }+ });++ it("should reject categorical responses with categories outside the allowed set", () => {+ const outputDefinition = createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Why",+ categories: ["correct", "incorrect"],+ });++ const result = validateEvalOutputResult({+ response: { score: "partial", reasoning: "Not an allowed category" },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(false);+ });++ it("should reject categorical multi-match responses with duplicate categories", () => {+ const outputDefinition = createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Why",+ categories: ["correct", "incorrect"],+ shouldAllowMultipleMatches: true,+ });++ const result = validateEvalOutputResult({+ response: {+ score: ["correct", "correct"],+ reasoning: "Duplicates should be rejected.",+ },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(false);+ });+ });++ describe("PersistedEvalOutputDefinitionSchema", () => {+ it("should validate correct output definition", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ score: "A number between 0 and 1",+ reasoning: "Explanation of the score",+ });++ expect(result.success).toBe(true);+ });++ it("should default missing legacy score to an empty string", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ reasoning: "Only reasoning",+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.score).toBe("");+ }+ });++ it("should default missing legacy reasoning to an empty string", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ score: "Only score",+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.reasoning).toBe("");+ }+ });++ it("should reject non-string score", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ score: 0.5,+ reasoning: "Explanation",+ });++ expect(result.success).toBe(false);+ });++ it("should accept versioned categorical schemas", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose the best matching category",+ reasoningDescription: "Explain the selected category",+ categories: ["correct", "partial"],+ }),+ );++ expect(result.success).toBe(true);+ });++ it("should accept versioned categorical multi-match schemas", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse(+ createCategoricalEvalOutputDefinition({+ scoreDescription: "Choose all matching categories",+ reasoningDescription: "Explain the selected categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ }),+ );++ expect(result.success).toBe(true);+ });++ it("should default missing categorical multi-match flag to false", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "partial"],+ },+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.score.shouldAllowMultipleMatches).toBe(false);+ }+ });++ it("should reject categorical schemas with duplicate categories after trimming whitespace", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", " correct "],+ },+ });++ expect(result.success).toBe(false);+ });++ it("should reject categorical schemas with blank categories", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", " "],+ },+ });++ expect(result.success).toBe(false);+ });++ it("should reject categorical schemas with fewer than two categories", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse({+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct"],+ },+ });++ expect(result.success).toBe(false);+ });+ });+});diff --git a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.tsindex c61ae1404d..131e82660d 100644--- a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts+++ b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts@@ -1,10 +1,15 @@import { describe, expect, it, vi, type Mock } from "vitest";import { JobExecutionStatus } from "@prisma/client";+import z from "zod/v4";import { executeLLMAsJudgeEvaluation } from "./evalService";import { createMockEvalExecutionDeps } from "./evalExecutionDeps";import { UnrecoverableError } from "../../errors/UnrecoverableError";import { ExtractedVariable } from "./observationEval/extractObservationVariables";-import { EvalTargetObject } from "@langfuse/shared";+import {+ EvalTargetObject,+ type PersistedEvalOutputDefinition,+ ScoreDataTypeEnum,+} from "@langfuse/shared";/*** Unit tests for executeLLMAsJudgeEvaluation with mocked dependencies.@@ -62,7 +67,20 @@ describe("executeLLMAsJudgeEvaluation", () => {timeScope: ["NEW" as const],};- const mockEvalTemplate = {+ const mockEvalTemplate: {+ id: string;+ createdAt: Date;+ updatedAt: Date;+ name: string;+ version: number;+ prompt: string;+ model: string;+ provider: string;+ modelParams: Record<string, unknown>;+ outputDefinition: PersistedEvalOutputDefinition;+ vars: string[];+ projectId: string;+ } = {id: "template-xyz",createdAt: new Date(),updatedAt: new Date(),@@ -72,7 +90,7 @@ describe("executeLLMAsJudgeEvaluation", () => {model: "gpt-4",provider: "openai",modelParams: {},- outputSchema: {+ outputDefinition: {score: "A number between 0 and 1",reasoning: "Explain your reasoning",},@@ -108,8 +126,10 @@ describe("executeLLMAsJudgeEvaluation", () => {});/** Creates a mock for callLLM with a successful response */- const mockSuccessfulLLMCall = (score: number, reasoning: string) =>- vi.fn().mockResolvedValue({ score, reasoning });+ const mockSuccessfulLLMCall = (+ score: number | string | string[],+ reasoning: string,+ ) => vi.fn().mockResolvedValue({ score, reasoning });/** Creates standard deps with all mocks for a successful execution flow */const createSuccessfulDeps = (@@ -282,10 +302,10 @@ describe("executeLLMAsJudgeEvaluation", () => {).rejects.toThrow(UnrecoverableError);});- it("should throw UnrecoverableError if output schema invalid", async () => {+ it("should throw UnrecoverableError if output definition is invalid", async () => {const templateWithBadSchema = {...mockEvalTemplate,- outputSchema: { invalidKey: "value" },+ outputDefinition: { invalidKey: "value" },};await expect(@@ -446,16 +466,107 @@ describe("executeLLMAsJudgeEvaluation", () => {await executeLLMAsJudgeEvaluation(createExecutionParams({ deps }));- expect(callLLM).toHaveBeenCalledWith(- expect.objectContaining({- structuredOutputSchema: expect.objectContaining({- shape: expect.objectContaining({- reasoning: expect.any(Object),- score: expect.any(Object),- }),- }),+ const structuredOutputSchema = callLLM.mock.calls[0][0]+ .structuredOutputSchema as z.ZodTypeAny;++ expect(+ structuredOutputSchema.safeParse({+ score: 0.8,+ reasoning: "Good response",+ }).success,+ ).toBe(true);+ });++ it("should pass categorical structured output schema to LLM", async () => {+ const callLLM = mockSuccessfulLLMCall("correct", "Fully supported");+ const deps = createSuccessfulDeps({ callLLM });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "partial"],+ },+ },+ },}),);++ const structuredOutputSchema = callLLM.mock.calls[0][0]+ .structuredOutputSchema as z.ZodTypeAny;++ expect(+ structuredOutputSchema.safeParse({+ score: "correct",+ reasoning: "Fully supported",+ }).success,+ ).toBe(true);+ expect(+ structuredOutputSchema.safeParse({+ score: "incorrect",+ reasoning: "Not part of the allowed categories",+ }).success,+ ).toBe(false);+ });++ it("should pass categorical multi-match structured output schema to LLM", async () => {+ const callLLM = mockSuccessfulLLMCall(+ ["correct", "partial"],+ "Both categories apply.",+ );+ const deps = createSuccessfulDeps({ callLLM });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected categories",+ },+ score: {+ description: "Choose all matching categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ },+ },+ },+ }),+ );++ const structuredOutputSchema = callLLM.mock.calls[0][0]+ .structuredOutputSchema as z.ZodTypeAny;++ expect(+ structuredOutputSchema.safeParse({+ score: ["correct", "partial"],+ reasoning: "Both categories apply.",+ }).success,+ ).toBe(true);+ expect(+ structuredOutputSchema.safeParse({+ score: "correct",+ reasoning: "Single values should be rejected for multi-match.",+ }).success,+ ).toBe(false);+ expect(+ structuredOutputSchema.safeParse({+ score: ["correct", "correct"],+ reasoning: "Duplicates should be rejected.",+ }).success,+ ).toBe(false);});it("should pass model config to LLM", async () => {@@ -695,6 +806,241 @@ describe("executeLLMAsJudgeEvaluation", () => {}),);});++ it("should persist categorical eval scores", async () => {+ const uploadScore = vi.fn();+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ "correct",+ "The answer is fully supported by the context.",+ ),+ uploadScore,+ });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "partial"],+ },+ },+ },+ }),+ );++ expect(uploadScore).toHaveBeenCalledWith(+ expect.objectContaining({+ event: expect.objectContaining({+ body: expect.objectContaining({+ value: "correct",+ comment: "The answer is fully supported by the context.",+ dataType: "CATEGORICAL",+ }),+ }),+ }),+ );+ });++ it("should fail categorical evals when the model returns a category outside the allowed set", async () => {+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ "incorrect",+ "This category is not configured on the evaluator.",+ ),+ });++ await expect(+ executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "partial"],+ },+ },+ },+ }),+ ),+ ).rejects.toThrow(UnrecoverableError);+ });++ it("should fail categorical evals when the model returns multiple matches for a single-match evaluator", async () => {+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ ["correct", "partial"],+ "This should fail because only one match is allowed.",+ ),+ });++ await expect(+ executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected category",+ },+ score: {+ description: "Choose the best matching category",+ categories: ["correct", "partial"],+ },+ },+ },+ }),+ ),+ ).rejects.toThrow(UnrecoverableError);+ });++ it("should persist one score per categorical match", async () => {+ const uploadScore = vi.fn();+ const enqueueScoreIngestion = vi.fn();+ const updateJobExecution = vi.fn();+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ ["correct", "partial"],+ "Both categories apply to the answer.",+ ),+ uploadScore,+ enqueueScoreIngestion,+ updateJobExecution,+ });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected categories",+ },+ score: {+ description: "Choose all matching categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ },+ },+ },+ }),+ );++ expect(uploadScore).toHaveBeenCalledTimes(2);+ expect(enqueueScoreIngestion).toHaveBeenCalledTimes(2);++ const firstUploadCall = uploadScore.mock.calls[0][0];+ const secondUploadCall = uploadScore.mock.calls[1][0];++ expect(firstUploadCall.event.body.value).toBe("correct");+ expect(secondUploadCall.event.body.value).toBe("partial");+ expect(firstUploadCall.event.body.comment).toBe(+ "Both categories apply to the answer.",+ );+ expect(secondUploadCall.event.body.comment).toBe(+ "Both categories apply to the answer.",+ );+ expect(firstUploadCall.scoreId).not.toBe(secondUploadCall.scoreId);+ expect(firstUploadCall.event.body.executionTraceId).toBe(+ secondUploadCall.event.body.executionTraceId,+ );+ expect(firstUploadCall.event.body.metadata).toEqual(+ secondUploadCall.event.body.metadata,+ );++ expect(updateJobExecution).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ jobOutputScoreId: firstUploadCall.scoreId,+ }),+ }),+ );+ });++ it("should fail multi-match categorical evals when the model returns a scalar", async () => {+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ "correct",+ "This should fail because multi-match expects an array.",+ ),+ });++ await expect(+ executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected categories",+ },+ score: {+ description: "Choose all matching categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ },+ },+ },+ }),+ ),+ ).rejects.toThrow(UnrecoverableError);+ });++ it("should fail multi-match categorical evals when the model returns duplicate matches", async () => {+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ ["correct", "correct"],+ "This should fail because duplicates are not allowed.",+ ),+ });++ await expect(+ executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.CATEGORICAL,+ reasoning: {+ description: "Explain the selected categories",+ },+ score: {+ description: "Choose all matching categories",+ categories: ["correct", "partial"],+ shouldAllowMultipleMatches: true,+ },+ },+ },+ }),+ ),+ ).rejects.toThrow(UnrecoverableError);+ });});describe("LLM errors", () => {diff --git a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts b/worker/src/features/evaluation/observationEval/__tests__/fixtures.tsindex 105fc316e3..d07430c9e3 100644--- a/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/fixtures.ts@@ -254,7 +254,7 @@ export function createMockEvalTemplate(model: string;provider: string;modelParams: Record<string, unknown>;- outputSchema: Record<string, string>;+ outputDefinition: Record<string, string>;vars: string[];createdAt: Date;updatedAt: Date;@@ -271,7 +271,7 @@ export function createMockEvalTemplate(model: overrides.model ?? "gpt-4",provider: overrides.provider ?? "openai",modelParams: overrides.modelParams ?? {},- outputSchema: overrides.outputSchema ?? {+ outputDefinition: overrides.outputDefinition ?? {score: "A number between 0 and 1",reasoning: "Explain your reasoning",},diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.tsindex 6563ca833b..4889eed584 100644--- a/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEval.e2e.test.ts@@ -162,7 +162,7 @@ describe("Observation Eval E2E Pipeline", () => {model: "gpt-4",provider: "openai",modelParams: {},- outputSchema: {+ outputDefinition: {score: "A number between 0 and 1",reasoning: "Explanation",},@@ -391,7 +391,7 @@ describe("Observation Eval E2E Pipeline", () => {model: "gpt-4",provider: "openai",modelParams: {},- outputSchema: { score: "0-1", reasoning: "Why" },+ outputDefinition: { score: "0-1", reasoning: "Why" },vars: ["question", "answer"],createdAt: new Date(),updatedAt: new Date(),@@ -491,7 +491,7 @@ describe("Observation Eval E2E Pipeline", () => {model: "gpt-4",provider: "openai",modelParams: {},- outputSchema: { score: "0-1", reasoning: "Why" },+ outputDefinition: { score: "0-1", reasoning: "Why" },vars: ["generated", "expected"],createdAt: new Date(),updatedAt: new Date(),diff --git a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts b/worker/src/features/evaluation/observationEval/createSchedulerDeps.tsindex 44eba5fa7e..5aca3176d6 100644--- a/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts+++ b/worker/src/features/evaluation/observationEval/createSchedulerDeps.ts@@ -38,6 +38,7 @@ export function createObservationEvalSchedulerDeps(): ObservationEvalSchedulerDejobInputObservationId,jobTemplateId,status,+ startTime: new Date(),},update: {status,diff --git a/worker/src/scripts/upsertManagedEvaluators.ts b/worker/src/scripts/upsertManagedEvaluators.tsindex 77219370f1..74fddd9547 100644--- a/worker/src/scripts/upsertManagedEvaluators.ts+++ b/worker/src/scripts/upsertManagedEvaluators.ts@@ -2,7 +2,10 @@ import { z } from "zod/v4";import { prisma } from "@langfuse/shared/src/db";import managedEvaluators from "../constants/managed-evaluators.json";import { logger } from "@langfuse/shared/src/server";-import { extractVariables } from "@langfuse/shared";+import {+ extractVariables,+ PersistedEvalOutputDefinitionSchema,+} from "@langfuse/shared";const ManagedEvaluatorSchema = z.object({id: z.string(),@@ -11,10 +14,7 @@ const ManagedEvaluatorSchema = z.object({name: z.string(),partner: z.string().nullish(),version: z.number(),- outputSchema: z.object({- score: z.string(),- reasoning: z.string(),- }),+ outputDefinition: PersistedEvalOutputDefinitionSchema,prompt: z.string(),});@@ -67,7 +67,7 @@ export const upsertManagedEvaluators = async (force = false) => {name: evaluator.name,partner: evaluator.partner,version: evaluator.version,- outputSchema: evaluator.outputSchema,+ outputDefinition: evaluator.outputDefinition,prompt: evaluator.prompt,updatedAt: evaluator.updated_at,};