🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(evals): add boolean scores for LLM-as-a-judge (#12836)
Hassieb Pakzadbea079756f5f
diff --git a/packages/shared/src/features/evals/outputDefinition.ts b/packages/shared/src/features/evals/outputDefinition.tsindex a8d7ef1f3d..5068c77d94 100644--- a/packages/shared/src/features/evals/outputDefinition.ts+++ b/packages/shared/src/features/evals/outputDefinition.ts@@ -4,6 +4,7 @@ import { ScoreDataTypeEnum } from "../../domain/scores";export const EvalOutputDataTypeSchema = z.enum([ScoreDataTypeEnum.NUMERIC,ScoreDataTypeEnum.CATEGORICAL,+ ScoreDataTypeEnum.BOOLEAN,]);export type EvalOutputDataType = z.infer<typeof EvalOutputDataTypeSchema>;@@ -78,6 +79,16 @@ export type NumericEvalOutputDefinitionV2 = z.infer<typeof NumericEvalOutputDefinitionV2Schema>;+export const BooleanEvalOutputDefinitionV2Schema = z.object({+ version: z.literal(2),+ dataType: z.literal(ScoreDataTypeEnum.BOOLEAN),+ reasoning: EvalOutputFieldDefinitionSchema,+ score: EvalOutputFieldDefinitionSchema,+});+export type BooleanEvalOutputDefinitionV2 = z.infer<+ typeof BooleanEvalOutputDefinitionV2Schema+>;+export const CategoricalEvalOutputDefinitionV2Schema = z.object({version: z.literal(2),@@ -118,6 +129,7 @@ export type CategoricalEvalOutputDefinitionV2 = z.infer<export const PersistedEvalOutputDefinitionSchema = z.union([LegacyEvalOutputDefinitionSchema,NumericEvalOutputDefinitionV2Schema,+ BooleanEvalOutputDefinitionV2Schema,CategoricalEvalOutputDefinitionV2Schema,]);export type PersistedEvalOutputDefinition = z.infer<@@ -130,6 +142,11 @@ export type ResolvedEvalOutputDefinition =reasoningDescription: string;scoreDescription: string;}+ | {+ dataType: typeof ScoreDataTypeEnum.BOOLEAN;+ reasoningDescription: string;+ scoreDescription: string;+ }| {dataType: typeof ScoreDataTypeEnum.CATEGORICAL;reasoningDescription: string;@@ -139,7 +156,7 @@ export type ResolvedEvalOutputDefinition =};type RawEvalOutputResult = {- score: number | string | string[];+ score: number | boolean | string | string[];reasoning: string;};@@ -149,6 +166,11 @@ export type EvalOutputResult =score: number;reasoning: string;}+ | {+ dataType: typeof ScoreDataTypeEnum.BOOLEAN;+ score: boolean;+ reasoning: string;+ }| {dataType: typeof ScoreDataTypeEnum.CATEGORICAL;matches: string[];@@ -168,9 +190,12 @@ export function resolvePersistedEvalOutputDefinition(};}- if (outputDefinition.dataType === ScoreDataTypeEnum.NUMERIC) {+ if (+ outputDefinition.dataType === ScoreDataTypeEnum.NUMERIC ||+ outputDefinition.dataType === ScoreDataTypeEnum.BOOLEAN+ ) {return {- dataType: ScoreDataTypeEnum.NUMERIC,+ dataType: outputDefinition.dataType,reasoningDescription: outputDefinition.reasoning.description,scoreDescription: outputDefinition.score.description,};@@ -202,6 +227,22 @@ export function createNumericEvalOutputDefinition(params: {});}+export function createBooleanEvalOutputDefinition(params: {+ reasoningDescription: string;+ scoreDescription: string;+}) {+ return BooleanEvalOutputDefinitionV2Schema.parse({+ version: 2,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ reasoning: {+ description: params.reasoningDescription,+ },+ score: {+ description: params.scoreDescription,+ },+ });+}+export function createCategoricalEvalOutputDefinition(params: {reasoningDescription: string;scoreDescription: string;@@ -225,6 +266,10 @@ export function createCategoricalEvalOutputDefinition(params: {function buildResultSchemaForResolvedOutputDefinition(resolvedOutputDefinition: ResolvedEvalOutputDefinition,) {+ const reasoningSchema = z+ .string()+ .describe(resolvedOutputDefinition.reasoningDescription);+if (resolvedOutputDefinition.dataType === ScoreDataTypeEnum.CATEGORICAL) {const [firstCategory, ...remainingCategories] =resolvedOutputDefinition.categories;@@ -256,17 +301,20 @@ function buildResultSchemaForResolvedOutputDefinition(: categoricalValueSchema;return z.object({- reasoning: z- .string()- .describe(resolvedOutputDefinition.reasoningDescription),+ reasoning: reasoningSchema,score: scoreSchema.describe(resolvedOutputDefinition.scoreDescription),});}+ if (resolvedOutputDefinition.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return z.object({+ reasoning: reasoningSchema,+ score: z.boolean().describe(resolvedOutputDefinition.scoreDescription),+ });+ }+return z.object({- reasoning: z- .string()- .describe(resolvedOutputDefinition.reasoningDescription),+ reasoning: reasoningSchema,score: z.number().describe(resolvedOutputDefinition.scoreDescription),});}@@ -310,6 +358,14 @@ function normalizeValidatedEvalOutputResult(};}+ if (resolvedOutputDefinition.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return {+ dataType: ScoreDataTypeEnum.BOOLEAN,+ score: result.score as boolean,+ reasoning: result.reasoning,+ };+ }+return {dataType: ScoreDataTypeEnum.CATEGORICAL,matches: Array.isArray(result.score)diff --git a/web/src/__tests__/server/eval-template-output-definition.servertest.ts b/web/src/__tests__/server/eval-template-output-definition.servertest.tsindex 57c3aa766d..7aec53d652 100644--- a/web/src/__tests__/server/eval-template-output-definition.servertest.ts+++ b/web/src/__tests__/server/eval-template-output-definition.servertest.ts@@ -2,6 +2,7 @@import { CreateEvalTemplateInputSchema } from "@/src/features/evals/server/router";import {+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,ScoreDataTypeEnum,@@ -57,6 +58,19 @@ describe("CreateEvalTemplateInputSchema", () => {expect(result.success).toBe(true);});+ it("accepts versioned boolean output definitions", () => {+ const result = CreateEvalTemplateInputSchema.safeParse({+ ...baseInput,+ outputDefinition: createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer satisfies the criteria, otherwise false",+ reasoningDescription: "Explain the verdict",+ }),+ });++ expect(result.success).toBe(true);+ });+it("rejects duplicate categories", () => {const result = CreateEvalTemplateInputSchema.safeParse({...baseInput,diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.tsindex 284ed59409..58a6b98346 100644--- a/web/src/__tests__/server/evals-trpc.servertest.ts+++ b/web/src/__tests__/server/evals-trpc.servertest.ts@@ -5,6 +5,7 @@ import { createInnerTRPCContext } from "@/src/server/api/trpc";import { prisma } from "@langfuse/shared/src/db";import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import {+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,EvalTargetObject,@@ -273,6 +274,20 @@ describe("evals trpc", () => {},});+ const booleanTemplate = await prisma.evalTemplate.create({+ data: {+ projectId: project.id,+ name: "boolean-template",+ version: 1,+ prompt: "Judge whether the response satisfies the criteria",+ outputDefinition: createBooleanEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription:+ "Return true if the response satisfies the criteria, otherwise false",+ }),+ },+ });+const response = await caller.evals.templateNames({projectId: project.id,page: 0,@@ -295,6 +310,13 @@ describe("evals trpc", () => {dataType: "CATEGORICAL",}),}),+ expect.objectContaining({+ latestId: booleanTemplate.id,+ name: "boolean-template",+ outputDefinition: expect.objectContaining({+ dataType: "BOOLEAN",+ }),+ }),]),);});diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsxindex 8af67bccf9..d22be84056 100644--- a/web/src/features/evals/components/template-form.tsx+++ b/web/src/features/evals/components/template-form.tsx@@ -15,6 +15,7 @@ import {import { api } from "@/src/utils/api";import { zodResolver } from "@hookform/resolvers/zod";import {+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,EvalOutputDataTypeSchema,@@ -314,6 +315,7 @@ export const InnerEvalTemplateForm = (props: {const useDefaultModel = form.watch("shouldUseDefaultModel");const scoreDataType = form.watch("scoreDataType");const isCategoricalOutput = scoreDataType === ScoreDataTypeEnum.CATEGORICAL;+ const isBooleanOutput = scoreDataType === ScoreDataTypeEnum.BOOLEAN;const shouldAllowMultipleMatches = form.watch("shouldAllowMultipleMatches");const categoriesError = form.formState.errors.categories;const categoriesErrorMessage =@@ -326,6 +328,7 @@ export const InnerEvalTemplateForm = (props: {const applyDefaultOutputDefinitionCopy = (params: {scoreDataType:| typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.BOOLEAN| typeof ScoreDataTypeEnum.CATEGORICAL;shouldAllowMultipleMatches: boolean;}) => {@@ -410,10 +413,15 @@ export const InnerEvalTemplateForm = (props: {categories: values.categories.map((category) => category.value),shouldAllowMultipleMatches: values.shouldAllowMultipleMatches,})- : createNumericEvalOutputDefinition({- scoreDescription: values.scoreDescription,- reasoningDescription: values.reasoningDescription,- });+ : values.scoreDataType === ScoreDataTypeEnum.BOOLEAN+ ? createBooleanEvalOutputDefinition({+ scoreDescription: values.scoreDescription,+ reasoningDescription: values.reasoningDescription,+ })+ : createNumericEvalOutputDefinition({+ scoreDescription: values.scoreDescription,+ reasoningDescription: values.reasoningDescription,+ });const evalTemplate = {name: values.name,@@ -632,8 +640,8 @@ export const InnerEvalTemplateForm = (props: {<FormItem><FormLabel>Score type</FormLabel><FormDescription>- Choose whether the evaluator should return a numeric score or- one of a fixed set of categories.+ Choose whether the evaluator should return a numeric score, a+ boolean verdict, or one of a fixed set of categories.</FormDescription><Selectvalue={field.value}@@ -641,6 +649,7 @@ export const InnerEvalTemplateForm = (props: {onValueChange={(value) => {const nextScoreDataType = value as| typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.BOOLEAN| typeof ScoreDataTypeEnum.CATEGORICAL;const shouldEnableMultipleMatches =nextScoreDataType === ScoreDataTypeEnum.CATEGORICAL@@ -681,6 +690,9 @@ export const InnerEvalTemplateForm = (props: {<SelectItem value={ScoreDataTypeEnum.NUMERIC}>Numeric</SelectItem>+ <SelectItem value={ScoreDataTypeEnum.BOOLEAN}>+ Boolean+ </SelectItem><SelectItem value={ScoreDataTypeEnum.CATEGORICAL}>Categorical</SelectItem>@@ -815,14 +827,18 @@ export const InnerEvalTemplateForm = (props: {<FormLabel>{isCategoricalOutput? "Category selection prompt"- : "Score output prompt"}+ : isBooleanOutput+ ? "Boolean verdict prompt"+ : "Score output prompt"}</FormLabel><FormDescription>{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."}+ : isBooleanOutput+ ? "Define how the LLM should return either true or false based on the evaluation criteria."+ : "Define how the LLM should return the evaluation score in natural language. Needs to yield a numeric value."}</FormDescription><FormControl><Input {...field} />diff --git a/web/src/features/evals/utils/template-form-defaults.ts b/web/src/features/evals/utils/template-form-defaults.tsindex 24f2022ee7..b22d9818f6 100644--- a/web/src/features/evals/utils/template-form-defaults.ts+++ b/web/src/features/evals/utils/template-form-defaults.ts@@ -9,6 +9,16 @@ export const numericOutputDefinitionDefaults = {shouldAllowMultipleMatches: false,};+export const booleanOutputDefinitionDefaults = {+ scoreDataType: ScoreDataTypeEnum.BOOLEAN,+ reasoningDescription:+ "Explain briefly why the answer does or does not satisfy the criteria.",+ scoreDescription:+ "Return true if the answer satisfies the criteria, otherwise return false.",+ categories: [] as Array<{ value: string }>,+ shouldAllowMultipleMatches: false,+};+export const categoricalSingleOutputDefinitionDefaults = {scoreDataType: ScoreDataTypeEnum.CATEGORICAL,reasoningDescription: "Explain why the selected category is the best match.",@@ -29,6 +39,7 @@ export const categoricalMultiOutputDefinitionDefaults = {export const getDefaultOutputDefinitionFormValues = (params?: {scoreDataType?:| typeof ScoreDataTypeEnum.NUMERIC+ | typeof ScoreDataTypeEnum.BOOLEAN| typeof ScoreDataTypeEnum.CATEGORICAL;shouldAllowMultipleMatches?: boolean;}) => {@@ -38,12 +49,17 @@ export const getDefaultOutputDefinitionFormValues = (params?: {: categoricalSingleOutputDefinitionDefaults;}+ if (params?.scoreDataType === ScoreDataTypeEnum.BOOLEAN) {+ return booleanOutputDefinitionDefaults;+ }+return numericOutputDefinitionDefaults;};const defaultReasoningDescriptions = new Set([numericOutputDefinitionDefaults.reasoningDescription,+ booleanOutputDefinitionDefaults.reasoningDescription,categoricalSingleOutputDefinitionDefaults.reasoningDescription,categoricalMultiOutputDefinitionDefaults.reasoningDescription,"One sentence reasoning for the score",@@ -53,6 +69,7 @@ const defaultReasoningDescriptions = new Set(const defaultScoreDescriptions = new Set([numericOutputDefinitionDefaults.scoreDescription,+ booleanOutputDefinitionDefaults.scoreDescription,categoricalSingleOutputDefinitionDefaults.scoreDescription,categoricalMultiOutputDefinitionDefaults.scoreDescription,"Score between 0 and 1. Score 0 if false or negative and 1 if true or positive.",diff --git a/web/src/features/evals/utils/template-output.clienttest.ts b/web/src/features/evals/utils/template-output.clienttest.tsindex fcac93feb1..a05cc89051 100644--- a/web/src/features/evals/utils/template-output.clienttest.ts+++ b/web/src/features/evals/utils/template-output.clienttest.ts@@ -1,4 +1,5 @@import {+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,} from "@langfuse/shared";@@ -28,6 +29,17 @@ describe("getTemplateResultType", () => {).toBe("Categorical");});+ it("returns Boolean for boolean output definitions", () => {+ expect(+ getTemplateResultType(+ createBooleanEvalOutputDefinition({+ reasoningDescription: "Why",+ scoreDescription: "Return true or false",+ }),+ ),+ ).toBe("Boolean");+ });+it("returns Numeric for legacy output definitions", () => {expect(getTemplateResultType({diff --git a/web/src/features/evals/utils/template-output.ts b/web/src/features/evals/utils/template-output.tsindex a61fabeed4..1d13e389f2 100644--- a/web/src/features/evals/utils/template-output.ts+++ b/web/src/features/evals/utils/template-output.ts@@ -25,8 +25,14 @@ export const getTemplateResultType = (outputDefinition: unknown) => {return "Unknown";}- return resolvePersistedEvalOutputDefinition(parsedOutputDefinition.data)- .dataType === ScoreDataTypeEnum.CATEGORICAL- ? "Categorical"- : "Numeric";+ switch (+ resolvePersistedEvalOutputDefinition(parsedOutputDefinition.data).dataType+ ) {+ case ScoreDataTypeEnum.CATEGORICAL:+ return "Categorical";+ case ScoreDataTypeEnum.BOOLEAN:+ return "Boolean";+ default:+ return "Numeric";+ }};diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.tsindex f604632b16..a77fef1709 100644--- a/worker/src/__tests__/llmConnections.test.ts+++ b/worker/src/__tests__/llmConnections.test.ts@@ -7,6 +7,7 @@ import { encrypt } from "@langfuse/shared/encryption";import {buildEvalOutputResultSchema,ChatMessageType,+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,type PersistedEvalOutputDefinition,@@ -22,7 +23,7 @@ import { z } from "zod";* Each adapter is tested with:* 1. Simple completion* 2. Streaming completion- * 3. Structured output (legacy eval schema, v2 numeric schema, v2 categorical schema)+ * 3. Structured output (legacy eval schema, v2 numeric schema, v2 boolean schema, v2 categorical schema)* 4. Tool calling** Required environment variables (tests will FAIL if not set):@@ -50,6 +51,11 @@ const numericEvalResponseSchema = z.object({reasoning: z.string().min(1),});+const booleanEvalResponseSchema = z.object({+ score: z.boolean(),+ reasoning: z.string().min(1),+});+const categoricalScoreValues = ["correct", "incorrect"] as const;const categoricalEvalResponseSchema = z.object({score: z.enum(categoricalScoreValues),@@ -61,7 +67,10 @@ type EvalStructuredOutputTestCase = {prompt: string;outputDefinition: PersistedEvalOutputDefinition;responseSchema: z.ZodTypeAny;- assertParsed?: (data: { score: number | string; reasoning: string }) => void;+ assertParsed?: (data: {+ score: number | boolean | string;+ reasoning: string;+ }) => void;};const evalStructuredOutputTestCases: EvalStructuredOutputTestCase[] = [@@ -87,6 +96,20 @@ const evalStructuredOutputTestCases: EvalStructuredOutputTestCase[] = [}),responseSchema: numericEvalResponseSchema,},+ {+ name: "structured output - v2 boolean eval schema",+ prompt:+ "Judge whether the answer '2 + 2 = 5' is correct. Return true only if it is mathematically correct, otherwise false, and explain briefly.",+ outputDefinition: createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true when the answer is mathematically correct, otherwise return false.",+ reasoningDescription: "Explain briefly why you chose that verdict.",+ }),+ responseSchema: booleanEvalResponseSchema,+ assertParsed: (data) => {+ expect(data.score).toBe(false);+ },+ },{name: "structured output - v2 categorical eval schema",prompt:diff --git a/worker/src/features/evaluation/evalScoreEvent.ts b/worker/src/features/evaluation/evalScoreEvent.tsindex b569c191a1..bfa2d7fa72 100644--- a/worker/src/features/evaluation/evalScoreEvent.ts+++ b/worker/src/features/evaluation/evalScoreEvent.ts@@ -24,6 +24,10 @@ export type BuildScoreEventParams = BuildScoreEventBase &dataType: typeof ScoreDataTypeEnum.NUMERIC;scoreValue: number;}+ | {+ dataType: typeof ScoreDataTypeEnum.BOOLEAN;+ scoreValue: 0 | 1;+ }| {dataType: typeof ScoreDataTypeEnum.CATEGORICAL;scoreValue: string;@@ -38,6 +42,13 @@ type BuildScoreWritePayloadParams =>,"eventId">+ | Omit<+ Extract<+ BuildScoreEventParams,+ { dataType: typeof ScoreDataTypeEnum.BOOLEAN }+ >,+ "eventId"+ >| Omit<Extract<BuildScoreEventParams,@@ -88,6 +99,17 @@ export function buildScoreEvent(params: BuildScoreEventParams): ScoreEventType {});}+ if (params.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return createScoreEventEnvelope({+ eventId: params.eventId,+ body: {+ ...bodyBase,+ value: params.scoreValue,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ },+ });+ }+return createScoreEventEnvelope({eventId: params.eventId,body: {@@ -116,6 +138,19 @@ function buildScoreWritePayload(};}+ if (params.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return {+ eventId,+ scoreId: params.scoreId,+ event: buildScoreEvent({+ ...params,+ eventId,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ scoreValue: params.scoreValue,+ }),+ };+ }+return {eventId,scoreId: params.scoreId,@@ -159,6 +194,17 @@ export function buildEvalScoreWritePayloads(params: {];}+ if (params.outputResult.dataType === ScoreDataTypeEnum.BOOLEAN) {+ return [+ buildScoreWritePayload({+ ...commonParams,+ scoreId: params.primaryScoreId,+ scoreValue: params.outputResult.score ? 1 : 0,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ }),+ ];+ }+return params.outputResult.matches.map((scoreValue, index) =>buildScoreWritePayload({...commonParams,diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex b93878fa0c..9bf4ce9d3a 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -921,7 +921,9 @@ export async function executeLLMAsJudgeEvaluation({`Job ${jobExecutionId} received LLM output: ${parsedLLMOutput.data.dataType === ScoreDataTypeEnum.NUMERIC? `score=${parsedLLMOutput.data.score}`- : `matches=${parsedLLMOutput.data.matches.join(",")}`+ : parsedLLMOutput.data.dataType === ScoreDataTypeEnum.BOOLEAN+ ? `score=${parsedLLMOutput.data.score}`+ : `matches=${parsedLLMOutput.data.matches.join(",")}`}`,);@@ -984,7 +986,9 @@ export async function executeLLMAsJudgeEvaluation({`Eval job ${job.id} completed with ${parsedLLMOutput.data.dataType === ScoreDataTypeEnum.NUMERIC? `score ${parsedLLMOutput.data.score}`- : `matches ${parsedLLMOutput.data.matches.join(",")}`+ : parsedLLMOutput.data.dataType === ScoreDataTypeEnum.BOOLEAN+ ? `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.tsindex 1330b52607..aab5792554 100644--- a/worker/src/features/evaluation/evaluationHelpers.test.ts+++ b/worker/src/features/evaluation/evaluationHelpers.test.ts@@ -4,6 +4,7 @@ import {buildEvalOutputResultSchema,ChatMessageRole,ChatMessageType,+ createBooleanEvalOutputDefinition,createCategoricalEvalOutputDefinition,createNumericEvalOutputDefinition,PersistedEvalOutputDefinitionSchema,@@ -132,6 +133,40 @@ describe("evaluation helpers", () => {expect(result.success).toBe(false);});+ it("should validate boolean responses", () => {+ const schema = buildEvalOutputResultSchema(+ createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer is correct, otherwise false",+ reasoningDescription: "Explain the verdict",+ }),+ );++ expect(+ schema.safeParse({+ score: true,+ reasoning: "The answer satisfies the criteria.",+ }).success,+ ).toBe(true);+ });++ it("should reject string values for boolean responses", () => {+ const schema = buildEvalOutputResultSchema(+ createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer is correct, otherwise false",+ reasoningDescription: "Explain the verdict",+ }),+ );++ expect(+ schema.safeParse({+ score: "true",+ reasoning: "String booleans should be rejected.",+ }).success,+ ).toBe(false);+ });+it("should validate categorical responses against allowed values", () => {const schema = buildEvalOutputResultSchema(createCategoricalEvalOutputDefinition({@@ -389,6 +424,25 @@ describe("evaluation helpers", () => {expect(result.body.value).toBe("correct");expect(result.body.dataType).toBe("CATEGORICAL");});++ it("should build boolean score events", () => {+ const result = buildScoreEvent({+ eventId: "event-123",+ scoreId: "score-456",+ traceId: "trace-789",+ observationId: null,+ scoreName: "correctness",+ scoreValue: 1,+ reasoning: "The answer meets the criteria.",+ environment: "production",+ executionTraceId: "exec-trace-abc",+ metadata: { job_execution_id: "exec-123" },+ dataType: ScoreDataTypeEnum.BOOLEAN,+ });++ expect(result.body.value).toBe(1);+ expect(result.body.dataType).toBe("BOOLEAN");+ });});describe("buildEvalScoreWritePayloads", () => {@@ -421,6 +475,35 @@ describe("evaluation helpers", () => {});});+ it("should build a single boolean score payload", () => {+ const result = buildEvalScoreWritePayloads({+ outputResult: {+ dataType: ScoreDataTypeEnum.BOOLEAN,+ score: true,+ reasoning: "The answer satisfies the criteria",+ },+ primaryScoreId: "score-123",+ traceId: "trace-456",+ observationId: null,+ scoreName: "correctness",+ 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: 1,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ }),+ }),+ });+ });+it("should build one categorical payload per match while preserving shared metadata", () => {const result = buildEvalScoreWritePayloads({outputResult: {@@ -565,6 +648,48 @@ describe("evaluation helpers", () => {expect(result.success).toBe(false);});+ it("should normalize boolean responses", () => {+ const outputDefinition = createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer is correct, otherwise false",+ reasoningDescription: "Why",+ });++ const result = validateEvalOutputResult({+ response: { score: false, reasoning: "The answer is incorrect." },+ compiledOutputDefinition:+ compilePersistedEvalOutputDefinition(outputDefinition),+ });++ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data).toEqual({+ dataType: ScoreDataTypeEnum.BOOLEAN,+ score: false,+ reasoning: "The answer is incorrect.",+ });+ }+ });++ it("should reject invalid boolean responses", () => {+ const outputDefinition = createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer is correct, otherwise false",+ reasoningDescription: "Why",+ });++ const result = validateEvalOutputResult({+ response: {+ score: "false",+ reasoning: "String booleans are invalid.",+ },+ 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",@@ -705,6 +830,18 @@ describe("evaluation helpers", () => {expect(result.success).toBe(true);});+ it("should accept versioned boolean schemas", () => {+ const result = PersistedEvalOutputDefinitionSchema.safeParse(+ createBooleanEvalOutputDefinition({+ scoreDescription:+ "Return true if the answer is correct, otherwise false",+ reasoningDescription: "Explain the verdict",+ }),+ );++ expect(result.success).toBe(true);+ });+it("should accept versioned categorical multi-match schemas", () => {const result = PersistedEvalOutputDefinitionSchema.safeParse(createCategoricalEvalOutputDefinition({diff --git a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.tsindex 57fab20f54..abd3ca6fb7 100644--- a/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts+++ b/worker/src/features/evaluation/executeLLMAsJudgeEvaluation.test.ts@@ -127,7 +127,7 @@ describe("executeLLMAsJudgeEvaluation", () => {/** Creates a mock for callLLM with a successful response */const mockSuccessfulLLMCall = (- score: number | string | string[],+ score: number | boolean | string | string[],reasoning: string,) => vi.fn().mockResolvedValue({ score, reasoning });@@ -569,6 +569,50 @@ describe("executeLLMAsJudgeEvaluation", () => {).toBe(false);});+ it("should pass boolean structured output schema to LLM", async () => {+ const callLLM = mockSuccessfulLLMCall(+ false,+ "The answer does not satisfy the criteria.",+ );+ const deps = createSuccessfulDeps({ callLLM });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ reasoning: {+ description: "Explain the verdict",+ },+ score: {+ description:+ "Return true if the answer satisfies the criteria, otherwise false",+ },+ },+ },+ }),+ );++ const structuredOutputSchema = callLLM.mock.calls[0][0]+ .structuredOutputSchema as z.ZodTypeAny;++ expect(+ structuredOutputSchema.safeParse({+ score: true,+ reasoning: "The answer satisfies the criteria.",+ }).success,+ ).toBe(true);+ expect(+ structuredOutputSchema.safeParse({+ score: "true",+ reasoning: "String values should be rejected.",+ }).success,+ ).toBe(false);+ });+it("should pass model config to LLM", async () => {const customModelConfig = {provider: "anthropic",@@ -850,6 +894,80 @@ describe("executeLLMAsJudgeEvaluation", () => {);});+ it("should persist boolean eval scores", async () => {+ const uploadScore = vi.fn();+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ true,+ "The answer satisfies the criteria.",+ ),+ uploadScore,+ });++ await executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ reasoning: {+ description: "Explain the verdict",+ },+ score: {+ description:+ "Return true if the answer satisfies the criteria, otherwise false",+ },+ },+ },+ }),+ );++ expect(uploadScore).toHaveBeenCalledWith(+ expect.objectContaining({+ event: expect.objectContaining({+ body: expect.objectContaining({+ value: 1,+ comment: "The answer satisfies the criteria.",+ dataType: "BOOLEAN",+ }),+ }),+ }),+ );+ });++ it("should fail boolean evals when the model returns a string", async () => {+ const deps = createSuccessfulDeps({+ callLLM: mockSuccessfulLLMCall(+ "true",+ "Strings should not be accepted for boolean evaluators.",+ ),+ });++ await expect(+ executeLLMAsJudgeEvaluation(+ createExecutionParams({+ deps,+ template: {+ ...mockEvalTemplate,+ outputDefinition: {+ version: 2,+ dataType: ScoreDataTypeEnum.BOOLEAN,+ reasoning: {+ description: "Explain the verdict",+ },+ score: {+ description:+ "Return true if the answer satisfies the criteria, otherwise false",+ },+ },+ },+ }),+ ),+ ).rejects.toThrow(UnrecoverableError);+ });+it("should fail categorical evals when the model returns a category outside the allowed set", async () => {const deps = createSuccessfulDeps({callLLM: mockSuccessfulLLMCall(