Skip to content

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

feat(evals): decision-model evaluators with TypeSafe Jev (experimental) (#17733)

Hassieb Pakzadb6e0baf7795f
diff --git a/packages/shared/package.json b/packages/shared/package.json
index e271d7b055..89f776a992 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -169,6 +169,7 @@
"@ai-sdk/google-vertex": "^5.0.8",
"@ai-sdk/openai": "^4.0.0",
"@ai-sdk/openai-compatible": "^3.0.3",
+ "@ai-sdk/typesafe-ai": "^3.0.4",
"@aws-sdk/client-cloudwatch": "catalog:",
"@aws-sdk/client-lambda": "catalog:",
"@aws-sdk/client-s3": "catalog:",
diff --git a/packages/shared/prisma/migrations/20260921150000_add_decision_model_eval_template_type/migration.sql b/packages/shared/prisma/migrations/20260921150000_add_decision_model_eval_template_type/migration.sql
new file mode 100644
index 0000000000..aa8235e72f
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260921150000_add_decision_model_eval_template_type/migration.sql
@@ -0,0 +1 @@
+ALTER TYPE "EvalTemplateType" ADD VALUE 'DECISION_MODEL';
diff --git a/packages/shared/prisma/migrations/20260921191000_add_evaluator_version_questions/migration.sql b/packages/shared/prisma/migrations/20260921191000_add_evaluator_version_questions/migration.sql
new file mode 100644
index 0000000000..d804817e0c
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260921191000_add_evaluator_version_questions/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "evaluator_versions" ADD COLUMN "questions" JSONB;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index d4d3c57387..a50420f0df 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1011,6 +1011,7 @@ model EvaluatorVersion {
outputDefinition Json? @map("output_definition")
sourceCode String? @map("source_code") @db.VarChar(262144)
sourceCodeLanguage EvaluatorSourceCodeLanguage? @map("source_code_language")
+ questions Json?
@@unique([evaluatorId, version(sort: Desc)])
@@map("evaluator_versions")
@@ -1019,6 +1020,7 @@ model EvaluatorVersion {
enum EvalTemplateType {
LLM_AS_JUDGE
CODE
+ DECISION_MODEL
}
enum EvalTemplateSourceCodeLanguage {
diff --git a/packages/shared/src/features/evals/decisionModel.ts b/packages/shared/src/features/evals/decisionModel.ts
new file mode 100644
index 0000000000..794f8c5e77
--- /dev/null
+++ b/packages/shared/src/features/evals/decisionModel.ts
@@ -0,0 +1,137 @@
+import { z } from "zod";
+import { jsonSchema } from "../../utils/zod";
+
+export const DecisionModelQuestionType = {
+ CHOICE: "choice",
+ SCORE: "score",
+ NOUL: "noul",
+} as const;
+export type DecisionModelQuestionType =
+ (typeof DecisionModelQuestionType)[keyof typeof DecisionModelQuestionType];
+
+export const DECISION_MODEL_LIMITS = {
+ maxQuestions: 50,
+ minChoiceOptions: 2,
+ maxChoiceOptions: 255,
+ minScoreLevels: 2,
+ maxScoreLevels: 10,
+ maxInstructionLength: 20_000,
+ maxScoreNameLength: 100,
+} as const;
+
+export const DecisionModelEntrySchema = z.union([
+ z.string().trim().min(1).max(DECISION_MODEL_LIMITS.maxInstructionLength),
+ jsonSchema,
+]);
+export type DecisionModelEntry = z.infer<typeof DecisionModelEntrySchema>;
+
+const STATE_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export const DecisionModelStateKeySchema = z
+ .string()
+ .regex(
+ STATE_KEY_PATTERN,
+ "State keys must start with a letter or underscore and contain only letters, digits, and underscores",
+ );
+
+const DecisionModelQuestionBaseSchema = z.object({
+ id: z.string().trim().min(1).max(64),
+ scoreName: z
+ .string()
+ .trim()
+ .min(1)
+ .max(DECISION_MODEL_LIMITS.maxScoreNameLength),
+ instructions: DecisionModelEntrySchema,
+});
+
+export const DecisionModelChoiceOptionSchema = z.object({
+ value: z.string().trim().min(1).max(100),
+ description: DecisionModelEntrySchema.nullish(),
+});
+
+export const DecisionModelChoiceQuestionSchema =
+ DecisionModelQuestionBaseSchema.extend({
+ type: z.literal(DecisionModelQuestionType.CHOICE),
+ options: z
+ .array(DecisionModelChoiceOptionSchema)
+ .min(DECISION_MODEL_LIMITS.minChoiceOptions)
+ .max(DECISION_MODEL_LIMITS.maxChoiceOptions)
+ .refine(
+ (options) =>
+ new Set(options.map((option) => option.value)).size ===
+ options.length,
+ { message: "Choice options must be unique" },
+ ),
+ });
+
+export const DecisionModelScoreQuestionSchema =
+ DecisionModelQuestionBaseSchema.extend({
+ type: z.literal(DecisionModelQuestionType.SCORE),
+ levels: z
+ .array(z.object({ description: DecisionModelEntrySchema }))
+ .min(DECISION_MODEL_LIMITS.minScoreLevels)
+ .max(DECISION_MODEL_LIMITS.maxScoreLevels),
+ });
+
+export const DecisionModelNoulQuestionSchema =
+ DecisionModelQuestionBaseSchema.extend({
+ type: z.literal(DecisionModelQuestionType.NOUL),
+ criteria: z
+ .object({
+ true: DecisionModelEntrySchema.nullish(),
+ false: DecisionModelEntrySchema.nullish(),
+ })
+ .nullish(),
+ });
+
+export const DecisionModelQuestionSchema = z.discriminatedUnion("type", [
+ DecisionModelChoiceQuestionSchema,
+ DecisionModelScoreQuestionSchema,
+ DecisionModelNoulQuestionSchema,
+]);
+export type DecisionModelQuestion = z.infer<typeof DecisionModelQuestionSchema>;
+
+export const DecisionModelQuestionsSchema = z
+ .array(DecisionModelQuestionSchema)
+ .min(1)
+ .max(DECISION_MODEL_LIMITS.maxQuestions)
+ .superRefine((questions, ctx) => {
+ const ids = new Set<string>();
+ const scoreNames = new Set<string>();
+ questions.forEach((question, index) => {
+ if (ids.has(question.id)) {
+ ctx.addIssue({
+ code: "custom",
+ message: `Duplicate question id "${question.id}"`,
+ path: [index, "id"],
+ });
+ }
+ ids.add(question.id);
+ if (scoreNames.has(question.scoreName)) {
+ ctx.addIssue({
+ code: "custom",
+ message: `Score name "${question.scoreName}" is used by more than one question`,
+ path: [index, "scoreName"],
+ });
+ }
+ scoreNames.add(question.scoreName);
+ });
+ });
+export type DecisionModelQuestions = z.infer<
+ typeof DecisionModelQuestionsSchema
+>;
+
+export function parseDecisionModelQuestions(
+ value: unknown,
+):
+ | { success: true; data: DecisionModelQuestions }
+ | { success: false; error: string } {
+ const parsed = DecisionModelQuestionsSchema.safeParse(value);
+ if (parsed.success) return { success: true, data: parsed.data };
+ return {
+ success: false,
+ error: parsed.error.issues
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
+ .join("; "),
+ };
+}
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 6edc40ec5b..d8b572d9ea 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -15,6 +15,7 @@ import z from "zod";
export const EvalTemplateTypeEnum = {
LLM_AS_JUDGE: "LLM_AS_JUDGE",
CODE: "CODE",
+ DECISION_MODEL: "DECISION_MODEL",
} as const satisfies Record<EvalTemplateType, EvalTemplateType>;
export const EvalTemplateSourceCodeLanguageEnum = {
@@ -97,9 +98,19 @@ export type EvalTemplateCodeBased = EvalTemplate & {
sourceCodeLanguage: EvalTemplateSourceCodeLanguage;
};
+export type EvalTemplateDecisionModel = EvalTemplate & {
+ type: typeof EvalTemplateType.DECISION_MODEL;
+ prompt: null;
+ outputDefinition: null;
+ sourceCode: null;
+ sourceCodeLanguage: null;
+ questions: unknown;
+};
+
export type EvalTemplateWithType =
| EvalTemplateLlmAsAJudge
- | EvalTemplateCodeBased;
+ | EvalTemplateCodeBased
+ | EvalTemplateDecisionModel;
export const EvalTargetObject = {
TRACE: "trace",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index db37c15a3d..9497bf09a5 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -39,6 +39,7 @@ export * from "./server/llm/promptToolConfig";
export * from "./features/evals/types";
export * from "./features/evals/evalExecutionMetadata";
export * from "./features/evals/outputDefinition";
+export * from "./features/evals/decisionModel";
export * from "./features/evals/codeEvalConstants";
export {
extractValueFromObject,
diff --git a/packages/shared/src/server/evals/decisionModelEvaluatorExecution.test.ts b/packages/shared/src/server/evals/decisionModelEvaluatorExecution.test.ts
new file mode 100644
index 0000000000..97f5afeee1
--- /dev/null
+++ b/packages/shared/src/server/evals/decisionModelEvaluatorExecution.test.ts
@@ -0,0 +1,229 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ DecisionModelQuestionsSchema,
+ type DecisionModelQuestions,
+} from "../../features/evals/decisionModel";
+import {
+ DecisionModelEvaluatorError,
+ executeDecisionModelEvaluator,
+ type DecisionModelClient,
+ type DecisionModelEvaluation,
+} from "./decisionModelEvaluatorExecution";
+
+const questions: DecisionModelQuestions = DecisionModelQuestionsSchema.parse([
+ {
+ id: "readiness",
+ scoreName: "send_readiness",
+ type: "choice",
+ instructions: "Is `reply` ready to send as an answer to `question`?",
+ options: [
+ { value: "ready", description: "Answers and states the next step" },
+ { value: "needs_revision" },
+ ],
+ },
+ {
+ id: "frustration",
+ scoreName: "customer_frustration",
+ type: "score",
+ instructions: "How frustrated is the customer in `question`?",
+ levels: [
+ { description: "Calm" },
+ { description: "Frustrated but civil" },
+ { description: "Very angry" },
+ ],
+ },
+ {
+ id: "refund",
+ scoreName: "refund_requested",
+ type: "noul",
+ instructions: "Does `question` request a refund?",
+ },
+]);
+
+const evaluation: DecisionModelEvaluation = {
+ model: "jev-1.13.0",
+ answers: {
+ readiness: {
+ type: "choice",
+ choice: "ready",
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ confidence: 0.82,
+ },
+ frustration: {
+ type: "score",
+ score: 1.26,
+ probabilities: { "0": 0, "1": 0.74, "2": 0.26 },
+ confidence: 0.61,
+ },
+ refund: { type: "boolean", probability: 0.97 },
+ },
+ usage: { inputTokens: 300, outputTokens: 9 },
+};
+
+function createClient(result: DecisionModelEvaluation) {
+ const evaluate = vi.fn().mockResolvedValue(result);
+ const client: DecisionModelClient = { evaluate };
+ return { client, evaluate };
+}
+
+describe("executeDecisionModelEvaluator", () => {
+ it("sends the mapped fields as state and every question in one request", async () => {
+ const { client, evaluate } = createClient(evaluation);
+
+ await executeDecisionModelEvaluator({
+ variables: [
+ { var: "question", value: "Can I get a refund? Third time asking." },
+ { var: "reply", value: "" },
+ { var: "expected", value: null },
+ { var: "tools", value: undefined },
+ ],
+ questions,
+ client,
+ });
+
+ expect(evaluate).toHaveBeenCalledTimes(1);
+ expect(evaluate).toHaveBeenCalledWith({
+ state: {
+ question: "Can I get a refund? Third time asking.",
+ reply: "",
+ },
+ questions: {
+ readiness: {
+ type: "choice",
+ instructions: "Is `reply` ready to send as an answer to `question`?",
+ criteria: {
+ ready: "Answers and states the next step",
+ needs_revision: null,
+ },
+ },
+ frustration: {
+ type: "score",
+ instructions: "How frustrated is the customer in `question`?",
+ criteria: ["Calm", "Frustrated but civil", "Very angry"],
+ },
+ refund: {
+ type: "boolean",
+ instructions: "Does `question` request a refund?",
+ },
+ },
+ });
+ });
+
+ it("writes one score per question with certainty in metadata", async () => {
+ const { client } = createClient(evaluation);
+
+ const { scores } = await executeDecisionModelEvaluator({
+ variables: [{ var: "question", value: "refund?" }],
+ questions,
+ client,
+ });
+
+ expect(scores).toEqual([
+ {
+ name: "send_readiness",
+ dataType: "CATEGORICAL",
+ value: "ready",
+ comment:
+ "ready (p=0.91); confidence 0.82; runner-up needs_revision (0.09)",
+ metadata: {
+ typesafe: {
+ questionId: "readiness",
+ type: "choice",
+ model: "jev-1.13.0",
+ choice: "ready",
+ confidence: 0.82,
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ },
+ },
+ },
+ {
+ name: "customer_frustration",
+ dataType: "NUMERIC",
+ value: 1.26,
+ comment: '1.26 ≈ level 1 "Frustrated but civil"; confidence 0.61',
+ metadata: {
+ typesafe: {
+ questionId: "frustration",
+ type: "score",
+ model: "jev-1.13.0",
+ confidence: 0.61,
+ probabilities: { "0": 0, "1": 0.74, "2": 0.26 },
+ legend: {
+ "0": "Calm",
+ "1": "Frustrated but civil",
+ "2": "Very angry",
+ },
+ },
+ },
+ },
+ {
+ name: "refund_requested",
+ dataType: "NUMERIC",
+ value: 0.97,
+ comment: "P(true)=0.97",
+ metadata: {
+ typesafe: {
+ questionId: "refund",
+ type: "noul",
+ model: "jev-1.13.0",
+ },
+ },
+ },
+ ]);
+ });
+
+ it("fails permanently when the state is empty", async () => {
+ const { client, evaluate } = createClient(evaluation);
+
+ await expect(
+ executeDecisionModelEvaluator({
+ variables: [{ var: "question", value: null }],
+ questions,
+ client,
+ }),
+ ).rejects.toBeInstanceOf(DecisionModelEvaluatorError);
+ expect(evaluate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [
+ "a missing answer",
+ { ...evaluation, answers: { ...evaluation.answers, refund: undefined } },
+ ],
+ [
+ "a wrongly typed answer",
+ {
+ ...evaluation,
+ answers: {
+ ...evaluation.answers,
+ refund: { type: "score", score: 1, probabilities: {}, confidence: 1 },
+ },
+ },
+ ],
+ [
+ "a choice outside the options",
+ {
+ ...evaluation,
+ answers: {
+ ...evaluation.answers,
+ readiness: {
+ type: "choice",
+ choice: "constructor",
+ probabilities: { constructor: 1 },
+ confidence: 1,
+ },
+ },
+ },
+ ],
+ ] as const)("fails permanently on %s", async (_label, broken) => {
+ const { client } = createClient(broken as DecisionModelEvaluation);
+
+ await expect(
+ executeDecisionModelEvaluator({
+ variables: [{ var: "question", value: "refund?" }],
+ questions,
+ client,
+ }),
+ ).rejects.toBeInstanceOf(DecisionModelEvaluatorError);
+ });
+});
diff --git a/packages/shared/src/server/evals/decisionModelEvaluatorExecution.ts b/packages/shared/src/server/evals/decisionModelEvaluatorExecution.ts
new file mode 100644
index 0000000000..7bf4dcdf37
--- /dev/null
+++ b/packages/shared/src/server/evals/decisionModelEvaluatorExecution.ts
@@ -0,0 +1,366 @@
+import { ScoreDataTypeEnum } from "../../domain/scores";
+import {
+ DecisionModelQuestionType,
+ type DecisionModelEntry,
+ type DecisionModelQuestion,
+ type DecisionModelQuestions,
+} from "../../features/evals/decisionModel";
+import type { EvalExecutionContext } from "../../features/evals/evalExecutionMetadata";
+import { stringifyValue } from "../../utils/stringChecks";
+import {
+ INTERNAL_TRACE_EVENT_SOURCE,
+ type InternalTraceEventInput,
+} from "../llm/internalTraceEvents";
+import {
+ LangfuseInternalTraceEnvironment,
+ type InternalTraceWriteInput,
+} from "../llm/types";
+import type { CodeEvalScoreWithName } from "./codeEvalDispatcherTypes";
+import type { ExtractedVariable } from "./extractObservationVariables";
+
+export type DecisionModelRequestQuestion =
+ | {
+ type: "choice";
+ instructions: DecisionModelEntry;
+ criteria: Record<string, DecisionModelEntry | null>;
+ }
+ | {
+ type: "score";
+ instructions: DecisionModelEntry;
+ criteria: DecisionModelEntry[];
+ }
+ | {
+ type: "boolean";
+ instructions: DecisionModelEntry;
+ criteria?: {
+ true?: DecisionModelEntry | null;
+ false?: DecisionModelEntry | null;
+ };
+ };
+
+export type DecisionModelRequest = {
+ state: Record<string, unknown>;
+ questions: Record<string, DecisionModelRequestQuestion>;
+};
+
+export type DecisionModelAnswer =
+ | {
+ type: "choice";
+ choice: string;
+ probabilities: Record<string, number>;
+ confidence: number | null;
+ }
+ | {
+ type: "score";
+ score: number;
+ probabilities: Record<string, number>;
+ confidence: number | null;
+ }
+ | {
+ type: "boolean";
+ probability: number;
+ };
+
+export type DecisionModelEvaluation = {
+ model: string;
+ answers: Record<string, DecisionModelAnswer>;
+ usage: { inputTokens: number | null; outputTokens: number | null } | null;
+};
+
+export type DecisionModelClient = {
+ evaluate: (request: DecisionModelRequest) => Promise<DecisionModelEvaluation>;
+};
+
+export class DecisionModelEvaluatorError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "DecisionModelEvaluatorError";
+ }
+}
+
+export function buildDecisionModelState(
+ variables: ExtractedVariable[],
+): Record<string, unknown> {
+ const state: Record<string, unknown> = {};
+ for (const variable of variables) {
+ if (variable.value === null || variable.value === undefined) continue;
+ state[variable.var] = variable.value;
+ }
+ return state;
+}
+
+export function toDecisionModelRequestQuestion(
+ question: DecisionModelQuestion,
+): DecisionModelRequestQuestion {
+ switch (question.type) {
+ case DecisionModelQuestionType.CHOICE:
+ return {
+ type: "choice",
+ instructions: question.instructions,
+ criteria: Object.fromEntries(
+ question.options.map((option) => [
+ option.value,
+ option.description ?? null,
+ ]),
+ ),
+ };
+ case DecisionModelQuestionType.SCORE:
+ return {
+ type: "score",
+ instructions: question.instructions,
+ criteria: question.levels.map((level) => level.description),
+ };
+ case DecisionModelQuestionType.NOUL:
+ return {
+ type: "boolean",
+ instructions: question.instructions,
+ ...(question.criteria
+ ? {
+ criteria: {
+ true: question.criteria.true ?? null,
+ false: question.criteria.false ?? null,
+ },
+ }
+ : {}),
+ };
+ }
+}
+
+export function buildDecisionModelRequest(params: {
+ variables: ExtractedVariable[];
+ questions: DecisionModelQuestions;
+}): DecisionModelRequest {
+ const state = buildDecisionModelState(params.variables);
+ if (Object.keys(state).length === 0) {
+ throw new DecisionModelEvaluatorError(
+ "Decision-model state is empty: none of the mapped fields exist on this observation",
+ );
+ }
+ return {
+ state,
+ questions: Object.fromEntries(
+ params.questions.map((question) => [
+ question.id,
+ toDecisionModelRequestQuestion(question),
+ ]),
+ ),
+ };
+}
+
+function formatNumber(value: number) {
+ return value.toFixed(2);
+}
+
+function rankedEntries(probabilities: Record<string, number>) {
+ return Object.entries(probabilities).sort(([, a], [, b]) => b - a);
+}
+
+export function formatDecisionModelComment(params: {
+ question: DecisionModelQuestion;
+ answer: DecisionModelAnswer;
+}): string {
+ const { question, answer } = params;
+ const parts: string[] = [];
+ if (answer.type === "choice") {
+ const winner = answer.probabilities[answer.choice];
+ parts.push(
+ winner === undefined
+ ? answer.choice
+ : `${answer.choice} (p=${formatNumber(winner)})`,
+ );
+ if (answer.confidence !== null) {
+ parts.push(`confidence ${formatNumber(answer.confidence)}`);
+ }
+ const runnerUp = rankedEntries(answer.probabilities).find(
+ ([option]) => option !== answer.choice,
+ );
+ if (runnerUp) {
+ parts.push(`runner-up ${runnerUp[0]} (${formatNumber(runnerUp[1])})`);
+ }
+ } else if (answer.type === "score") {
+ const nearestLevel = Math.min(
+ Math.max(Math.round(answer.score), 0),
+ question.type === DecisionModelQuestionType.SCORE
+ ? question.levels.length - 1
+ : 0,
+ );
+ const levelDescription =
+ question.type === DecisionModelQuestionType.SCORE
+ ? question.levels[nearestLevel]?.description
+ : undefined;
+ parts.push(
+ typeof levelDescription === "string"
+ ? `${formatNumber(answer.score)} ≈ level ${nearestLevel} "${levelDescription}"`
+ : `${formatNumber(answer.score)} ≈ level ${nearestLevel}`,
+ );
+ if (answer.confidence !== null) {
+ parts.push(`confidence ${formatNumber(answer.confidence)}`);
+ }
+ } else {
+ parts.push(`P(true)=${formatNumber(answer.probability)}`);
+ }
+ return parts.join("; ");
+}
+
+function toScoreMetadata(params: {
+ question: DecisionModelQuestion;
+ answer: DecisionModelAnswer;
+ model: string;
+}): Record<string, unknown> {
+ const { question, answer, model } = params;
+ const base = { questionId: question.id, type: question.type, model };
+ switch (answer.type) {
+ case "choice":
+ return {
+ typesafe: {
+ ...base,
+ choice: answer.choice,
+ confidence: answer.confidence,
+ probabilities: answer.probabilities,
+ },
+ };
+ case "score":
+ return {
+ typesafe: {
+ ...base,
+ confidence: answer.confidence,
+ probabilities: answer.probabilities,
+ legend:
+ question.type === DecisionModelQuestionType.SCORE
+ ? Object.fromEntries(
+ question.levels.map((level, index) => [
+ String(index),
+ level.description,
+ ]),
+ )
+ : undefined,
+ },
+ };
+ case "boolean":
+ return { typesafe: base };
+ }
+}
+
+function expectedAnswerType(
+ question: DecisionModelQuestion,
+): DecisionModelAnswer["type"] {
+ return question.type === DecisionModelQuestionType.NOUL
+ ? "boolean"
+ : question.type;
+}
+
+export function mapDecisionModelAnswersToScores(params: {
+ questions: DecisionModelQuestions;
+ evaluation: DecisionModelEvaluation;
+}): CodeEvalScoreWithName[] {
+ const { questions, evaluation } = params;
+
+ return questions.map((question) => {
+ const answer = evaluation.answers[question.id];
+ if (!answer) {
+ throw new DecisionModelEvaluatorError(
+ `Decision model returned no answer for question "${question.scoreName}"`,
+ );
+ }
+ if (answer.type !== expectedAnswerType(question)) {
+ throw new DecisionModelEvaluatorError(
+ `Decision model returned a ${answer.type} answer for the ${question.type} question "${question.scoreName}"`,
+ );
+ }
+
+ const common = {
+ name: question.scoreName,
+ comment: formatDecisionModelComment({ question, answer }),
+ metadata: toScoreMetadata({ question, answer, model: evaluation.model }),
+ };
+
+ switch (answer.type) {
+ case "choice": {
+ if (
+ question.type !== DecisionModelQuestionType.CHOICE ||
+ !question.options.some((option) => option.value === answer.choice)
+ ) {
+ throw new DecisionModelEvaluatorError(
+ `Decision model returned "${answer.choice}", which is not an option of question "${question.scoreName}"`,
+ );
+ }
+ return {
+ ...common,
+ dataType: ScoreDataTypeEnum.CATEGORICAL,
+ value: answer.choice,
+ };
+ }
+ case "score":
+ return {
+ ...common,
+ dataType: ScoreDataTypeEnum.NUMERIC,
+ value: answer.score,
+ };
+ case "boolean":
+ return {
+ ...common,
+ dataType: ScoreDataTypeEnum.NUMERIC,
+ value: answer.probability,
+ };
+ }
+ });
+}
+
+export async function executeDecisionModelEvaluator(params: {
+ variables: ExtractedVariable[];
+ questions: DecisionModelQuestions;
+ client: DecisionModelClient;
+}) {
+ const request = buildDecisionModelRequest(params);
+ const evaluation = await params.client.evaluate(request);
+ const scores = mapDecisionModelAnswersToScores({
+ questions: params.questions,
+ evaluation,
+ });
+ return { request, evaluation, scores };
+}
+
+export function buildDecisionModelTraceInput(params: {
+ projectId: string;
+ executionTraceId: string;
+ traceStartTime: Date;
+ traceName: string;
+ request: DecisionModelRequest;
+ evaluation: DecisionModelEvaluation;
+ metadata: Record<string, unknown>;
+ evaluationContext?: EvalExecutionContext;
+}): InternalTraceWriteInput {
+ const usage = params.evaluation.usage;
+ const eventInput: InternalTraceEventInput = {
+ projectId: params.projectId,
+ traceId: params.executionTraceId,
+ spanId: params.executionTraceId,
+ startTimeISO: params.traceStartTime.toISOString(),
+ endTimeISO: new Date().toISOString(),
+ name: params.traceName,
+ traceName: params.traceName,
+ type: "GENERATION",
+ environment: LangfuseInternalTraceEnvironment.LLMJudge,
+ modelName: params.evaluation.model,
+ input: stringifyValue(params.request),
+ output: stringifyValue(params.evaluation.answers),
+ ...(usage
+ ? {
+ providedUsageDetails: {
+ ...(usage.inputTokens !== null ? { input: usage.inputTokens } : {}),
+ ...(usage.outputTokens !== null
+ ? { output: usage.outputTokens }
+ : {}),
+ },
+ }
+ : {}),
+ metadata: params.metadata,
+ evaluationContext: params.evaluationContext,
+ source: INTERNAL_TRACE_EVENT_SOURCE,
+ };
+
+ return {
+ rootSpanId: params.executionTraceId,
+ eventInputs: [eventInput],
+ };
+}
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index bea12ab5a9..6ecd44753e 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -38,6 +38,8 @@ export * from "./evals/evalScoreIds";
export * from "./evals/extractObservationVariables";
export * from "./evals/classifyEvaluatorLlmError";
export * from "./evals/llmEvaluatorExecution";
+export * from "./evals/decisionModelEvaluatorExecution";
+export * from "./llm/typesafe/typeSafeDecisionModelClient";
export * from "./utils/traceId";
export * from "./auth/apiKeyCache";
export * from "./auth/apiKeys";
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/index.ts b/packages/shared/src/server/llm/ai-sdk/providers/index.ts
index 498308c39c..fc49c60e10 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/index.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/index.ts
@@ -118,6 +118,11 @@ export async function buildAiSdkModel(params: {
),
});
+ case LLMAdapter.TypeSafe:
+ throw new Error(
+ "TypeSafe decision models cannot generate text; use a decision-model evaluator",
+ );
+
default: {
const _exhaustiveCheck: never = model.adapter;
throw new Error(`AI SDK adapter is not supported: ${_exhaustiveCheck}`);
diff --git a/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts b/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts
index f52081812b..35bdb60b90 100644
--- a/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts
+++ b/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts
@@ -99,6 +99,13 @@ export function resolveAiSdkModelConfig(params: {
case LLMAdapter.GoogleAIStudio:
return { adapter: model.adapter };
+ case LLMAdapter.TypeSafe:
+ throw new LLMValidationError({
+ code: "invalid-request",
+ message:
+ "TypeSafe decision models cannot generate text; use a decision-model evaluator",
+ });
+
default: {
const _exhaustiveCheck: never = model.adapter;
throw new Error(`Unsupported LLM adapter: ${_exhaustiveCheck}`);
diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.ts
index bd6f6afe8a..69addfa5bc 100644
--- a/packages/shared/src/server/llm/llmText.ts
+++ b/packages/shared/src/server/llm/llmText.ts
@@ -673,6 +673,12 @@ function translateLegacyProviderOptions(params: {
});
break;
}
+ case LLMAdapter.TypeSafe:
+ throw new LLMValidationError({
+ code: "invalid-request",
+ message:
+ "TypeSafe decision models cannot generate text; use a decision-model evaluator",
+ });
default: {
const _exhaustiveCheck: never = modelParams.adapter;
throw new LLMValidationError({
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index bc1a12ccf7..10468d1c0c 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -251,6 +251,15 @@ export enum LLMAdapter {
Bedrock = "bedrock",
VertexAI = "google-vertex-ai",
GoogleAIStudio = "google-ai-studio",
+ TypeSafe = "typesafe",
+}
+
+export const DECISION_MODEL_ADAPTERS: readonly LLMAdapter[] = [
+ LLMAdapter.TypeSafe,
+];
+
+export function isDecisionModelAdapter(adapter: string): boolean {
+ return DECISION_MODEL_ADAPTERS.includes(adapter as LLMAdapter);
}
// Some providers require at least one user message. The persisted-message
@@ -460,6 +469,8 @@ export const googleAIStudioModels = [
"gemini-1.5-flash-8b",
] as const;
+export const typeSafeModels = ["jev-1.13.0", "jev-latest"] as const;
+
export type AnthropicModel = (typeof anthropicModels)[number];
export type VertexAIModel = (typeof vertexAIModels)[number];
export const supportedModels = {
@@ -469,6 +480,7 @@ export const supportedModels = {
[LLMAdapter.GoogleAIStudio]: googleAIStudioModels,
[LLMAdapter.Azure]: [],
[LLMAdapter.Bedrock]: [],
+ [LLMAdapter.TypeSafe]: typeSafeModels,
} as const;
export type LLMFunctionCall = {
diff --git a/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.test.ts b/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.test.ts
new file mode 100644
index 0000000000..c2bf65026f
--- /dev/null
+++ b/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from "vitest";
+import type { DecisionModelRequest } from "../../evals/decisionModelEvaluatorExecution";
+import { createTypeSafeDecisionModelClient } from "./typeSafeDecisionModelClient";
+
+function jsonResponse(body: unknown, status = 200) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+const request: DecisionModelRequest = {
+ state: { question: "Can I get a refund?", reply: "Yes." },
+ questions: {
+ readiness: {
+ type: "choice",
+ instructions: "Is `reply` ready to send?",
+ criteria: { ready: null, needs_revision: null },
+ },
+ frustration: {
+ type: "score",
+ instructions: "How frustrated is the customer?",
+ criteria: ["Calm", "Frustrated", "Angry"],
+ },
+ refund: {
+ type: "boolean",
+ instructions: "Does `question` request a refund?",
+ },
+ },
+};
+
+describe("createTypeSafeDecisionModelClient", () => {
+ it("posts all questions in one call and maps every answer type back", async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse({
+ model: "jev-1.13.0",
+ answers: {
+ readiness: {
+ type: "choice",
+ choice: "ready",
+ confidence: 0.82,
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ },
+ frustration: {
+ type: "score",
+ score: 1.26,
+ confidence: 0.61,
+ legend: { "0": "Calm", "1": "Frustrated", "2": "Angry" },
+ probabilities: { "0": 0, "1": 0.74, "2": 0.26 },
+ },
+ refund: { type: "noul", noul: 0.97 },
+ },
+ usage: { input_tokens: 300, output_tokens: 9 },
+ }),
+ );
+
+ const client = createTypeSafeDecisionModelClient({
+ apiKey: "sk-test",
+ model: "jev-latest",
+ fetchImpl,
+ });
+ const evaluation = await client.evaluate(request);
+
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("https://api.typesafe.ai/v1/systemone");
+ expect(new Headers(init.headers).get("authorization")).toBe(
+ "Bearer sk-test",
+ );
+ // The SDK sends TypeSafe's native `noul` type for boolean questions.
+ expect(JSON.parse(init.body as string)).toEqual({
+ model: "jev-latest",
+ state: request.state,
+ questions: {
+ readiness: request.questions.readiness,
+ frustration: request.questions.frustration,
+ refund: { ...request.questions.refund, type: "noul" },
+ },
+ });
+
+ expect(evaluation).toEqual({
+ model: "jev-1.13.0",
+ answers: {
+ readiness: {
+ type: "choice",
+ choice: "ready",
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ confidence: 0.82,
+ },
+ frustration: {
+ type: "score",
+ score: 1.26,
+ probabilities: { "0": 0, "1": 0.74, "2": 0.26 },
+ confidence: 0.61,
+ },
+ refund: { type: "boolean", probability: 0.97 },
+ },
+ usage: { inputTokens: 300, outputTokens: 9 },
+ });
+ });
+
+ it("surfaces API failures as AI SDK call errors with the status code", async () => {
+ const fetchImpl = vi
+ .fn()
+ .mockResolvedValue(jsonResponse({ message: "invalid api key" }, 401));
+
+ const client = createTypeSafeDecisionModelClient({
+ apiKey: "sk-bad",
+ model: "jev-latest",
+ fetchImpl,
+ });
+
+ await expect(client.evaluate(request)).rejects.toMatchObject({
+ name: "AI_APICallError",
+ statusCode: 401,
+ isRetryable: false,
+ });
+ });
+});
diff --git a/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.ts b/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.ts
new file mode 100644
index 0000000000..1d9f750649
--- /dev/null
+++ b/packages/shared/src/server/llm/typesafe/typeSafeDecisionModelClient.ts
@@ -0,0 +1,93 @@
+import { createTypeSafeAi } from "@ai-sdk/typesafe-ai";
+import {
+ experimental_evaluate as evaluate,
+ type Experimental_EvaluationQuestion as EvaluationQuestion,
+ type JSONValue,
+} from "ai";
+import type {
+ DecisionModelAnswer,
+ DecisionModelClient,
+ DecisionModelEvaluation,
+} from "../../evals/decisionModelEvaluatorExecution";
+import { createSecureLlmFetch } from "../secureLlmFetch";
+
+export function createTypeSafeDecisionModelClient(params: {
+ apiKey: string;
+ model: string;
+ fetchImpl?: typeof fetch;
+}): DecisionModelClient {
+ const provider = createTypeSafeAi({
+ apiKey: params.apiKey,
+ fetch:
+ params.fetchImpl ??
+ createSecureLlmFetch({ logContext: "TypeSafe decision model" }),
+ });
+ const model = provider.evaluationModel(params.model);
+
+ return {
+ evaluate: async (request) => {
+ const result = await evaluate({
+ model,
+ state: request.state as Record<string, JSONValue>,
+ questions: request.questions as Record<string, EvaluationQuestion>,
+ maxRetries: 1,
+ });
+
+ const confidenceById = readConfidence(result.providerMetadata);
+
+ const answers: Record<string, DecisionModelAnswer> = {};
+ for (const [id, answer] of Object.entries(result.answers)) {
+ const confidence = confidenceById[id] ?? null;
+ switch (answer.type) {
+ case "choice":
+ answers[id] = {
+ type: "choice",
+ choice: answer.choice,
+ probabilities: answer.probabilities ?? { [answer.choice]: 1 },
+ confidence,
+ };
+ break;
+ case "score":
+ answers[id] = {
+ type: "score",
+ score: answer.score,
+ probabilities: answer.probabilities ?? {},
+ confidence,
+ };
+ break;
+ case "boolean":
+ answers[id] = { type: "boolean", probability: answer.probability };
+ break;
+ }
+ }
+
+ const evaluation: DecisionModelEvaluation = {
+ model: result.response.modelId,
+ answers,
+ usage: {
+ inputTokens: result.usage.inputTokens ?? null,
+ outputTokens: result.usage.outputTokens ?? null,
+ },
+ };
+ return evaluation;
+ },
+ };
+}
+
+function readConfidence(providerMetadata: unknown): Record<string, number> {
+ if (typeof providerMetadata !== "object" || providerMetadata === null) {
+ return {};
+ }
+ const typesafe = (providerMetadata as Record<string, unknown>).typesafe;
+ if (typeof typesafe !== "object" || typesafe === null) return {};
+ const confidence = (typesafe as Record<string, unknown>).confidence;
+ if (typeof confidence !== "object" || confidence === null) return {};
+ return Object.fromEntries(
+ Object.entries(confidence as Record<string, unknown>).flatMap(
+ ([id, value]) =>
+ typeof value === "number" && value >= 0 && value <= 1
+ ? [[id, value]]
+ : [],
+ ),
+ );
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a4586784f5..89c4a6eb80 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -300,6 +300,9 @@ importers:
'@ai-sdk/openai-compatible':
specifier: ^3.0.3
version: 3.0.3([email protected])
+ '@ai-sdk/typesafe-ai':
+ specifier: ^3.0.4
+ version: 3.0.4([email protected])
'@aws-sdk/client-cloudwatch':
specifier: 'catalog:'
version: 3.1074.0
@@ -365,7 +368,7 @@ importers:
version: 2.4.6
ai:
specifier: ^7.0.0
- version: 7.0.8([email protected])
+ version: 7.0.107([email protected])
ajv:
specifier: ^8.18.0
version: 8.20.0
@@ -1371,8 +1374,8 @@ packages:
peerDependencies:
zod: 4.3.6
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-8GjssUxXeTd8tst2fYXNOFbtNNZFv3sG7aq7wKnQYrU2eB3JFR7np6o4F3Snp/fy/rJZSeH28LvjSWq5wkdL8Q==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-6wJmX/D5OO7tvDJbtFdXdBuRt8AkCnW+FLK+W35UHe/tHgolAa4hclXtJcMSYnlTDy/t5DNRgdesVaoMXtwzow==}
engines: {node: '>=22'}
peerDependencies:
zod: 4.3.6
@@ -1461,14 +1464,14 @@ packages:
peerDependencies:
zod: 4.3.6
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-EcmdjJb7yggsZPCbS3MFBpvAUnKaPW+QvanU5GzF00XCq0bqqAmvJ3MN19ejlmOETbW8sJNiq6qam48wTcbUNw==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-El0JOXXGcHFe6+owJ1UV0VgB9XtdivP8vcZni+rUIt6lt+cBHCnUdddaA6LE2avJGJ5AD0uXSY+uAvRL2tSvgw==}
engines: {node: '>=22'}
peerDependencies:
zod: 4.3.6
- '@ai-sdk/[email protected]':
- resolution: {integrity: sha512-El0JOXXGcHFe6+owJ1UV0VgB9XtdivP8vcZni+rUIt6lt+cBHCnUdddaA6LE2avJGJ5AD0uXSY+uAvRL2tSvgw==}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-gLuaCups8OCIRz3eO6WWz5op7VLYNNtFzyH0sWUr0FE9v7cTxR0qxDpQdrKnGcql+9WWttobjnZsJVsuEbsPQQ==}
engines: {node: '>=22'}
peerDependencies:
zod: 4.3.6
@@ -1505,10 +1508,20 @@ packages:
resolution: {integrity: sha512-6p3C/vGqVIjcptBu1DnVd/BZJ2wWmV9TUv9192vT6ZvT9KNED8EwRTqyqFpoQZKgSbMDSvBSq3dqR524Nt/Crw==}
engines: {node: '>=22'}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-VYMBxIQdcHqbIf1j+YZlI9Ati6LZ4wJe0GGd4z4a5H/KxTggjeOiyaVYTnfF7LHZK5jMQ+rofmzz4QPqf++NUw==}
+ engines: {node: '>=22'}
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-e0CpNWJUY7OxAFAnCZkw+ri9QOHWwTs1tXP42782KFGCU07qt8NiXCrCVowyCB5dP2r5/Uls+g2oPd8kOJn9dw==}
engines: {node: '>=22'}
+ '@ai-sdk/[email protected]':
+ resolution: {integrity: sha512-LQvqtf6cVla5iyH/LYs9rvl63NDWRRqggz9ilGNmjixhi5TuONAWo+SC6+xT46izn/bpyx9hmXNdMLg3ZSSW0A==}
+ engines: {node: '>=22'}
+ peerDependencies:
+ zod: 4.3.6
+
'@ai-sdk/[email protected]':
resolution: {integrity: sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==}
engines: {node: '>=18'}
@@ -7325,8 +7338,8 @@ packages:
peerDependencies:
zod: 4.3.6
- resolution: {integrity: sha512-vTEKl6fDBZ2IxBXTRaZOajf9W2Ev57Ju8iKtUvqlmDk8Z9BrEP4c22SWJsg1RcWHSFmJMSBa/s5dlUBHUq3YwA==}
+ resolution: {integrity: sha512-PVYQ3W9kR8oYiGQxbg4aFIlhQzKskZm8UV+4E0zB2uKOzFr8ju3bXQncOOZtLsOgJY8vdpgyu3cXtomsfcdQYg==}
engines: {node: '>=22'}
peerDependencies:
zod: 4.3.6
@@ -12854,10 +12867,10 @@ snapshots:
'@vercel/oidc': 3.2.0
zod: 4.3.6
dependencies:
- '@ai-sdk/provider': 4.0.1
- '@ai-sdk/provider-utils': 5.0.2([email protected])
+ '@ai-sdk/provider': 4.0.17
+ '@ai-sdk/provider-utils': 5.0.45([email protected])
'@vercel/oidc': 3.2.0
zod: 4.3.6
@@ -12964,7 +12977,7 @@ snapshots:
eventsource-parser: 3.1.0
zod: 4.3.6
dependencies:
'@ai-sdk/provider': 4.0.1
'@standard-schema/spec': 1.1.0
@@ -12972,12 +12985,13 @@ snapshots:
eventsource-parser: 3.1.0
zod: 4.3.6
dependencies:
- '@ai-sdk/provider': 4.0.1
+ '@ai-sdk/provider': 4.0.17
'@standard-schema/spec': 1.1.0
'@workflow/serde': 4.1.0
eventsource-parser: 3.1.0
+ undici: 7.29.1
zod: 4.3.6
'@ai-sdk/[email protected]':
@@ -13012,10 +13026,20 @@ snapshots:
dependencies:
json-schema: 0.4.0
+ '@ai-sdk/[email protected]':
+ dependencies:
+ json-schema: 0.4.0
+
'@ai-sdk/[email protected]':
dependencies:
json-schema: 0.4.0
+ dependencies:
+ '@ai-sdk/provider': 4.0.17
+ '@ai-sdk/provider-utils': 5.0.45([email protected])
+ zod: 4.3.6
+
dependencies:
'@ai-sdk/provider': 1.1.3
@@ -19218,11 +19242,11 @@ snapshots:
'@opentelemetry/api': 1.9.1
zod: 4.3.6
dependencies:
- '@ai-sdk/gateway': 4.0.6([email protected])
- '@ai-sdk/provider': 4.0.1
- '@ai-sdk/provider-utils': 5.0.2([email protected])
+ '@ai-sdk/gateway': 4.0.87([email protected])
+ '@ai-sdk/provider': 4.0.17
+ '@ai-sdk/provider-utils': 5.0.45([email protected])
zod: 4.3.6
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 59b3ee1209..b7e4a84ea6 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -158,3 +158,8 @@ minimumReleaseAgeExclude:
# User impersonation via trusted-proxy confusion (CVE-2026-90711); 2.0.8 is
# the only patched release, pulled in transitively through express.
+ - "@ai-sdk/[email protected]"
+ - "@ai-sdk/[email protected]"
+ - "@ai-sdk/[email protected]"
+ - "@ai-sdk/[email protected]"
diff --git a/web/src/__tests__/server/evaluator-v2-service.servertest.ts b/web/src/__tests__/server/evaluator-v2-service.servertest.ts
index b003970824..0fa9e8d5b1 100644
--- a/web/src/__tests__/server/evaluator-v2-service.servertest.ts
+++ b/web/src/__tests__/server/evaluator-v2-service.servertest.ts
@@ -393,6 +393,64 @@ describe("EvaluatorService", () => {
);
});
+ it("persists the state mapping and typed questions of a decision-model evaluator", async () => {
+ const questions = [
+ {
+ id: "readiness",
+ scoreName: "send_readiness",
+ type: "choice" as const,
+ instructions: "Is `reply` ready to send as an answer to `question`?",
+ options: [{ value: "ready" }, { value: "needs_revision" }],
+ },
+ {
+ id: "refund",
+ scoreName: "refund_requested",
+ type: "noul" as const,
+ instructions: "Does `question` request a refund?",
+ },
+ ];
+ const variableMapping = [
+ {
+ templateVariable: "question",
+ selectedColumnId: "input",
+ jsonSelector: "$.messages[-1].content",
+ },
+ {
+ templateVariable: "reply",
+ selectedColumnId: "output",
+ jsonSelector: null,
+ },
+ ];
+
+ const created = await createService().create(
+ {
+ projectId,
+ name: "Send readiness",
+ description: null,
+ definition: {
+ type: "DECISION_MODEL",
+ questions,
+ provider: "typesafe",
+ model: "jev-1.13.0",
+ vars: ["question", "reply"],
+ variableMapping,
+ },
+ },
+ null,
+ );
+
+ expect(created.type).toBe("DECISION_MODEL");
+ expect(created.versions[0]).toMatchObject({
+ provider: "typesafe",
+ model: "jev-1.13.0",
+ vars: ["question", "reply"],
+ variableMapping,
+ questions,
+ promptMessages: null,
+ outputDefinition: null,
+ });
+ });
+
it("returns the filter from the first assigned rule", async () => {
const service = createService();
const created = await service.create(llmInput("Assigned evaluator"), null);
diff --git a/web/src/features/evals/components/template-form.tsx b/web/src/features/evals/components/template-form.tsx
index 636f5ff744..5ab71dce27 100644
--- a/web/src/features/evals/components/template-form.tsx
+++ b/web/src/features/evals/components/template-form.tsx
@@ -260,10 +260,13 @@ const InnerEvalTemplateForm = (props: {
defaultValues: {
name:
props.existingEvalTemplateName ?? props.preFilledFormValues?.name ?? "",
+ // The legacy editor only knows LLM and code templates.
type:
templateTypeSelectorMode === "code-only"
? EvalTemplateType.CODE
- : (props.preFilledFormValues?.type ?? EvalTemplateType.LLM_AS_JUDGE),
+ : props.preFilledFormValues?.type === EvalTemplateType.CODE
+ ? EvalTemplateType.CODE
+ : EvalTemplateType.LLM_AS_JUDGE,
prompt: props.preFilledFormValues?.prompt ?? undefined,
variables: props.preFilledFormValues?.vars ?? [],
sourceCode: props.preFilledFormValues?.sourceCode
diff --git a/web/src/features/evals/server/legacyCompatibilityService.ts b/web/src/features/evals/server/legacyCompatibilityService.ts
index b9a9c27f11..ce89a99a5f 100644
--- a/web/src/features/evals/server/legacyCompatibilityService.ts
+++ b/web/src/features/evals/server/legacyCompatibilityService.ts
@@ -254,14 +254,28 @@ function evaluatorVersionData(
const common = {
createdByUserId,
};
- return definition.type === EvalTemplateType.CODE
- ? {
+ switch (definition.type) {
+ case EvalTemplateType.CODE:
+ return {
...common,
variableMapping: getCodeEvalVariableMapping() as Prisma.InputJsonValue,
sourceCode: definition.sourceCode,
sourceCodeLanguage: definition.sourceCodeLanguage,
- }
- : {
+ };
+ case EvalTemplateType.DECISION_MODEL:
+ return {
+ ...common,
+ variableMapping:
+ definition.variableMapping === null
+ ? Prisma.DbNull
+ : (definition.variableMapping as Prisma.InputJsonValue),
+ provider: definition.provider,
+ model: definition.model,
+ vars: definition.vars,
+ questions: definition.questions as Prisma.InputJsonValue,
+ };
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return {
...common,
variableMapping:
definition.variableMapping === null
@@ -278,6 +292,7 @@ function evaluatorVersionData(
vars: definition.vars,
outputDefinition: definition.outputDefinition as Prisma.InputJsonValue,
};
+ }
}
/**
@@ -292,6 +307,17 @@ function definitionsMatch(a: EvaluatorDefinition, b: EvaluatorDefinition) {
a.sourceCodeLanguage === b.sourceCodeLanguage
);
}
+ if (
+ a.type === EvalTemplateType.DECISION_MODEL &&
+ b.type === EvalTemplateType.DECISION_MODEL
+ ) {
+ return (
+ isEqual(a.questions, b.questions) &&
+ a.provider === b.provider &&
+ a.model === b.model &&
+ isEqual([...a.vars].sort(), [...b.vars].sort())
+ );
+ }
if (
a.type === EvalTemplateType.LLM_AS_JUDGE &&
b.type === EvalTemplateType.LLM_AS_JUDGE
diff --git a/web/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard.tsx b/web/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard.tsx
index 9cb2497f5b..31a79366ef 100644
--- a/web/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard.tsx
+++ b/web/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard.tsx
@@ -6,6 +6,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/src/components/ui/collapsible";
+import { cn } from "@/src/utils/tailwind";
/** A framed disclosure with a consistent header surface and collapse affordance. */
export function CollapsibleCard({
@@ -14,6 +15,7 @@ export function CollapsibleCard({
disabled,
triggerTitle,
header,
+ headerInteractive = true,
actions,
children,
}: {
@@ -22,25 +24,41 @@ export function CollapsibleCard({
disabled: boolean;
triggerTitle: string;
header: ReactNode;
+ headerInteractive?: boolean;
actions: ReactNode;
children: ReactNode;
}) {
+ const headerContent = (
+ <>
+ <ChevronDown
+ className={cn(
+ "text-muted-foreground h-3.5 w-3.5 shrink-0 transition-transform",
+ open ? "rotate-0" : "-rotate-90",
+ )}
+ />
+ <span className="flex min-w-0 flex-1 items-baseline gap-2">{header}</span>
+ </>
+ );
+
return (
<Collapsible open={open} onOpenChange={onOpenChange} disabled={disabled}>
<div className="bg-card text-card-foreground overflow-hidden rounded-md border">
<div className="bg-secondary text-secondary-foreground flex min-h-9 min-w-0 items-center text-sm">
- <CollapsibleTrigger asChild>
- <button
- type="button"
- className="group hover:bg-accent hover:text-accent-foreground disabled:hover:bg-secondary disabled:hover:text-secondary-foreground flex min-h-9 min-w-0 flex-1 items-center gap-2 px-3 py-1.5 text-left disabled:cursor-not-allowed disabled:opacity-50"
- title={triggerTitle}
- >
- <ChevronDown className="text-muted-foreground h-3.5 w-3.5 shrink-0 -rotate-90 transition-transform group-data-[state=open]:rotate-0" />
- <span className="flex min-w-0 flex-1 items-baseline gap-2">
- {header}
- </span>
- </button>
- </CollapsibleTrigger>
+ {headerInteractive ? (
+ <CollapsibleTrigger asChild>
+ <button
+ type="button"
+ className="hover:bg-accent hover:text-accent-foreground disabled:hover:bg-secondary disabled:hover:text-secondary-foreground flex min-h-9 min-w-0 flex-1 items-center gap-2 px-3 py-1.5 text-left disabled:cursor-not-allowed disabled:opacity-50"
+ title={triggerTitle}
+ >
+ {headerContent}
+ </button>
+ </CollapsibleTrigger>
+ ) : (
+ <div className="flex min-h-9 min-w-0 flex-1 items-center gap-2 px-3 py-1.5">
+ {headerContent}
+ </div>
+ )}
{actions}
</div>
<CollapsibleContent>
diff --git a/web/src/features/evals/v2/components/EvaluatorGalleryView/components/EvaluatorGalleryMethodBadge/EvaluatorGalleryMethodBadge.tsx b/web/src/features/evals/v2/components/EvaluatorGalleryView/components/EvaluatorGalleryMethodBadge/EvaluatorGalleryMethodBadge.tsx
index 1d5d4cad99..60074c07fc 100644
--- a/web/src/features/evals/v2/components/EvaluatorGalleryView/components/EvaluatorGalleryMethodBadge/EvaluatorGalleryMethodBadge.tsx
+++ b/web/src/features/evals/v2/components/EvaluatorGalleryView/components/EvaluatorGalleryMethodBadge/EvaluatorGalleryMethodBadge.tsx
@@ -1,18 +1,26 @@
-import { Code2, Sparkles } from "lucide-react";
+import { Code2, Scale, Sparkles } from "lucide-react";
import { EvalTemplateTypeEnum, type EvalTemplateType } from "@langfuse/shared";
+const METHOD_BADGES = {
+ [EvalTemplateTypeEnum.CODE]: { Icon: Code2, label: "Code" },
+ [EvalTemplateTypeEnum.LLM_AS_JUDGE]: { Icon: Sparkles, label: "LLM judge" },
+ [EvalTemplateTypeEnum.DECISION_MODEL]: {
+ Icon: Scale,
+ label: "Decision model",
+ },
+} as const satisfies Record<EvalTemplateType, unknown>;
+
export function EvaluatorGalleryMethodBadge({
type,
}: {
type: EvalTemplateType;
}) {
- const isCode = type === EvalTemplateTypeEnum.CODE;
- const Icon = isCode ? Code2 : Sparkles;
+ const { Icon, label } = METHOD_BADGES[type];
return (
<span className="bg-muted text-muted-foreground inline-flex h-5 shrink-0 items-center gap-1 rounded-full px-2 text-xs leading-none">
<Icon className="size-3" />
- {isCode ? "Code" : "LLM judge"}
+ {label}
</span>
);
}
diff --git a/web/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestSectionContainer/TestSectionContainer.tsx b/web/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestSectionContainer/TestSectionContainer.tsx
index 3889c87092..b1ab135cb7 100644
--- a/web/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestSectionContainer/TestSectionContainer.tsx
+++ b/web/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestSectionContainer/TestSectionContainer.tsx
@@ -1,6 +1,10 @@
+import type { EvalTemplateType } from "@langfuse/shared";
import { useStore } from "zustand";
-import { TestResultPanelView } from "@/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView";
+import {
+ TestResultPanelView,
+ type TestResultPanelTitle,
+} from "@/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView";
import { TestSection } from "@/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/TestSection";
import { TestRerunAction } from "@/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestRerunAction/TestRerunAction";
import { TestResultActions } from "@/src/features/evals/v2/components/EvaluatorTestPanel/components/TestSection/components/TestResultActions/TestResultActions";
@@ -8,6 +12,12 @@ import { TestRunCard } from "@/src/features/evals/v2/components/EvaluatorTestPan
import { toTestResultPanelState } from "@/src/features/evals/v2/fns/evaluatorTesting/toTestResultPanelState";
import type { EvaluatorSetupStore } from "@/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore";
+const RESULT_TITLES: Record<EvalTemplateType, TestResultPanelTitle> = {
+ LLM_AS_JUDGE: "LLM Output",
+ CODE: "Code Output",
+ DECISION_MODEL: "Decision Model Output",
+};
+
export function TestSectionContainer({
projectId,
store,
@@ -52,7 +62,7 @@ export function TestSectionContainer({
/>
) : (
<TestResultPanelView
- title={type === "LLM_AS_JUDGE" ? "LLM Output" : "Code Output"}
+ title={RESULT_TITLES[type]}
result={toTestResultPanelState({
type,
isPending: testPending,
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.stories.tsx
new file mode 100644
index 0000000000..1d958b53b1
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.stories.tsx
@@ -0,0 +1,44 @@
+import { useState } from "react";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { ChoiceOptionsEditor } from "./ChoiceOptionsEditor";
+
+const meta = preview.meta({ component: ChoiceOptionsEditor });
+
+const OPTIONS = [
+ {
+ value: "ready",
+ description: "Answers the request and states the next step.",
+ },
+ { value: "needs_revision", description: "Accurate but incomplete." },
+ { value: "unsafe", description: "" },
+];
+
+export const Default = meta.story({
+ args: { options: OPTIONS, onChange: fn() },
+ render: (args) => {
+ const [options, setOptions] = useState(args.options);
+ return (
+ <ChoiceOptionsEditor
+ {...args}
+ options={options}
+ onChange={(next) => {
+ setOptions(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Error = meta.story({
+ args: {
+ options: [
+ { value: "yes", description: "" },
+ { value: "yes", description: "" },
+ ],
+ error: "Option labels must be unique.",
+ onChange: fn(),
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.tsx
new file mode 100644
index 0000000000..c2128ad73b
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor.tsx
@@ -0,0 +1,105 @@
+import { DECISION_MODEL_LIMITS } from "@langfuse/shared";
+import { Plus, Trash2 } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
+import { Input } from "@/src/components/ui/input";
+import { Label } from "@/src/components/ui/label";
+import { SortableList } from "@/src/features/evals/v2/components/SortableList/SortableList";
+import { moveItem } from "@/src/features/evals/v2/fns/moveItem";
+
+export type ChoiceOptionDraft = { value: string; description: string };
+
+/**
+ * Options of a Choice question, one row each with the label and its
+ * description side by side: descriptions sharpen the boundary between options,
+ * so they stay visible rather than behind a popover.
+ */
+export function ChoiceOptionsEditor({
+ options,
+ onChange,
+ error,
+}: {
+ options: ChoiceOptionDraft[];
+ onChange: (options: ChoiceOptionDraft[]) => void;
+ error?: string;
+}) {
+ const update = (index: number, next: Partial<ChoiceOptionDraft>) =>
+ onChange(
+ options.map((option, i) =>
+ i === index ? { ...option, ...next } : option,
+ ),
+ );
+ const remove = (index: number) =>
+ onChange(options.filter((_, i) => i !== index));
+ const canRemove = options.length > DECISION_MODEL_LIMITS.minChoiceOptions;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <Label className="flex items-center gap-1.5">
+ Options
+ <InfoTooltip label="About options">
+ One label per option. A short description sharpens the boundary
+ between options; add an “other” option when the list may not cover
+ every input.
+ </InfoTooltip>
+ <span className="text-muted-foreground text-xs font-normal">
+ {options.length} of {DECISION_MODEL_LIMITS.maxChoiceOptions}
+ </span>
+ </Label>
+ <SortableList
+ items={options}
+ getId={(_option, index) => `option-${index}`}
+ getLabel={(option, index) => option.value || `option ${index + 1}`}
+ onReorder={(from, to) => onChange(moveItem(options, from, to))}
+ renderItem={(option, index) => (
+ <div className="grid grid-cols-[minmax(8rem,1fr)_2fr_auto] items-center gap-2">
+ <Input
+ value={option.value}
+ onChange={(event) => update(index, { value: event.target.value })}
+ placeholder="label"
+ aria-label={`Option ${index + 1} label`}
+ className="font-mono"
+ />
+ <Input
+ value={option.description}
+ onChange={(event) =>
+ update(index, { description: event.target.value })
+ }
+ placeholder="What this option covers (optional)"
+ aria-label={`Option ${index + 1} description`}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="hover:text-destructive"
+ disabled={!canRemove}
+ onClick={() => remove(index)}
+ title={
+ canRemove
+ ? "Remove option"
+ : `Keep at least ${DECISION_MODEL_LIMITS.minChoiceOptions} options`
+ }
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ )}
+ />
+ <div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={options.length >= DECISION_MODEL_LIMITS.maxChoiceOptions}
+ onClick={() => onChange([...options, { value: "", description: "" }])}
+ >
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ Add option
+ </Button>
+ </div>
+ {error ? <p className="text-destructive text-xs">{error}</p> : null}
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.stories.tsx
new file mode 100644
index 0000000000..4c2668f463
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.stories.tsx
@@ -0,0 +1,131 @@
+import { useState } from "react";
+import { DecisionModelQuestionType } from "@langfuse/shared";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { QUESTION_EXAMPLES } from "../DecisionModelQuestionList/DecisionModelQuestionList";
+import { DecisionModelQuestionCard } from "./DecisionModelQuestionCard";
+
+const meta = preview.meta({ component: DecisionModelQuestionCard });
+
+const STATE_KEYS = ["input", "output"];
+
+const base = {
+ index: 0,
+ stateKeys: STATE_KEYS,
+ expanded: true,
+ onExpandedChange: fn(),
+ onChange: fn(),
+ onRemove: fn(),
+};
+
+export const Choice = meta.story({
+ args: {
+ ...base,
+ question: {
+ id: "q1",
+ ...QUESTION_EXAMPLES[DecisionModelQuestionType.CHOICE],
+ },
+ },
+ render: (args) => {
+ const [question, setQuestion] = useState(args.question);
+ const [expanded, setExpanded] = useState(args.expanded);
+ return (
+ <DecisionModelQuestionCard
+ {...args}
+ question={question}
+ expanded={expanded}
+ onExpandedChange={(next) => {
+ setExpanded(next);
+ args.onExpandedChange(next);
+ }}
+ onChange={(next) => {
+ setQuestion(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Score = meta.story({
+ args: {
+ ...base,
+ question: {
+ id: "q2",
+ ...QUESTION_EXAMPLES[DecisionModelQuestionType.SCORE],
+ },
+ },
+});
+
+export const YesNo = meta.story({
+ args: {
+ ...base,
+ question: {
+ id: "q3",
+ ...QUESTION_EXAMPLES[DecisionModelQuestionType.NOUL],
+ },
+ },
+});
+
+export const Blank = meta.story({
+ args: {
+ ...base,
+ onRemove: null,
+ question: {
+ id: "q4",
+ type: DecisionModelQuestionType.CHOICE,
+ scoreName: "",
+ instructions: "",
+ options: [
+ { value: "", description: "" },
+ { value: "", description: "" },
+ ],
+ levels: [{ description: "" }, { description: "" }],
+ criteria: { true: "", false: "" },
+ },
+ },
+ render: (args) => {
+ const [question, setQuestion] = useState(args.question);
+ return (
+ <DecisionModelQuestionCard
+ {...args}
+ question={question}
+ onChange={(next) => {
+ setQuestion(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Collapsed = meta.story({
+ args: {
+ ...base,
+ expanded: false,
+ question: {
+ id: "q1",
+ ...QUESTION_EXAMPLES[DecisionModelQuestionType.CHOICE],
+ },
+ },
+});
+
+export const WithErrors = meta.story({
+ args: {
+ ...base,
+ question: {
+ id: "q5",
+ ...QUESTION_EXAMPLES[DecisionModelQuestionType.CHOICE],
+ scoreName: "send_readiness",
+ options: [
+ { value: "ready", description: "" },
+ { value: "ready", description: "" },
+ ],
+ },
+ errors: {
+ scoreName: "Another question already writes “send_readiness”.",
+ options: "Option labels must be unique.",
+ },
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.tsx
new file mode 100644
index 0000000000..c40bc816e4
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard.tsx
@@ -0,0 +1,235 @@
+import { useId } from "react";
+import { DecisionModelQuestionType } from "@langfuse/shared";
+import { Trash2 } from "lucide-react";
+
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
+import { Input } from "@/src/components/ui/input";
+import { Label } from "@/src/components/ui/label";
+import { CollapsibleCard } from "@/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard";
+import { ChoiceOptionsEditor } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/ChoiceOptionsEditor/ChoiceOptionsEditor";
+import { NoulCriteriaEditor } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor";
+import { QuestionInstructionsField } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField";
+import {
+ QUESTION_TYPE_COPY,
+ QuestionTypeSelector,
+} from "@/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector";
+import { ScoreLevelsEditor } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor";
+import {
+ suggestScoreName,
+ type DecisionModelQuestionDraft,
+ type DecisionModelQuestionDraftErrors,
+} from "@/src/features/evals/v2/types/decisionModel";
+import { cn } from "@/src/utils/tailwind";
+
+export type DecisionModelQuestionCardProps = {
+ question: DecisionModelQuestionDraft;
+ index: number;
+ stateKeys: string[];
+ expanded: boolean;
+ onExpandedChange: (expanded: boolean) => void;
+ onChange: (question: DecisionModelQuestionDraft) => void;
+ onRemove: (() => void) | null;
+ errors?: DecisionModelQuestionDraftErrors;
+};
+
+function writesLine(question: DecisionModelQuestionDraft) {
+ switch (question.type) {
+ case DecisionModelQuestionType.CHOICE:
+ return `Writes a categorical score with one of ${question.options.length} labels.`;
+ case DecisionModelQuestionType.SCORE:
+ return `Writes a numeric score from 0 to ${Math.max(question.levels.length - 1, 0)} (expected level; can fall between levels).`;
+ case DecisionModelQuestionType.NOUL:
+ return "Writes a numeric score from 0 to 1: the probability the answer is yes.";
+ }
+}
+
+function CriteriaEditor({
+ question,
+ errors,
+ onChange,
+}: {
+ question: DecisionModelQuestionDraft;
+ errors: DecisionModelQuestionDraftErrors;
+ onChange: (question: DecisionModelQuestionDraft) => void;
+}) {
+ switch (question.type) {
+ case DecisionModelQuestionType.CHOICE:
+ return (
+ <ChoiceOptionsEditor
+ options={question.options}
+ onChange={(options) => onChange({ ...question, options })}
+ error={errors.options}
+ />
+ );
+ case DecisionModelQuestionType.SCORE:
+ return (
+ <ScoreLevelsEditor
+ levels={question.levels}
+ onChange={(levels) => onChange({ ...question, levels })}
+ error={errors.levels}
+ />
+ );
+ case DecisionModelQuestionType.NOUL:
+ return (
+ <NoulCriteriaEditor
+ criteria={question.criteria}
+ onChange={(criteria) => onChange({ ...question, criteria })}
+ />
+ );
+ }
+}
+
+/**
+ * One question of a decision-model evaluator. Collapses to a one-line summary
+ * so a long list stays scannable; expanded it walks type → question →
+ * criteria → score name, top to bottom.
+ */
+export function DecisionModelQuestionCard({
+ question,
+ index,
+ stateKeys,
+ expanded,
+ onExpandedChange,
+ onChange,
+ onRemove,
+ errors = {},
+}: DecisionModelQuestionCardProps) {
+ const id = useId();
+ const copy = QUESTION_TYPE_COPY[question.type];
+ const hasErrors = Object.values(errors).some(Boolean);
+ const summary = question.instructions.trim() || "Untitled question";
+
+ return (
+ <CollapsibleCard
+ open={expanded}
+ onOpenChange={onExpandedChange}
+ disabled={false}
+ triggerTitle={expanded ? "Collapse question" : "Expand question"}
+ header={
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="text-muted-foreground shrink-0 font-mono text-xs">
+ {index + 1}
+ </span>
+ <copy.icon className="h-4 w-4 shrink-0" aria-label={copy.label} />
+ <Badge
+ variant="secondary"
+ className={cn(
+ "shrink-0 font-mono",
+ !question.scoreName.trim() && "text-dark-yellow",
+ )}
+ >
+ {question.scoreName.trim() || "score name missing"}
+ </Badge>
+ <span
+ className={cn(
+ "truncate",
+ !question.instructions.trim() && "text-muted-foreground italic",
+ )}
+ title={summary}
+ >
+ {summary}
+ </span>
+ {hasErrors ? (
+ <Badge variant="destructive" className="shrink-0">
+ Needs attention
+ </Badge>
+ ) : null}
+ </span>
+ }
+ actions={
+ <span className="flex shrink-0 items-center pr-1">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="hover:text-destructive"
+ disabled={!onRemove}
+ onClick={onRemove ?? undefined}
+ title={
+ onRemove ? "Remove question" : "At least one question is required"
+ }
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </span>
+ }
+ >
+ <div className="flex flex-col gap-5 p-4">
+ <div className="flex flex-col gap-1.5">
+ <Label className="flex items-center gap-1.5">
+ Type
+ <InfoTooltip label="About question types">
+ Choice picks one of a fixed set of labels. Score rates along
+ ordered levels you describe. Yes/no returns the probability that a
+ statement is true. Pick the one your code can act on directly.
+ </InfoTooltip>
+ </Label>
+ <QuestionTypeSelector
+ value={question.type}
+ onValueChange={(type) => onChange({ ...question, type })}
+ />
+ </div>
+
+ <QuestionInstructionsField
+ value={question.instructions}
+ onChange={(instructions) =>
+ onChange({
+ ...question,
+ instructions,
+ scoreName:
+ question.scoreName === "" ||
+ question.scoreName === suggestScoreName(question.instructions)
+ ? suggestScoreName(instructions)
+ : question.scoreName,
+ })
+ }
+ stateKeys={stateKeys}
+ placeholder={copy.example}
+ error={errors.instructions}
+ />
+
+ <CriteriaEditor
+ question={question}
+ errors={errors}
+ onChange={onChange}
+ />
+
+ <div className="flex flex-col gap-1.5">
+ <Label
+ htmlFor={`${id}-score-name`}
+ className="flex items-center gap-1.5"
+ >
+ Score name
+ <InfoTooltip label="About score names">
+ Each question writes its own score under this name. Keep it
+ stable: renaming starts a new score series.
+ </InfoTooltip>
+ </Label>
+ <div className="flex flex-wrap items-center gap-3">
+ <Input
+ id={`${id}-score-name`}
+ value={question.scoreName}
+ onChange={(event) =>
+ onChange({ ...question, scoreName: event.target.value })
+ }
+ placeholder="e.g. refund_requested"
+ aria-invalid={Boolean(errors.scoreName)}
+ className={cn(
+ "max-w-xs font-mono",
+ errors.scoreName && "border-destructive",
+ )}
+ />
+ <span className="text-muted-foreground text-xs">
+ {writesLine(question)}
+ </span>
+ </div>
+ {errors.scoreName ? (
+ <p className="text-destructive text-xs">{errors.scoreName}</p>
+ ) : null}
+ </div>
+ </div>
+ </CollapsibleCard>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.stories.tsx
new file mode 100644
index 0000000000..6762edcc05
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.stories.tsx
@@ -0,0 +1,126 @@
+import { useState } from "react";
+import { DecisionModelQuestionType } from "@langfuse/shared";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { createEmptyQuestion } from "@/src/features/evals/v2/fns/evaluators/decisionModelQuestions";
+import { moveItem } from "@/src/features/evals/v2/fns/moveItem";
+import type { DecisionModelQuestionDraft } from "@/src/features/evals/v2/types/decisionModel";
+import {
+ DecisionModelQuestionList,
+ QUESTION_EXAMPLES,
+} from "./DecisionModelQuestionList";
+
+const meta = preview.meta({ component: DecisionModelQuestionList });
+
+const STATE_KEYS = ["input", "output"];
+
+const THREE_QUESTIONS: DecisionModelQuestionDraft[] = [
+ { id: "q1", ...QUESTION_EXAMPLES[DecisionModelQuestionType.CHOICE] },
+ { id: "q2", ...QUESTION_EXAMPLES[DecisionModelQuestionType.SCORE] },
+ { id: "q3", ...QUESTION_EXAMPLES[DecisionModelQuestionType.NOUL] },
+];
+
+const callbacks = {
+ onExpandedChange: fn(),
+ onChange: fn(),
+ onAdd: fn(),
+ onAddExample: fn(),
+ onRemove: fn(),
+ onReorder: fn(),
+};
+
+type StoryArgs = React.ComponentProps<typeof DecisionModelQuestionList>;
+
+/** Shared by the editable stories: local state so add / edit / reorder / remove work in the canvas. */
+function InteractiveQuestionList(args: StoryArgs) {
+ const [questions, setQuestions] = useState(args.questions);
+ const [expandedId, setExpandedId] = useState(args.expandedId);
+ const nextId = () => `q-${Date.now()}`;
+ return (
+ <DecisionModelQuestionList
+ {...args}
+ questions={questions}
+ expandedId={expandedId}
+ onExpandedChange={(id) => {
+ setExpandedId(id);
+ args.onExpandedChange(id);
+ }}
+ onChange={(next) => {
+ setQuestions((current) =>
+ current.map((question) =>
+ question.id === next.id ? next : question,
+ ),
+ );
+ args.onChange(next);
+ }}
+ onAdd={() => {
+ const question = createEmptyQuestion();
+ setQuestions((current) => [...current, question]);
+ setExpandedId(question.id);
+ args.onAdd();
+ }}
+ onAddExample={(type) => {
+ const question = { id: nextId(), ...QUESTION_EXAMPLES[type] };
+ setQuestions((current) => [...current, question]);
+ setExpandedId(question.id);
+ args.onAddExample(type);
+ }}
+ onRemove={(id) => {
+ setQuestions((current) =>
+ current.filter((question) => question.id !== id),
+ );
+ args.onRemove(id);
+ }}
+ onReorder={(from, to) => {
+ setQuestions((current) => moveItem(current, from, to));
+ args.onReorder(from, to);
+ }}
+ />
+ );
+}
+
+/** Full editing flow: add, edit, reorder, remove, collapse. */
+export const Default = meta.story({
+ args: {
+ ...callbacks,
+ questions: THREE_QUESTIONS,
+ expandedId: "q1",
+ stateKeys: STATE_KEYS,
+ },
+ render: (args) => <InteractiveQuestionList {...args} />,
+});
+
+export const Empty = meta.story({
+ args: {
+ ...callbacks,
+ questions: [],
+ expandedId: null,
+ stateKeys: STATE_KEYS,
+ },
+ render: (args) => <InteractiveQuestionList {...args} />,
+});
+
+export const AllCollapsed = meta.story({
+ args: {
+ ...callbacks,
+ questions: THREE_QUESTIONS,
+ expandedId: null,
+ stateKeys: STATE_KEYS,
+ },
+});
+
+export const WithErrors = meta.story({
+ args: {
+ ...callbacks,
+ questions: [
+ THREE_QUESTIONS[0]!,
+ { ...THREE_QUESTIONS[2]!, scoreName: "send_readiness" },
+ ],
+ expandedId: null,
+ stateKeys: STATE_KEYS,
+ errorsById: {
+ q3: { scoreName: "Another question already writes “send_readiness”." },
+ },
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.tsx
new file mode 100644
index 0000000000..67bea54c2f
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList.tsx
@@ -0,0 +1,172 @@
+import {
+ DECISION_MODEL_LIMITS,
+ DecisionModelQuestionType,
+} from "@langfuse/shared";
+import { Plus, Sparkles } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
+import { Label } from "@/src/components/ui/label";
+import { SortableList } from "@/src/features/evals/v2/components/SortableList/SortableList";
+import { DecisionModelQuestionCard } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionCard/DecisionModelQuestionCard";
+import { QUESTION_TYPE_COPY } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector";
+import type {
+ DecisionModelQuestionDraft,
+ DecisionModelQuestionDraftErrors,
+} from "@/src/features/evals/v2/types/decisionModel";
+
+export const QUESTION_EXAMPLES: Record<
+ DecisionModelQuestionType,
+ Omit<DecisionModelQuestionDraft, "id">
+> = {
+ [DecisionModelQuestionType.CHOICE]: {
+ type: DecisionModelQuestionType.CHOICE,
+ scoreName: "send_readiness",
+ instructions: "Is `output` ready to send as an answer to `input`?",
+ options: [
+ {
+ value: "ready",
+ description: "Answers the request and states the next step.",
+ },
+ {
+ value: "needs_revision",
+ description: "Accurate but incomplete or unclear.",
+ },
+ {
+ value: "unsafe",
+ description: "Contradicts policy or invents information.",
+ },
+ ],
+ levels: [],
+ criteria: { true: "", false: "" },
+ },
+ [DecisionModelQuestionType.SCORE]: {
+ type: DecisionModelQuestionType.SCORE,
+ scoreName: "customer_frustration",
+ instructions: "How frustrated is the customer in `input`?",
+ options: [],
+ levels: [
+ { description: "Calm, just stating facts" },
+ { description: "Frustrated but civil" },
+ { description: "Very angry, strong language or threatening to leave" },
+ ],
+ criteria: { true: "", false: "" },
+ },
+ [DecisionModelQuestionType.NOUL]: {
+ type: DecisionModelQuestionType.NOUL,
+ scoreName: "refund_requested",
+ instructions: "Does `input` request a refund?",
+ options: [],
+ levels: [],
+ criteria: { true: "", false: "" },
+ },
+};
+
+/**
+ * The ordered questions of a decision-model evaluator. Every question is
+ * answered in the same call, so adding one costs only its own tokens; the
+ * footer says so because that is the reason to use a decision model.
+ */
+export function DecisionModelQuestionList({
+ questions,
+ expandedId,
+ stateKeys,
+ errorsById = {},
+ onExpandedChange,
+ onChange,
+ onAdd,
+ onAddExample,
+ onRemove,
+ onReorder,
+}: {
+ questions: DecisionModelQuestionDraft[];
+ expandedId: string | null;
+ stateKeys: string[];
+ errorsById?: Record<string, DecisionModelQuestionDraftErrors>;
+ onExpandedChange: (id: string | null) => void;
+ onChange: (question: DecisionModelQuestionDraft) => void;
+ onAdd: () => void;
+ onAddExample: (type: DecisionModelQuestionType) => void;
+ onRemove: (id: string) => void;
+ onReorder: (fromIndex: number, toIndex: number) => void;
+}) {
+ return (
+ <div className="flex flex-col gap-3">
+ <Label className="flex items-center gap-1.5">
+ Questions
+ <InfoTooltip label="About questions">
+ Each question is one snap judgment about the state and writes one
+ score. All questions are answered in a single model call, so a second
+ or tenth question costs only its own tokens.
+ </InfoTooltip>
+ <span className="text-muted-foreground text-xs font-normal">
+ {questions.length} of {DECISION_MODEL_LIMITS.maxQuestions}
+ </span>
+ </Label>
+
+ {questions.length === 0 ? (
+ <div className="text-muted-foreground flex flex-col items-start gap-3 rounded-md border border-dashed p-4 text-sm">
+ <p>
+ No questions yet. Start from an example to see the shape of each
+ type, or add a blank question.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {Object.values(DecisionModelQuestionType).map((type) => {
+ const copy = QUESTION_TYPE_COPY[type];
+ return (
+ <Button
+ key={type}
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onAddExample(type)}
+ >
+ <Sparkles className="mr-1 h-3.5 w-3.5" />
+ {copy.label}: “
+ {QUESTION_EXAMPLES[type].instructions.replace(/`/g, "")}”
+ </Button>
+ );
+ })}
+ </div>
+ </div>
+ ) : (
+ <SortableList
+ items={questions}
+ getId={(question) => question.id}
+ getLabel={(question, index) =>
+ question.scoreName || `question ${index + 1}`
+ }
+ onReorder={onReorder}
+ gap="md"
+ renderItem={(question, index) => (
+ <DecisionModelQuestionCard
+ question={question}
+ index={index}
+ stateKeys={stateKeys}
+ expanded={expandedId === question.id}
+ onExpandedChange={(expanded) =>
+ onExpandedChange(expanded ? question.id : null)
+ }
+ onChange={onChange}
+ onRemove={
+ questions.length > 1 ? () => onRemove(question.id) : null
+ }
+ errors={errorsById[question.id]}
+ />
+ )}
+ />
+ )}
+
+ <div className="flex flex-wrap items-center gap-3">
+ <Button type="button" variant="outline" size="sm" onClick={onAdd}>
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ Add question
+ </Button>
+ <span className="text-muted-foreground text-xs">
+ Answered together in one call; extra questions add only their own
+ tokens.
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionSummary/DecisionModelQuestionSummary.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionSummary/DecisionModelQuestionSummary.tsx
new file mode 100644
index 0000000000..7dcdf3e9cb
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionSummary/DecisionModelQuestionSummary.tsx
@@ -0,0 +1,95 @@
+import {
+ DecisionModelQuestionType,
+ type DecisionModelEntry,
+ type DecisionModelQuestion,
+} from "@langfuse/shared";
+
+import { Badge } from "@/src/components/ui/badge";
+import { QUESTION_TYPE_COPY } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector";
+
+function entryText(entry: DecisionModelEntry | null | undefined) {
+ if (entry == null) return "";
+ return typeof entry === "string" ? entry : JSON.stringify(entry);
+}
+
+function Criteria({ question }: { question: DecisionModelQuestion }) {
+ switch (question.type) {
+ case DecisionModelQuestionType.CHOICE:
+ return (
+ <ul className="flex flex-col gap-0.5">
+ {question.options.map((option) => (
+ <li key={option.value} className="flex gap-2">
+ <span className="shrink-0 font-mono">{option.value}</span>
+ {option.description ? (
+ <span className="text-muted-foreground">
+ {entryText(option.description)}
+ </span>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ );
+ case DecisionModelQuestionType.SCORE:
+ return (
+ <ol className="flex flex-col gap-0.5">
+ {question.levels.map((level, index) => (
+ <li key={index} className="flex gap-2">
+ <span className="text-muted-foreground shrink-0 font-mono">
+ {index}
+ </span>
+ <span>{entryText(level.description)}</span>
+ </li>
+ ))}
+ </ol>
+ );
+ case DecisionModelQuestionType.NOUL:
+ return question.criteria?.true || question.criteria?.false ? (
+ <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5">
+ {question.criteria.true ? (
+ <>
+ <dt className="text-muted-foreground">Yes</dt>
+ <dd>{entryText(question.criteria.true)}</dd>
+ </>
+ ) : null}
+ {question.criteria.false ? (
+ <>
+ <dt className="text-muted-foreground">No</dt>
+ <dd>{entryText(question.criteria.false)}</dd>
+ </>
+ ) : null}
+ </dl>
+ ) : (
+ <p className="text-muted-foreground">Returns the probability of yes.</p>
+ );
+ }
+}
+
+/** Read-only rendering of a saved decision-model question. */
+export function DecisionModelQuestionSummary({
+ question,
+ index,
+}: {
+ question: DecisionModelQuestion;
+ index: number;
+}) {
+ const copy = QUESTION_TYPE_COPY[question.type];
+ return (
+ <div className="bg-card text-card-foreground flex flex-col gap-2 rounded-md border p-3 text-sm">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="text-muted-foreground shrink-0 font-mono text-xs">
+ {index + 1}
+ </span>
+ <copy.icon className="h-4 w-4 shrink-0" aria-label={copy.label} />
+ <Badge variant="secondary" className="shrink-0 font-mono">
+ {question.scoreName}
+ </Badge>
+ <span className="truncate" title={entryText(question.instructions)}>
+ {entryText(question.instructions)}
+ </span>
+ </div>
+ <div className="pl-6 text-xs">
+ <Criteria question={question} />
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.stories.tsx
new file mode 100644
index 0000000000..2ba0fb516d
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.stories.tsx
@@ -0,0 +1,96 @@
+import preview from "../../../../../../../../.storybook/preview";
+import { DecisionModelResultView } from "./DecisionModelResultView";
+
+const meta = preview.meta({ component: DecisionModelResultView });
+
+export const AllTypes = meta.story({
+ args: {
+ results: [
+ {
+ questionId: "q1",
+ type: "choice",
+ scoreName: "send_readiness",
+ instructions: "Is `output` ready to send as an answer to `input`?",
+ choice: "ready",
+ probabilities: { ready: 0.86, needs_revision: 0.11, unsafe: 0.03 },
+ confidence: 0.82,
+ },
+ {
+ questionId: "q2",
+ type: "score",
+ scoreName: "customer_frustration",
+ instructions: "How frustrated is the customer in `input`?",
+ score: 1.28,
+ levels: [
+ "Calm, just stating facts",
+ "Frustrated but civil",
+ "Very angry, strong language or threatening to leave",
+ ],
+ probabilities: { "0": 0.08, "1": 0.56, "2": 0.36 },
+ confidence: 0.61,
+ },
+ {
+ questionId: "q3",
+ type: "noul",
+ scoreName: "refund_requested",
+ instructions: "Does `input` request a refund?",
+ probability: 0.97,
+ },
+ ],
+ },
+});
+
+export const LowConfidence = meta.story({
+ args: {
+ results: [
+ {
+ questionId: "q1",
+ type: "choice",
+ scoreName: "send_readiness",
+ instructions: "Is `output` ready to send as an answer to `input`?",
+ choice: "needs_revision",
+ probabilities: { ready: 0.41, needs_revision: 0.44, unsafe: 0.15 },
+ confidence: 0.31,
+ },
+ {
+ questionId: "q3",
+ type: "noul",
+ scoreName: "refund_requested",
+ instructions: "Does `input` request a refund?",
+ probability: 0.52,
+ },
+ ],
+ },
+});
+
+/** Expected values at both ends of the scale keep their labels inside the track. */
+export const ScoreAtEdges = meta.story({
+ args: {
+ results: [
+ {
+ questionId: "q1",
+ type: "score",
+ scoreName: "customer_frustration",
+ instructions: "How frustrated is the customer in `input`?",
+ score: 0,
+ levels: [
+ "Calm, just stating facts",
+ "Frustrated but civil",
+ "Very angry",
+ ],
+ probabilities: { "0": 1, "1": 0, "2": 0 },
+ confidence: 1,
+ },
+ {
+ questionId: "q2",
+ type: "score",
+ scoreName: "urgency",
+ instructions: "How urgent is `input`?",
+ score: 2,
+ levels: ["Can wait", "This week", "Right now"],
+ probabilities: { "0": 0, "1": 0, "2": 1 },
+ confidence: 1,
+ },
+ ],
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.tsx
new file mode 100644
index 0000000000..bce806e500
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView.tsx
@@ -0,0 +1,257 @@
+import { Badge } from "@/src/components/ui/badge";
+import { QUESTION_TYPE_COPY } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector";
+import { cn } from "@/src/utils/tailwind";
+
+export type DecisionModelQuestionResult = {
+ questionId: string;
+ scoreName: string;
+ instructions: string;
+} & (
+ | {
+ type: "choice";
+ choice: string;
+ probabilities: Record<string, number>;
+ confidence: number | null;
+ }
+ | {
+ type: "score";
+ score: number;
+ levels: string[];
+ probabilities: Record<string, number>;
+ confidence: number | null;
+ }
+ | { type: "noul"; probability: number }
+);
+
+const percent = (value: number) => `${Math.round(value * 100)}%`;
+
+function confidenceTone(confidence: number) {
+ if (confidence >= 0.8) return "text-dark-green";
+ if (confidence >= 0.5) return "text-dark-yellow";
+ return "text-destructive";
+}
+
+function ConfidenceBadge({ confidence }: { confidence: number }) {
+ return (
+ <span
+ className={cn("font-mono text-xs", confidenceTone(confidence))}
+ title="How concentrated the distribution is (0–1). Not the winner's probability."
+ >
+ confidence {confidence.toFixed(2)}
+ </span>
+ );
+}
+
+function ProbabilityBars({
+ entries,
+ highlight,
+}: {
+ entries: Array<{ label: string; value: number }>;
+ highlight: string;
+}) {
+ return (
+ <ul className="flex flex-col gap-1">
+ {entries.map(({ label, value }) => {
+ const winner = label === highlight;
+ return (
+ <li
+ key={label}
+ className="grid grid-cols-[minmax(6rem,1fr)_3fr_3rem] items-center gap-2 text-xs"
+ >
+ <span
+ className={cn(
+ "truncate font-mono",
+ winner ? "font-bold" : "text-muted-foreground",
+ )}
+ title={label}
+ >
+ {label}
+ </span>
+ <span className="bg-muted h-2 overflow-hidden rounded-full">
+ <span
+ className={cn(
+ "block h-full rounded-full",
+ winner ? "bg-primary-accent" : "bg-muted-foreground/40",
+ )}
+ style={{ width: percent(value) }}
+ />
+ </span>
+ <span
+ className={cn(
+ "text-right font-mono",
+ winner ? "" : "text-muted-foreground",
+ )}
+ >
+ {percent(value)}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ );
+}
+
+function ScoreDistribution({
+ score,
+ levels,
+ probabilities,
+}: {
+ score: number;
+ levels: string[];
+ probabilities: Record<string, number>;
+}) {
+ const top = Math.max(levels.length - 1, 1);
+ const nearest = Math.min(Math.max(Math.round(score), 0), levels.length - 1);
+ const position = Math.min(Math.max(score / top, 0), 1) * 100;
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="relative pt-4">
+ <div className="bg-muted h-2 rounded-full" />
+ <span
+ className="bg-primary-accent absolute top-3 h-4 w-0.5 -translate-x-1/2 rounded"
+ style={{ left: `${position}%` }}
+ aria-hidden="true"
+ />
+ <span
+ className="text-primary-accent absolute top-0 font-mono text-xs font-bold"
+ style={{
+ left: `${position}%`,
+ transform: `translateX(-${position}%)`,
+ }}
+ >
+ {score.toFixed(2)}
+ </span>
+ </div>
+ <ol
+ className="grid gap-1"
+ style={{
+ gridTemplateColumns: `repeat(${levels.length}, minmax(0, 1fr))`,
+ }}
+ >
+ {levels.map((description, index) => (
+ <li
+ key={index}
+ className={cn(
+ "flex flex-col gap-0.5 text-xs",
+ index === nearest ? "" : "text-muted-foreground",
+ )}
+ >
+ <span className="font-mono">
+ {index} · {percent(probabilities[String(index)] ?? 0)}
+ </span>
+ <span className="line-clamp-2" title={description}>
+ {description}
+ </span>
+ </li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
+function NoulGauge({ probability }: { probability: number }) {
+ const leaning = probability >= 0.5 ? "yes" : "no";
+ return (
+ <div className="flex flex-col gap-1 text-xs">
+ <div className="flex items-center justify-between font-mono">
+ <span className="text-muted-foreground">no</span>
+ <span className="font-bold">
+ P(yes) = {probability.toFixed(2)} → leaning {leaning}
+ </span>
+ <span className="text-muted-foreground">yes</span>
+ </div>
+ <div className="bg-muted relative h-2 rounded-full">
+ <span
+ className="bg-primary-accent absolute inset-y-0 left-0 rounded-full"
+ style={{ width: percent(probability) }}
+ />
+ <span
+ className="bg-muted-foreground/40 absolute inset-y-[-3px] left-1/2 w-px"
+ aria-hidden="true"
+ />
+ </div>
+ </div>
+ );
+}
+
+function resultValue(result: DecisionModelQuestionResult) {
+ switch (result.type) {
+ case "choice":
+ return result.choice;
+ case "score":
+ return result.score.toFixed(2);
+ case "noul":
+ return result.probability.toFixed(2);
+ }
+}
+
+function ResultVisual({ result }: { result: DecisionModelQuestionResult }) {
+ switch (result.type) {
+ case "choice":
+ return (
+ <ProbabilityBars
+ entries={Object.entries(result.probabilities)
+ .sort(([, a], [, b]) => b - a)
+ .map(([label, value]) => ({ label, value }))}
+ highlight={result.choice}
+ />
+ );
+ case "score":
+ return (
+ <ScoreDistribution
+ score={result.score}
+ levels={result.levels}
+ probabilities={result.probabilities}
+ />
+ );
+ case "noul":
+ return <NoulGauge probability={result.probability} />;
+ }
+}
+
+function ResultRow({ result }: { result: DecisionModelQuestionResult }) {
+ const copy = QUESTION_TYPE_COPY[result.type];
+ return (
+ <li className="flex flex-col gap-2 rounded-md border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="flex min-w-0 items-center gap-2 text-sm">
+ <copy.icon className="h-4 w-4 shrink-0" aria-label={copy.label} />
+ <Badge variant="secondary" className="font-mono">
+ {result.scoreName}
+ </Badge>
+ <span
+ className="text-muted-foreground truncate"
+ title={result.instructions}
+ >
+ {result.instructions}
+ </span>
+ </span>
+ <span className="flex items-center gap-3">
+ {result.type !== "noul" && result.confidence !== null ? (
+ <ConfidenceBadge confidence={result.confidence} />
+ ) : null}
+ <Badge className="font-mono">{resultValue(result)}</Badge>
+ </span>
+ </div>
+ <ResultVisual result={result} />
+ </li>
+ );
+}
+
+/**
+ * Test result of a decision-model evaluator: one row per question with the
+ * full probability distribution, since the model returns no rationale.
+ */
+export function DecisionModelResultView({
+ results,
+}: {
+ results: DecisionModelQuestionResult[];
+}) {
+ return (
+ <ul className="flex flex-col gap-2">
+ {results.map((result) => (
+ <ResultRow key={result.questionId} result={result} />
+ ))}
+ </ul>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.stories.tsx
new file mode 100644
index 0000000000..5c9f204b16
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.stories.tsx
@@ -0,0 +1,140 @@
+import { useState } from "react";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import type { ActiveVariableMapping } from "@/src/features/evals/v2/types/variableMapping";
+import {
+ DecisionModelStateEditor,
+ type DecisionModelStateField,
+} from "./DecisionModelStateEditor";
+
+const meta = preview.meta({ component: DecisionModelStateEditor });
+
+const SAMPLE = {
+ input: {
+ messages: [
+ { role: "system", content: "You are a support agent for Acme." },
+ {
+ role: "user",
+ content:
+ "My order #4411 arrived broken and I want my money back. This is the second time.",
+ },
+ ],
+ },
+ output: {
+ answer:
+ "I'm sorry about that. I've issued a full refund for order #4411; it will show up within 3-5 business days.",
+ tool_calls: [{ name: "issue_refund", args: { order: "4411" } }],
+ },
+ metadata: { channel: "email", tier: "gold" },
+};
+
+const FIELDS: DecisionModelStateField[] = [
+ {
+ key: "input",
+ fieldState: {
+ selectedColumnId: "input",
+ jsonSelector: "$.messages[1].content",
+ },
+ },
+ {
+ key: "output",
+ fieldState: { selectedColumnId: "output", jsonSelector: "$.answer" },
+ },
+];
+
+const callbacks = {
+ onActiveMappingChange: fn(),
+ onChangeField: fn(),
+ onAddField: fn(),
+ onRenameField: fn(),
+ onRemoveField: fn(),
+};
+
+/** Full flow: expand, re-map, add and remove fields, inspect the object. */
+export const Default = meta.story({
+ args: {
+ ...callbacks,
+ fields: FIELDS,
+ activeMapping: { variable: "input", state: "preview" },
+ sourceObject: SAMPLE,
+ hasMatchingObservations: true,
+ },
+ render: (args) => {
+ const [fields, setFields] = useState(args.fields);
+ const [activeMapping, setActiveMapping] = useState<ActiveVariableMapping>(
+ args.activeMapping,
+ );
+ return (
+ <DecisionModelStateEditor
+ {...args}
+ fields={fields}
+ activeMapping={activeMapping}
+ onActiveMappingChange={(next) => {
+ setActiveMapping(next);
+ args.onActiveMappingChange(next);
+ }}
+ onChangeField={(key, fieldState) => {
+ setFields((current) =>
+ current.map((field) =>
+ field.key === key ? { ...field, fieldState } : field,
+ ),
+ );
+ args.onChangeField(key, fieldState);
+ }}
+ onAddField={() => {
+ const key = `field_${fields.length + 1}`;
+ setFields((current) => [
+ ...current,
+ { key, fieldState: { selectedColumnId: "", jsonSelector: "" } },
+ ]);
+ setActiveMapping({ variable: key, state: "renaming" });
+ args.onAddField();
+ }}
+ onRenameField={(key, next) => {
+ setFields((current) =>
+ current.map((field) =>
+ field.key === key ? { ...field, key: next } : field,
+ ),
+ );
+ setActiveMapping({ variable: next, state: "editing" });
+ args.onRenameField(key, next);
+ }}
+ onRemoveField={(key) => {
+ setFields((current) => current.filter((field) => field.key !== key));
+ args.onRemoveField(key);
+ }}
+ />
+ );
+ },
+});
+
+export const NoSample = meta.story({
+ args: {
+ ...callbacks,
+ fields: FIELDS,
+ activeMapping: null,
+ sourceObject: null,
+ hasMatchingObservations: false,
+ },
+});
+
+export const StateTooLarge = meta.story({
+ args: {
+ ...callbacks,
+ fields: [
+ {
+ key: "transcript",
+ fieldState: { selectedColumnId: "input", jsonSelector: "" },
+ },
+ ],
+ activeMapping: null,
+ sourceObject: {
+ input: Array.from({ length: 120 }, (_, index) => ({
+ role: index % 2 ? "assistant" : "user",
+ content: `Turn ${index}: ${"lorem ipsum dolor sit amet ".repeat(12)}`,
+ })),
+ },
+ hasMatchingObservations: true,
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.tsx
new file mode 100644
index 0000000000..8a341885ab
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor.tsx
@@ -0,0 +1,183 @@
+import { useMemo, useState } from "react";
+import {
+ DecisionModelStateKeySchema,
+ deepParseJsonIterative,
+} from "@langfuse/shared";
+import { ChevronDown, Plus, TriangleAlert } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import { EditableVariableMapping } from "@/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping";
+import { extractVariableMappingValue } from "@/src/features/evals/v2/fns/variableMapping/extractVariableMappingValue";
+import type {
+ ActiveVariableMapping,
+ VariableFieldState,
+} from "@/src/features/evals/v2/types/variableMapping";
+import { cn } from "@/src/utils/tailwind";
+
+export type DecisionModelStateField = {
+ key: string;
+ fieldState: VariableFieldState;
+};
+
+/** TypeSafe accepts ~32k for state plus the longest question; warn well below. */
+const STATE_SIZE_WARNING_CHARS = 24_000;
+
+/**
+ * Builds the JSON object the model receives from the mapped fields and the
+ * sample observation, mirroring the worker's state builder.
+ */
+function buildStatePreview(
+ fields: DecisionModelStateField[],
+ sourceObject: Record<string, unknown> | null,
+): Record<string, unknown> | null {
+ if (!sourceObject) return null;
+ const state: Record<string, unknown> = {};
+ for (const field of fields) {
+ const columnId = field.fieldState.selectedColumnId;
+ if (!columnId) continue;
+ const { value } = extractVariableMappingValue(
+ sourceObject,
+ columnId,
+ field.fieldState.jsonSelector ?? undefined,
+ );
+ if (value === null || value === undefined || value === "") continue;
+ state[field.key] = deepParseJsonIterative(value) ?? value;
+ }
+ return state;
+}
+
+/** Mirrors the shared state-key rule plus uniqueness within this evaluator. */
+function validateStateKey(
+ next: string,
+ fields: DecisionModelStateField[],
+): string | null {
+ if (!DecisionModelStateKeySchema.safeParse(next).success) {
+ return "Use letters, digits, and underscores; start with a letter.";
+ }
+ if (fields.some((field) => field.key === next)) {
+ return "A field with this name already exists.";
+ }
+ return null;
+}
+
+/**
+ * The state a decision model sees: a JSON object whose keys the user names and
+ * whose values are extracted from the observation. Reuses the LLM-judge
+ * mapping cards (field picker, JSON tree, JSONPath, live value) and adds the
+ * assembled object with a size indicator, since context rot is the model's
+ * main failure mode.
+ */
+export function DecisionModelStateEditor({
+ fields,
+ activeMapping,
+ onActiveMappingChange,
+ onChangeField,
+ onAddField,
+ onRenameField,
+ onRemoveField,
+ sourceObject,
+ hasMatchingObservations,
+ sourceUnavailableMessage,
+}: {
+ fields: DecisionModelStateField[];
+ activeMapping: ActiveVariableMapping;
+ onActiveMappingChange: (activeMapping: ActiveVariableMapping) => void;
+ onChangeField: (key: string, fieldState: VariableFieldState) => void;
+ /** Appends a placeholder-named field that opens in rename mode. */
+ onAddField: () => void;
+ onRenameField: (key: string, next: string) => void;
+ onRemoveField: (key: string) => void;
+ sourceObject: Record<string, unknown> | null;
+ hasMatchingObservations: boolean;
+ sourceUnavailableMessage?: string;
+}) {
+ const [previewOpen, setPreviewOpen] = useState(false);
+ const statePreview = useMemo(
+ () => buildStatePreview(fields, sourceObject),
+ [fields, sourceObject],
+ );
+ const stateSize = statePreview ? JSON.stringify(statePreview).length : 0;
+ const tooLarge = stateSize > STATE_SIZE_WARNING_CHARS;
+
+ return (
+ <div className="flex flex-col gap-3">
+ <EditableVariableMapping
+ mappings={fields.map((field) => ({
+ variable: field.key,
+ fieldState: field.fieldState,
+ }))}
+ variableDisplay="stateKey"
+ activeMapping={activeMapping}
+ onActiveMappingChange={onActiveMappingChange}
+ onChangeField={onChangeField}
+ onDeleteVariable={fields.length > 1 ? onRemoveField : undefined}
+ onRenameVariable={onRenameField}
+ validateVariableName={(_variable, next) =>
+ validateStateKey(next, fields)
+ }
+ sourceObject={sourceObject}
+ hasMatchingObservations={hasMatchingObservations}
+ sourceUnavailableMessage={sourceUnavailableMessage}
+ />
+
+ <div>
+ <Button type="button" variant="outline" size="sm" onClick={onAddField}>
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ Add field
+ </Button>
+ </div>
+
+ <div className="rounded-md border">
+ <button
+ type="button"
+ className="hover:bg-muted/50 flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm"
+ aria-expanded={previewOpen}
+ onClick={() => setPreviewOpen((open) => !open)}
+ >
+ <span className="flex items-center gap-2">
+ <span className="font-bold">State sent to the model</span>
+ {statePreview ? (
+ <span
+ className={cn(
+ "text-muted-foreground font-mono text-xs",
+ tooLarge && "text-dark-yellow flex items-center gap-1",
+ )}
+ >
+ {tooLarge ? <TriangleAlert className="h-3.5 w-3.5" /> : null}
+ {Object.keys(statePreview).length} field
+ {Object.keys(statePreview).length === 1 ? "" : "s"} ·{" "}
+ {stateSize.toLocaleString()} chars
+ {tooLarge ? " · trim fields, ~32k limit" : ""}
+ </span>
+ ) : (
+ <span className="text-muted-foreground text-xs">
+ select a sample observation to preview
+ </span>
+ )}
+ </span>
+ <ChevronDown
+ className={cn(
+ "h-4 w-4 shrink-0 transition-transform",
+ previewOpen ? "rotate-180" : "rotate-0",
+ )}
+ />
+ </button>
+ {previewOpen && statePreview ? (
+ <div className="border-t">
+ <PrettyJsonView
+ json={statePreview}
+ currentView="pretty"
+ isLoading={false}
+ showNullValues={true}
+ stickyTopLevelKey={false}
+ showObservationTypeBadge={false}
+ scrollable={true}
+ className="max-h-80 [&_.border]:border-0 [&_.rounded-sm]:rounded-none"
+ />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.stories.tsx
new file mode 100644
index 0000000000..d57d871372
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.stories.tsx
@@ -0,0 +1,34 @@
+import { useState } from "react";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { NoulCriteriaEditor } from "./NoulCriteriaEditor";
+
+const meta = preview.meta({ component: NoulCriteriaEditor });
+
+export const Collapsed = meta.story({
+ args: { criteria: { true: "", false: "" }, onChange: fn() },
+ render: (args) => {
+ const [criteria, setCriteria] = useState(args.criteria);
+ return (
+ <NoulCriteriaEditor
+ {...args}
+ criteria={criteria}
+ onChange={(next) => {
+ setCriteria(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Refined = meta.story({
+ args: {
+ criteria: {
+ true: "The user clearly asks for money back, a refund, or a chargeback.",
+ false: "A complaint or question without asking for money back.",
+ },
+ onChange: fn(),
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.tsx
new file mode 100644
index 0000000000..57ac2cf6be
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/NoulCriteriaEditor/NoulCriteriaEditor.tsx
@@ -0,0 +1,77 @@
+import { useId, useState } from "react";
+import { ChevronDown } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { Label } from "@/src/components/ui/label";
+import { Textarea } from "@/src/components/ui/textarea";
+import { cn } from "@/src/utils/tailwind";
+
+export type NoulCriteriaDraft = { true: string; false: string };
+
+/**
+ * Optional refinement of a yes/no question. Collapsed by default: most
+ * questions are clear without it, and the model returns P(true) either way.
+ */
+export function NoulCriteriaEditor({
+ criteria,
+ onChange,
+}: {
+ criteria: NoulCriteriaDraft;
+ onChange: (criteria: NoulCriteriaDraft) => void;
+}) {
+ const id = useId();
+ const hasContent = Boolean(criteria.true.trim() || criteria.false.trim());
+ const [open, setOpen] = useState(hasContent);
+
+ return (
+ <div className="@container flex flex-col gap-2">
+ <Button
+ type="button"
+ variant="link"
+ size="sm"
+ className="w-fit pl-0"
+ aria-expanded={open}
+ onClick={() => setOpen((value) => !value)}
+ >
+ Refine what yes and no mean
+ <span className="text-muted-foreground ml-1 font-normal">
+ (optional)
+ </span>
+ <ChevronDown
+ className={cn(
+ "ml-1 h-4 w-4 transition-transform",
+ open ? "rotate-180" : "rotate-0",
+ )}
+ />
+ </Button>
+ {open ? (
+ <div className="grid gap-3 @md:grid-cols-2">
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={`${id}-true`}>Yes means</Label>
+ <Textarea
+ id={`${id}-true`}
+ value={criteria.true}
+ onChange={(event) =>
+ onChange({ ...criteria, true: event.target.value })
+ }
+ placeholder="The user clearly asks for money back, a refund, or a chargeback."
+ rows={3}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={`${id}-false`}>No means</Label>
+ <Textarea
+ id={`${id}-false`}
+ value={criteria.false}
+ onChange={(event) =>
+ onChange({ ...criteria, false: event.target.value })
+ }
+ placeholder="A complaint or question without asking for money back."
+ rows={3}
+ />
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.stories.tsx
new file mode 100644
index 0000000000..91f3167503
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.stories.tsx
@@ -0,0 +1,54 @@
+import { useState } from "react";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { QuestionInstructionsField } from "./QuestionInstructionsField";
+
+const meta = preview.meta({ component: QuestionInstructionsField });
+
+export const Default = meta.story({
+ args: {
+ value: "Does `input` request a refund?",
+ stateKeys: ["input", "output", "policy"],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [value, setValue] = useState(args.value);
+ return (
+ <QuestionInstructionsField
+ {...args}
+ value={value}
+ onChange={(next) => {
+ setValue(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Empty = meta.story({
+ args: {
+ value: "",
+ stateKeys: ["input", "output"],
+ placeholder: "Which team should handle this ticket?",
+ onChange: fn(),
+ },
+});
+
+export const UnknownFieldReference = meta.story({
+ args: {
+ value: "Does `reply` answer `question` fully?",
+ stateKeys: ["input", "output"],
+ onChange: fn(),
+ },
+});
+
+export const Error = meta.story({
+ args: {
+ value: "",
+ stateKeys: ["input", "output"],
+ error: "Every question needs instructions.",
+ onChange: fn(),
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.tsx
new file mode 100644
index 0000000000..a6232fe6d3
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionInstructionsField/QuestionInstructionsField.tsx
@@ -0,0 +1,111 @@
+import { useId, useRef } from "react";
+import { TriangleAlert } from "lucide-react";
+
+import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
+import { Label } from "@/src/components/ui/label";
+import { Textarea } from "@/src/components/ui/textarea";
+import { extractReferencedStateKeys } from "@/src/features/evals/v2/types/decisionModel";
+import { cn } from "@/src/utils/tailwind";
+
+/**
+ * The plain-text question. Instructions never contain templates: the model
+ * receives the state as a JSON object and the question names the field it is
+ * about in backticks, so the field chips insert `` `key` `` at the cursor and
+ * a reference to a key that no longer exists is flagged.
+ */
+export function QuestionInstructionsField({
+ value,
+ onChange,
+ stateKeys,
+ placeholder,
+ error,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ stateKeys: string[];
+ placeholder?: string;
+ error?: string;
+}) {
+ const id = useId();
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const referenced = extractReferencedStateKeys(value);
+ const unknown = referenced.filter((key) => !stateKeys.includes(key));
+
+ const insertKey = (key: string) => {
+ const element = textareaRef.current;
+ const token = `\`${key}\``;
+ if (!element) {
+ onChange(value ? `${value} ${token}` : token);
+ return;
+ }
+ const start = element.selectionStart ?? value.length;
+ const end = element.selectionEnd ?? value.length;
+ const before = value.slice(0, start);
+ const after = value.slice(end);
+ const spacedBefore = before && !/\s$/.test(before) ? `${before} ` : before;
+ const spacedAfter = after && !/^\s/.test(after) ? ` ${after}` : after;
+ onChange(`${spacedBefore}${token}${spacedAfter}`);
+ requestAnimationFrame(() => {
+ const caret = spacedBefore.length + token.length;
+ element.focus();
+ element.setSelectionRange(caret, caret);
+ });
+ };
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={id} className="flex items-center gap-1.5">
+ Question
+ <InfoTooltip label="About questions">
+ Ask for one snap judgment a knowledgeable person makes in a second.
+ Name the state field the question is about in backticks, for example
+ “Does `question` request a refund?”. The model reads the state as a
+ JSON object, so the question does not repeat the data.
+ </InfoTooltip>
+ </Label>
+ <Textarea
+ id={id}
+ ref={textareaRef}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder={placeholder}
+ rows={3}
+ aria-invalid={Boolean(error) || unknown.length > 0}
+ className={cn(error && "border-destructive")}
+ />
+ <div className="flex flex-wrap items-center gap-1.5 text-xs">
+ <span className="text-muted-foreground">Fields:</span>
+ {stateKeys.map((key) => {
+ const used = referenced.includes(key);
+ return (
+ <button
+ key={key}
+ type="button"
+ onClick={() => insertKey(key)}
+ title={`Insert \`${key}\` at the cursor`}
+ className={cn(
+ "rounded border px-1.5 py-0.5 font-mono transition-colors",
+ used
+ ? "border-primary-accent/40 bg-primary-accent/10 text-primary-accent"
+ : "text-muted-foreground hover:bg-muted border-dashed",
+ )}
+ >
+ {key}
+ </button>
+ );
+ })}
+ {unknown.map((key) => (
+ <span
+ key={key}
+ className="text-dark-yellow flex items-center gap-1 rounded border border-dashed px-1.5 py-0.5 font-mono"
+ title={`\`${key}\` is not a state field`}
+ >
+ <TriangleAlert className="h-3 w-3" />
+ {key}
+ </span>
+ ))}
+ </div>
+ {error ? <p className="text-destructive text-xs">{error}</p> : null}
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.stories.tsx
new file mode 100644
index 0000000000..f4aa40f802
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.stories.tsx
@@ -0,0 +1,36 @@
+import { useState } from "react";
+import { DecisionModelQuestionType } from "@langfuse/shared";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { QuestionTypeSelector } from "./QuestionTypeSelector";
+
+const meta = preview.meta({ component: QuestionTypeSelector });
+
+export const Default = meta.story({
+ args: {
+ value: DecisionModelQuestionType.CHOICE,
+ onValueChange: fn(),
+ },
+ render: (args) => {
+ const [value, setValue] = useState(args.value);
+ return (
+ <QuestionTypeSelector
+ {...args}
+ value={value}
+ onValueChange={(next) => {
+ setValue(next);
+ args.onValueChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Disabled = meta.story({
+ args: {
+ value: DecisionModelQuestionType.SCORE,
+ disabled: true,
+ onValueChange: fn(),
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.tsx
new file mode 100644
index 0000000000..af3748fb19
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/QuestionTypeSelector/QuestionTypeSelector.tsx
@@ -0,0 +1,110 @@
+import { DecisionModelQuestionType } from "@langfuse/shared";
+import { Gauge, ListChecks, ToggleLeft, type LucideIcon } from "lucide-react";
+
+import { cn } from "@/src/utils/tailwind";
+
+export const QUESTION_TYPE_COPY: Record<
+ DecisionModelQuestionType,
+ {
+ label: string;
+ icon: LucideIcon;
+ summary: string;
+ writes: string;
+ example: string;
+ whenToUse: string;
+ }
+> = {
+ [DecisionModelQuestionType.CHOICE]: {
+ label: "Choice",
+ icon: ListChecks,
+ summary: "Pick one of a fixed set of labels.",
+ writes: "a categorical score",
+ example: "Which team should handle this ticket?",
+ whenToUse:
+ "The answer is one of a few options with no order between them. Add an “other” option if the list may not cover every input.",
+ },
+ [DecisionModelQuestionType.SCORE]: {
+ label: "Score",
+ icon: Gauge,
+ summary: "Rate along ordered levels you describe.",
+ writes: "a numeric score (the expected level)",
+ example: "How frustrated is the customer?",
+ whenToUse:
+ "The answer sits on a spectrum you can describe in steps. Describe situations, not degrees: “broken but a workaround exists” beats “moderately severe”.",
+ },
+ [DecisionModelQuestionType.NOUL]: {
+ label: "Yes / no",
+ icon: ToggleLeft,
+ summary: "Get the probability a statement is true.",
+ writes: "a numeric score (probability 0–1)",
+ example: "Does the message request a refund?",
+ whenToUse:
+ "A clean yes/no where the probability itself is the signal. Define the condition precisely; 0.5 means undecided, not “medium”.",
+ },
+};
+
+const ORDER: DecisionModelQuestionType[] = [
+ DecisionModelQuestionType.CHOICE,
+ DecisionModelQuestionType.SCORE,
+ DecisionModelQuestionType.NOUL,
+];
+
+/**
+ * Picks the question type. All three primitives stay visible with their
+ * descriptor so the model's vocabulary is learned where it is used.
+ */
+export function QuestionTypeSelector({
+ value,
+ onValueChange,
+ disabled = false,
+}: {
+ value: DecisionModelQuestionType;
+ onValueChange: (value: DecisionModelQuestionType) => void;
+ disabled?: boolean;
+}) {
+ const active = QUESTION_TYPE_COPY[value];
+ return (
+ <div className="@container flex flex-col gap-1.5">
+ <div
+ role="radiogroup"
+ aria-label="Question type"
+ className="grid gap-2 @lg:grid-cols-3"
+ >
+ {ORDER.map((type) => {
+ const copy = QUESTION_TYPE_COPY[type];
+ const selected = type === value;
+ return (
+ <button
+ key={type}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={disabled}
+ onClick={() => onValueChange(type)}
+ className={cn(
+ "flex flex-col gap-1 rounded-md border p-3 text-left text-sm transition-colors",
+ "hover:bg-muted/50 focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-hidden",
+ selected
+ ? "border-primary-accent bg-primary-accent/5 ring-primary-accent ring-1"
+ : "border-border",
+ disabled && "cursor-not-allowed opacity-60",
+ )}
+ >
+ <span className="flex items-center gap-1.5 font-bold">
+ <copy.icon className="h-4 w-4 shrink-0" />
+ {copy.label}
+ </span>
+ <span className="text-muted-foreground">{copy.summary}</span>
+ <span className="text-muted-foreground text-xs italic">
+ e.g. “{copy.example}”
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-muted-foreground text-xs">
+ Writes {active.writes}. {active.whenToUse}
+ </p>
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.stories.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.stories.tsx
new file mode 100644
index 0000000000..f8ffafe2c1
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.stories.tsx
@@ -0,0 +1,46 @@
+import { useState } from "react";
+import { fn } from "storybook/test";
+
+import preview from "../../../../../../../../.storybook/preview";
+import { ScoreLevelsEditor } from "./ScoreLevelsEditor";
+
+const meta = preview.meta({ component: ScoreLevelsEditor });
+
+export const Default = meta.story({
+ args: {
+ levels: [
+ { description: "Calm, just stating facts" },
+ { description: "Frustrated but civil" },
+ { description: "Very angry, strong language or threatening to leave" },
+ ],
+ onChange: fn(),
+ },
+ render: (args) => {
+ const [levels, setLevels] = useState(args.levels);
+ return (
+ <ScoreLevelsEditor
+ {...args}
+ levels={levels}
+ onChange={(next) => {
+ setLevels(next);
+ args.onChange(next);
+ }}
+ />
+ );
+ },
+});
+
+export const Empty = meta.story({
+ args: {
+ levels: [{ description: "" }, { description: "" }],
+ onChange: fn(),
+ },
+});
+
+export const Error = meta.story({
+ args: {
+ levels: [{ description: "Low" }, { description: "" }],
+ error: "Every level needs a description.",
+ onChange: fn(),
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.tsx b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.tsx
new file mode 100644
index 0000000000..4240cf5365
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/DecisionModel/ScoreLevelsEditor/ScoreLevelsEditor.tsx
@@ -0,0 +1,111 @@
+import { DECISION_MODEL_LIMITS } from "@langfuse/shared";
+import { Plus, Trash2 } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import { InfoTooltip } from "@/src/components/ui/InfoTooltip/InfoTooltip";
+import { Input } from "@/src/components/ui/input";
+import { Label } from "@/src/components/ui/label";
+import { SortableList } from "@/src/features/evals/v2/components/SortableList/SortableList";
+import { moveItem } from "@/src/features/evals/v2/fns/moveItem";
+
+export type ScoreLevelDraft = { description: string };
+
+function levelPlaceholder(index: number, count: number) {
+ if (index === 0) return "Lowest level, e.g. Calm, just stating facts";
+ if (index === count - 1) {
+ return "Highest level, e.g. Very angry or threatening to leave";
+ }
+ return "Describe this level";
+}
+
+/**
+ * Ordered levels of a Score question, low to high. The level number is its
+ * position; the model only sees the descriptions, so each one has to describe
+ * a recognisable situation rather than a degree.
+ */
+export function ScoreLevelsEditor({
+ levels,
+ onChange,
+ error,
+}: {
+ levels: ScoreLevelDraft[];
+ onChange: (levels: ScoreLevelDraft[]) => void;
+ error?: string;
+}) {
+ const update = (index: number, description: string) =>
+ onChange(levels.map((level, i) => (i === index ? { description } : level)));
+ const remove = (index: number) =>
+ onChange(levels.filter((_, i) => i !== index));
+ const canRemove = levels.length > DECISION_MODEL_LIMITS.minScoreLevels;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <Label className="flex items-center gap-1.5">
+ Levels, low to high
+ <InfoTooltip label="About levels">
+ Each level is one point on the scale. The model judges every level on
+ its own against the state and returns a position between them, so
+ describe situations (“broken, but a workaround exists”), not degrees
+ (“moderately severe”). Two to ten levels; drag to reorder.
+ </InfoTooltip>
+ <span className="text-muted-foreground text-xs font-normal">
+ {levels.length} of {DECISION_MODEL_LIMITS.maxScoreLevels}
+ </span>
+ </Label>
+ <SortableList
+ items={levels}
+ getId={(_level, index) => `level-${index}`}
+ getLabel={(_level, index) => `level ${index}`}
+ onReorder={(from, to) => onChange(moveItem(levels, from, to))}
+ renderItem={(level, index) => (
+ <div className="grid grid-cols-[2rem_1fr_auto] items-center gap-2">
+ <span
+ className="bg-muted text-muted-foreground flex h-8 w-8 items-center justify-center rounded-md font-mono text-xs"
+ aria-hidden="true"
+ >
+ {index}
+ </span>
+ <Input
+ value={level.description}
+ onChange={(event) => update(index, event.target.value)}
+ placeholder={levelPlaceholder(index, levels.length)}
+ aria-label={`Level ${index} description`}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="hover:text-destructive"
+ disabled={!canRemove}
+ onClick={() => remove(index)}
+ title={
+ canRemove
+ ? "Remove level"
+ : `Keep at least ${DECISION_MODEL_LIMITS.minScoreLevels} levels`
+ }
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ )}
+ />
+ <div className="flex items-center gap-3">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={levels.length >= DECISION_MODEL_LIMITS.maxScoreLevels}
+ onClick={() => onChange([...levels, { description: "" }])}
+ >
+ <Plus className="mr-1 h-3.5 w-3.5" />
+ Add level
+ </Button>
+ <span className="text-muted-foreground text-xs">
+ Score = 0 … {Math.max(levels.length - 1, 0)}, e.g. 1.3 sits between
+ levels 1 and 2.
+ </span>
+ </div>
+ {error ? <p className="text-destructive text-xs">{error}</p> : null}
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/EvaluationTypeConfiguration.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/EvaluationTypeConfiguration.tsx
index 047e27f1cb..5220473443 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/EvaluationTypeConfiguration.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/EvaluationTypeConfiguration.tsx
@@ -11,11 +11,13 @@ export function EvaluationTypeConfiguration({
mode,
onModeChange,
disabled,
+ showDecisionModel = false,
children,
}: {
mode: EvalTemplateType;
onModeChange: (mode: EvalTemplateType) => void;
disabled: boolean;
+ showDecisionModel?: boolean;
children: ReactNode;
}) {
return (
@@ -27,6 +29,9 @@ export function EvaluationTypeConfiguration({
Use custom code for deterministic checks like exact matches, regex,
or schema validation. Use an LLM when the check needs judgment, such
as rating helpfulness, tone, or answer quality.
+ {showDecisionModel
+ ? " Use a decision model (experimental) for a fast, cheap label with calibrated probabilities when the possible answers are known upfront."
+ : null}
</InfoTooltip>
</span>
</Label>
@@ -36,6 +41,7 @@ export function EvaluationTypeConfiguration({
value={mode}
onValueChange={onModeChange}
disabled={disabled}
+ showDecisionModel={showDecisionModel}
/>
<span>{mode === "CODE" ? "written in" : "with"}</span>
{children}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/components/EvaluationTypeToggle/EvaluationTypeToggle.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/components/EvaluationTypeToggle/EvaluationTypeToggle.tsx
index 106b0f8122..04cd99e878 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/components/EvaluationTypeToggle/EvaluationTypeToggle.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluationTypeConfiguration/components/EvaluationTypeToggle/EvaluationTypeToggle.tsx
@@ -1,4 +1,4 @@
-import { Code2, Sparkles } from "lucide-react";
+import { Code2, Scale, Sparkles } from "lucide-react";
import { EvalTemplateTypeEnum, type EvalTemplateType } from "@langfuse/shared";
import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
@@ -8,10 +8,12 @@ export function EvaluationTypeToggle({
value,
onValueChange,
disabled = false,
+ showDecisionModel = false,
}: {
value: EvalTemplateType;
onValueChange: (value: EvalTemplateType) => void;
disabled?: boolean;
+ showDecisionModel?: boolean;
}) {
return (
<Tabs
@@ -35,6 +37,15 @@ export function EvaluationTypeToggle({
label="Code evaluator"
/>
) : null}
+ {(showDecisionModel && !disabled) ||
+ value === EvalTemplateTypeEnum.DECISION_MODEL ? (
+ <Tabs.Trigger
+ value={EvalTemplateTypeEnum.DECISION_MODEL}
+ disabled={disabled}
+ icon={Scale}
+ label="Decision model (experimental)"
+ />
+ ) : null}
</Tabs.List>
</Tabs>
);
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorAlertButton/EvaluatorAlertButton.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorAlertButton/EvaluatorAlertButton.tsx
index ec821d117f..d4716da05c 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorAlertButton/EvaluatorAlertButton.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorAlertButton/EvaluatorAlertButton.tsx
@@ -9,6 +9,7 @@ import {
LoaderCircle,
Plus,
} from "lucide-react";
+import type { EvalTemplateType } from "@langfuse/shared";
import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
@@ -45,7 +46,7 @@ type EvaluatorAlertButtonProps = {
| {
scope: "evaluator";
evaluatorId: string;
- evaluatorType: "LLM_AS_JUDGE" | "CODE";
+ evaluatorType: EvalTemplateType;
scoreDataType?: "NUMERIC" | "BOOLEAN" | "CATEGORICAL";
}
| { scope: "allEvaluators" }
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/EvaluatorSetupEditor.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/EvaluatorSetupEditor.tsx
index c205664245..0b4bd354fa 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/EvaluatorSetupEditor.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/EvaluatorSetupEditor.tsx
@@ -58,7 +58,7 @@ export function EvaluatorSetupEditor({
onSetProjectDefault={onSetProjectDefault}
codeValidationResult={codeValidationResult}
/>
- {type === "LLM_AS_JUDGE" ? (
+ {type === "LLM_AS_JUDGE" || type === "DECISION_MODEL" ? (
<VariableMappingStepContainer
projectId={projectId}
store={store}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.stories.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.stories.tsx
index 65335fea9a..c97a4afad4 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.stories.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.stories.tsx
@@ -12,6 +12,7 @@ export const LlmAsJudge = meta.story({
type: "LLM_AS_JUDGE",
onTypeChange: fn(),
isEditing: false,
+ showDecisionModel: false,
typeConfiguration: <button type="button">Project default model</button>,
promptEditor: <div className="rounded-md border p-3">Prompt editor</div>,
scoreOutputEditor: (
@@ -27,7 +28,21 @@ export const Code = meta.story({
type: "CODE",
onTypeChange: fn(),
isEditing: false,
+ showDecisionModel: false,
typeConfiguration: <button type="button">TypeScript</button>,
codeEditor: <div className="rounded-md border p-3">Code editor</div>,
},
});
+
+export const DecisionModel = meta.story({
+ args: {
+ open: true,
+ onOpenChange: fn(),
+ type: "DECISION_MODEL",
+ onTypeChange: fn(),
+ isEditing: false,
+ showDecisionModel: true,
+ typeConfiguration: <button type="button">typesafe: jev-1.13.0</button>,
+ questionsEditor: <div className="rounded-md border p-3">Question list</div>,
+ },
+});
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.tsx
index 1e4169fd1e..f6fe5c29c5 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep.tsx
@@ -9,7 +9,10 @@ type DefinitionStepProps = {
onOpenChange: (open: boolean) => void;
onTypeChange: (type: EvalTemplateType) => void;
isEditing: boolean;
-} & (
+ showDecisionModel: boolean;
+} & DefinitionStepContent;
+
+type DefinitionStepContent =
| {
type: "LLM_AS_JUDGE";
typeConfiguration: ReactNode;
@@ -21,7 +24,27 @@ type DefinitionStepProps = {
typeConfiguration: ReactNode;
codeEditor: ReactNode;
}
-);
+ | {
+ type: "DECISION_MODEL";
+ typeConfiguration: ReactNode;
+ questionsEditor: ReactNode;
+ };
+
+function DefinitionStepBody(props: DefinitionStepContent) {
+ switch (props.type) {
+ case "LLM_AS_JUDGE":
+ return (
+ <>
+ {props.promptEditor}
+ {props.scoreOutputEditor}
+ </>
+ );
+ case "CODE":
+ return props.codeEditor;
+ case "DECISION_MODEL":
+ return props.questionsEditor;
+ }
+}
export function DefinitionStep(props: DefinitionStepProps) {
return (
@@ -36,17 +59,11 @@ export function DefinitionStep(props: DefinitionStepProps) {
mode={props.type}
onModeChange={props.onTypeChange}
disabled={props.isEditing}
+ showDecisionModel={props.showDecisionModel}
>
{props.typeConfiguration}
</EvaluationTypeConfiguration>
- {props.type === "LLM_AS_JUDGE" ? (
- <>
- {props.promptEditor}
- {props.scoreOutputEditor}
- </>
- ) : (
- props.codeEditor
- )}
+ <DefinitionStepBody {...props} />
</Stepper>
);
}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelQuestionsEditor/DecisionModelQuestionsEditor.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelQuestionsEditor/DecisionModelQuestionsEditor.tsx
new file mode 100644
index 0000000000..ba942b224a
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelQuestionsEditor/DecisionModelQuestionsEditor.tsx
@@ -0,0 +1,59 @@
+import { useMemo } from "react";
+import { useStore } from "zustand";
+import { useShallow } from "zustand/react/shallow";
+
+import {
+ DecisionModelQuestionList,
+ QUESTION_EXAMPLES,
+} from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionList/DecisionModelQuestionList";
+import {
+ createEmptyQuestion,
+ getQuestionDraftErrors,
+} from "@/src/features/evals/v2/fns/evaluators/decisionModelQuestions";
+import type { EvaluatorSetupStore } from "@/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore";
+import { safeRandomUUID } from "@/src/utils/safe-random-uuid";
+
+export function DecisionModelQuestionsEditor({
+ store,
+}: {
+ store: EvaluatorSetupStore;
+}) {
+ const state = useStore(
+ store,
+ useShallow((state) => ({
+ questions: state.questions,
+ expandedQuestionId: state.expandedQuestionId,
+ stateKeys: state.stateKeys,
+ actions: state.actions,
+ })),
+ );
+ const errorsById = useMemo(() => {
+ const errors = getQuestionDraftErrors(state.questions);
+ for (const question of state.questions) {
+ if (!question.instructions && !question.scoreName) {
+ delete errors[question.id];
+ }
+ }
+ return errors;
+ }, [state.questions]);
+
+ return (
+ <DecisionModelQuestionList
+ questions={state.questions}
+ expandedId={state.expandedQuestionId}
+ stateKeys={state.stateKeys}
+ errorsById={errorsById}
+ onExpandedChange={state.actions.setExpandedQuestionId}
+ onChange={state.actions.setQuestion}
+ onAdd={() => state.actions.addQuestion(createEmptyQuestion())}
+ onAddExample={(type) =>
+ state.actions.addQuestion({
+ id: safeRandomUUID(),
+ ...QUESTION_EXAMPLES[type],
+ })
+ }
+ onRemove={state.actions.removeQuestion}
+ onReorder={state.actions.reorderQuestion}
+ />
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelSelector/DecisionModelSelector.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelSelector/DecisionModelSelector.tsx
new file mode 100644
index 0000000000..2eaecd8c35
--- /dev/null
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelSelector/DecisionModelSelector.tsx
@@ -0,0 +1,74 @@
+import { isDecisionModelAdapter, supportedModels } from "@langfuse/shared";
+import { useStore } from "zustand";
+
+import { Button } from "@/src/components/ui/button";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import type { EvaluatorSetupStore } from "@/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore";
+import { api } from "@/src/utils/api";
+
+const SEPARATOR = "::";
+
+/**
+ * Picks the decision-model connection and model version. Decision models have
+ * no project default and no sampling parameters, so this replaces the judge
+ * model picker with a flat list of `provider :: model` options.
+ */
+export function DecisionModelSelector({
+ projectId,
+ store,
+ onConfigureProviders,
+}: {
+ projectId: string;
+ store: EvaluatorSetupStore;
+ onConfigureProviders: () => void;
+}) {
+ const selectedModel = useStore(store, (state) => state.selectedModel);
+ const selectModel = store.getState().actions.selectModel;
+ const connections = api.llmApiKey.all.useQuery({
+ projectId,
+ includeDecisionModels: true,
+ });
+
+ const options = (connections.data?.data ?? [])
+ .filter((connection) => isDecisionModelAdapter(connection.adapter))
+ .flatMap((connection) => {
+ const models = connection.withDefaultModels
+ ? [...connection.customModels, ...supportedModels[connection.adapter]]
+ : connection.customModels;
+ return models.map((model) => ({
+ value: `${connection.provider}${SEPARATOR}${model}`,
+ label: `${connection.provider}: ${model}`,
+ }));
+ });
+
+ if (connections.isSuccess && options.length === 0) {
+ return (
+ <Button type="button" variant="outline" onClick={onConfigureProviders}>
+ Add a TypeSafe connection
+ </Button>
+ );
+ }
+
+ return (
+ <div className="max-w-xs min-w-56">
+ <SelectInput
+ aria-label="Decision model"
+ placeholder="Select a decision model"
+ value={
+ selectedModel
+ ? `${selectedModel.provider}${SEPARATOR}${selectedModel.model}`
+ : ""
+ }
+ options={options}
+ onValueChange={(value) => {
+ const separatorIndex = value.indexOf(SEPARATOR);
+ if (separatorIndex === -1) return;
+ selectModel({
+ provider: value.slice(0, separatorIndex),
+ model: value.slice(separatorIndex + SEPARATOR.length),
+ });
+ }}
+ />
+ </div>
+ );
+}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DefinitionStepContainer/DefinitionStepContainer.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DefinitionStepContainer/DefinitionStepContainer.tsx
index 5b2c938e16..f0db1597b0 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DefinitionStepContainer/DefinitionStepContainer.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DefinitionStepContainer/DefinitionStepContainer.tsx
@@ -2,9 +2,13 @@ import { useStore } from "zustand";
import { useShallow } from "zustand/react/shallow";
import type { LLMAdapter } from "@langfuse/shared";
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
+
import { DefinitionStep } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/DefinitionStep";
import { CodeEditor } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/CodeEditor/CodeEditor";
import { CodeLanguageSelector } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/CodeLanguageSelector/CodeLanguageSelector";
+import { DecisionModelQuestionsEditor } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelQuestionsEditor/DecisionModelQuestionsEditor";
+import { DecisionModelSelector } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/DecisionModelSelector/DecisionModelSelector";
import { ModelSelector } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/ModelSelector/ModelSelector";
import { PromptEditor } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/PromptEditor/PromptEditor";
import { ScoreOutputEditor } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/DefinitionStep/components/ScoreOutputEditor/ScoreOutputEditor";
@@ -47,43 +51,68 @@ export function DefinitionStepContainer({
})),
);
- return state.type === "LLM_AS_JUDGE" ? (
- <DefinitionStep
- open={state.open}
- onOpenChange={(open) => onStepOpenChange(1, open)}
- type={state.type}
- onTypeChange={state.actions.setType}
- isEditing={isEditing}
- typeConfiguration={
- <ModelSelector
- projectId={projectId}
- store={store}
- defaultModel={defaultModel}
- providerGroups={providerGroups}
- providerAdapters={providerAdapters}
- canSetProjectDefault={canSetProjectDefault}
- onConfigureProviders={onConfigureProviders}
- onSetProjectDefault={onSetProjectDefault}
+ const showDecisionModel = useIsFeatureEnabled("decisionModelEvaluators", {
+ projectId,
+ });
+ const stepProps = {
+ open: state.open,
+ onOpenChange: (open: boolean) => onStepOpenChange(1, open),
+ onTypeChange: state.actions.setType,
+ isEditing,
+ showDecisionModel,
+ };
+
+ switch (state.type) {
+ case "LLM_AS_JUDGE":
+ return (
+ <DefinitionStep
+ {...stepProps}
+ type={state.type}
+ typeConfiguration={
+ <ModelSelector
+ projectId={projectId}
+ store={store}
+ defaultModel={defaultModel}
+ providerGroups={providerGroups}
+ providerAdapters={providerAdapters}
+ canSetProjectDefault={canSetProjectDefault}
+ onConfigureProviders={onConfigureProviders}
+ onSetProjectDefault={onSetProjectDefault}
+ />
+ }
+ promptEditor={<PromptEditor projectId={projectId} store={store} />}
+ scoreOutputEditor={<ScoreOutputEditor store={store} />}
/>
- }
- promptEditor={<PromptEditor projectId={projectId} store={store} />}
- scoreOutputEditor={<ScoreOutputEditor store={store} />}
- />
- ) : (
- <DefinitionStep
- open={state.open}
- onOpenChange={(open) => onStepOpenChange(1, open)}
- type={state.type}
- onTypeChange={state.actions.setType}
- isEditing={isEditing}
- typeConfiguration={<CodeLanguageSelector store={store} />}
- codeEditor={
- <CodeEditor
- projectId={projectId}
- store={store}
- validationResult={codeValidationResult}
+ );
+ case "CODE":
+ return (
+ <DefinitionStep
+ {...stepProps}
+ type={state.type}
+ typeConfiguration={<CodeLanguageSelector store={store} />}
+ codeEditor={
+ <CodeEditor
+ projectId={projectId}
+ store={store}
+ validationResult={codeValidationResult}
+ />
+ }
/>
- }
- />
- );
+ );
+ case "DECISION_MODEL":
+ return (
+ <DefinitionStep
+ {...stepProps}
+ type={state.type}
+ typeConfiguration={
+ <DecisionModelSelector
+ projectId={projectId}
+ store={store}
+ onConfigureProviders={onConfigureProviders}
+ />
+ }
+ questionsEditor={<DecisionModelQuestionsEditor store={store} />}
+ />
+ );
+ }
}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/VariableMappingStep.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/VariableMappingStep.tsx
index b0e56b2641..7573ad1650 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/VariableMappingStep.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/VariableMappingStep.tsx
@@ -2,20 +2,36 @@ import type { ReactNode } from "react";
import { Stepper } from "@/src/features/evals/v2/components/Stepper/Stepper";
+const COPY = {
+ variables: {
+ title: "Map variables to data",
+ description:
+ "Choose how observation fields populate each variable in your evaluation prompt. The live preview fills in real data so you can verify the mapping.",
+ },
+ state: {
+ title: "Build the state",
+ description:
+ "Choose which observation fields the decision model sees, as one JSON object. Questions refer to these fields by name; the live preview shows the exact object sent.",
+ },
+} as const;
+
export function VariableMappingStep({
open,
onOpenChange,
mappingEditor,
+ variant = "variables",
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
mappingEditor: ReactNode;
+ /** Prompt variables of an LLM judge, or the state of a decision model. */
+ variant?: keyof typeof COPY;
}) {
return (
<Stepper
number={2}
- title="Map variables to data"
- description="Choose how observation fields populate each variable in your evaluation prompt. The live preview fills in real data so you can verify the mapping."
+ title={COPY[variant].title}
+ description={COPY[variant].description}
open={open}
onOpenChange={onOpenChange}
>
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingEditorContainer/VariableMappingEditorContainer.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingEditorContainer/VariableMappingEditorContainer.tsx
index f2e6345b7b..cbdc7d15f5 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingEditorContainer/VariableMappingEditorContainer.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingEditorContainer/VariableMappingEditorContainer.tsx
@@ -2,13 +2,18 @@ import { memo, useMemo, useRef } from "react";
import { useStore } from "zustand";
import { useShallow } from "zustand/react/shallow";
+import { DecisionModelStateEditor } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelStateEditor/DecisionModelStateEditor";
import { VariableMapping } from "@/src/features/evals/v2/components/VariableMapping/VariableMapping";
+import { buildDecisionModelStateFields } from "@/src/features/evals/v2/fns/variableMapping/buildDecisionModelStateFields";
import { buildEvaluatorVariableMappings } from "@/src/features/evals/v2/fns/variableMapping/buildEvaluatorVariableMappings";
import { useEvaluatorSetupSample } from "@/src/features/evals/v2/hooks/useEvaluatorSetupSample";
import type { EvaluatorSetupStore } from "@/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore";
const StableVariableMapping = memo(VariableMapping);
+const SOURCE_UNAVAILABLE_MESSAGE =
+ "Select a sample observation in the test panel to preview mapped values.";
+
export function VariableMappingEditorContainer({
projectId,
store,
@@ -20,7 +25,9 @@ export function VariableMappingEditorContainer({
const state = useStore(
store,
useShallow((state) => ({
+ type: state.type,
promptMessages: state.promptMessages,
+ stateKeys: state.stateKeys,
variableFields: state.variableFields,
activeMapping: state.activeMapping,
selectedObservationId: state.selectedObservation?.id ?? null,
@@ -29,11 +36,16 @@ export function VariableMappingEditorContainer({
);
const mappings = useMemo(
() =>
- buildEvaluatorVariableMappings({
- promptMessages: state.promptMessages,
- variableFields: state.variableFields,
- }),
- [state.promptMessages, state.variableFields],
+ state.type === "DECISION_MODEL"
+ ? buildDecisionModelStateFields({
+ stateKeys: state.stateKeys,
+ variableFields: state.variableFields,
+ })
+ : buildEvaluatorVariableMappings({
+ promptMessages: state.promptMessages,
+ variableFields: state.variableFields,
+ }),
+ [state.type, state.stateKeys, state.promptMessages, state.variableFields],
);
const lastCompletedSample = useRef(resolvedSample);
@@ -42,6 +54,26 @@ export function VariableMappingEditorContainer({
const displayedSample = resolvedSample ?? lastCompletedSample.current;
+ if (state.type === "DECISION_MODEL") {
+ return (
+ <DecisionModelStateEditor
+ fields={mappings.map(({ variable, fieldState }) => ({
+ key: variable,
+ fieldState,
+ }))}
+ activeMapping={state.activeMapping}
+ onActiveMappingChange={state.actions.setActiveMapping}
+ onChangeField={state.actions.setVariableField}
+ onAddField={state.actions.addStateKey}
+ onRenameField={state.actions.renameStateKey}
+ onRemoveField={state.actions.removeStateKey}
+ sourceObject={displayedSample}
+ hasMatchingObservations={Boolean(displayedSample)}
+ sourceUnavailableMessage={SOURCE_UNAVAILABLE_MESSAGE}
+ />
+ );
+ }
+
return (
<StableVariableMapping
mode="editable"
@@ -51,7 +83,7 @@ export function VariableMappingEditorContainer({
onChangeField={state.actions.setVariableField}
sourceObject={displayedSample}
hasMatchingObservations={Boolean(displayedSample)}
- sourceUnavailableMessage="Select a sample observation in the test panel to preview mapped values."
+ sourceUnavailableMessage={SOURCE_UNAVAILABLE_MESSAGE}
/>
);
}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingStepContainer/VariableMappingStepContainer.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingStepContainer/VariableMappingStepContainer.tsx
index a185c32ca9..4cb5a01d23 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingStepContainer/VariableMappingStepContainer.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingStepContainer/VariableMappingStepContainer.tsx
@@ -1,4 +1,5 @@
import { useStore } from "zustand";
+import { useShallow } from "zustand/react/shallow";
import { VariableMappingStep } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/VariableMappingStep";
import { VariableMappingEditorContainer } from "@/src/features/evals/v2/components/Evaluators/EvaluatorSetupEditor/components/VariableMappingStep/components/VariableMappingEditorContainer/VariableMappingEditorContainer";
@@ -13,11 +14,18 @@ export function VariableMappingStepContainer({
store: EvaluatorSetupStore;
onStepOpenChange: (step: number, open: boolean) => void;
}) {
- const open = useStore(store, (state) => Boolean(state.openSteps[2]));
+ const { open, type } = useStore(
+ store,
+ useShallow((state) => ({
+ open: Boolean(state.openSteps[2]),
+ type: state.type,
+ })),
+ );
return (
<VariableMappingStep
open={open}
+ variant={type === "DECISION_MODEL" ? "state" : "variables"}
onOpenChange={(open) => onStepOpenChange(2, open)}
mappingEditor={
<VariableMappingEditorContainer projectId={projectId} store={store} />
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorTypeBadge/EvaluatorTypeBadge.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorTypeBadge/EvaluatorTypeBadge.tsx
index a57c83712c..099e266db9 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorTypeBadge/EvaluatorTypeBadge.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorTypeBadge/EvaluatorTypeBadge.tsx
@@ -1,12 +1,13 @@
-import { EvalTemplateTypeEnum, type EvalTemplateType } from "@langfuse/shared";
+import { type EvalTemplateType } from "@langfuse/shared";
import { Badge } from "@/src/components/ui/badge";
+import { evaluatorTypeLabel } from "@/src/features/evals/v2/fns/evaluators/evaluatorTypeLabel";
/** Displays the evaluator execution type with consistent product wording. */
export function EvaluatorTypeBadge({ type }: { type: EvalTemplateType }) {
return (
<Badge variant="secondary" className="whitespace-nowrap">
- {type === EvalTemplateTypeEnum.CODE ? "Code" : "LLM as a judge"}
+ {evaluatorTypeLabel(type)}
</Badge>
);
}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorDefinitionView/EvaluatorDefinitionView.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorDefinitionView/EvaluatorDefinitionView.tsx
index cbc4a2f6bd..182d3de149 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorDefinitionView/EvaluatorDefinitionView.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorDefinitionView/EvaluatorDefinitionView.tsx
@@ -5,6 +5,7 @@ import {
type EvalTemplateType,
type ObservationVariableMapping,
type EvaluatorPromptMessage,
+ parseDecisionModelQuestions,
} from "@langfuse/shared";
import { Codeblock as CodeBlock } from "@/src/components/design-system/Codeblock/Codeblock";
@@ -22,6 +23,7 @@ import {
import { PromptVariableEditor } from "@/src/features/evals/v2/components/Evaluators/Judges/PromptVariableEditor/PromptVariableEditor";
import { ScoreOutputConfiguration } from "@/src/features/evals/v2/components/Evaluators/Judges/ScoreOutputConfiguration/ScoreOutputConfiguration";
import { VariableMapping } from "@/src/features/evals/v2/components/VariableMapping/VariableMapping";
+import { DecisionModelQuestionSummary } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelQuestionSummary/DecisionModelQuestionSummary";
import { evalVariableColumnLabel } from "@/src/features/evals/v2/fns/variableMapping/evalVariableColumnLabel";
import { formatMappingLabel } from "@/src/features/evals/v2/fns/variableMapping/segmentsToJsonPath";
import { sourceCodeLanguageLabel } from "@/src/features/evals/v2/fns/evaluators/sourceCodeLanguageLabel";
@@ -43,6 +45,12 @@ export type EvaluatorDefinition =
variableMappings:
| { state: "hidden" }
| { state: "visible"; mappings: ObservationVariableMapping[] };
+ }
+ | {
+ type: Extract<EvalTemplateType, "DECISION_MODEL">;
+ questions: unknown;
+ selectedModel: JudgeModel | null;
+ variableMapping: ObservationVariableMapping[];
};
// A saved version is immutable, so every control below is the live editing
@@ -190,6 +198,59 @@ function LlmEvaluatorDefinitionView({
);
}
+function DecisionModelDefinitionView({
+ definition,
+}: {
+ definition: Extract<EvaluatorDefinition, { type: "DECISION_MODEL" }>;
+}) {
+ const questions = parseDecisionModelQuestions(definition.questions);
+
+ return (
+ <div className="flex min-w-0 flex-col gap-4">
+ <EvaluationTypeConfiguration
+ mode={EvalTemplateTypeEnum.DECISION_MODEL}
+ onModeChange={noop}
+ disabled
+ showDecisionModel
+ >
+ <Badge variant="outline" className="font-mono">
+ {definition.selectedModel
+ ? `${definition.selectedModel.provider}: ${definition.selectedModel.model}`
+ : "No model"}
+ </Badge>
+ </EvaluationTypeConfiguration>
+ <section className="flex min-w-0 flex-col gap-2">
+ <Label>Questions</Label>
+ {questions.success ? (
+ questions.data.map((question, index) => (
+ <DecisionModelQuestionSummary
+ key={question.id}
+ question={question}
+ index={index}
+ />
+ ))
+ ) : (
+ <p className="text-destructive text-xs">{questions.error}</p>
+ )}
+ </section>
+ <section className="flex flex-col gap-2">
+ <Label>State</Label>
+ <VariableMapping
+ mode="read-only"
+ variableDisplay="stateKey"
+ mappings={definition.variableMapping.map((mapping) => ({
+ variable: mapping.templateVariable,
+ fieldState: {
+ selectedColumnId: mapping.selectedColumnId,
+ jsonSelector: mapping.jsonSelector ?? null,
+ },
+ }))}
+ />
+ </section>
+ </div>
+ );
+}
+
function renderMediaAwareText(value: string) {
return splitStringByMediaReferences(value).map((segment, index) =>
segment.type === "media" ? (
@@ -211,9 +272,12 @@ export function EvaluatorDefinitionView({
}: {
definition: EvaluatorDefinition;
}) {
- return definition.type === EvalTemplateTypeEnum.CODE ? (
- <CodeEvaluatorDefinitionView definition={definition} />
- ) : (
- <LlmEvaluatorDefinitionView definition={definition} />
- );
+ switch (definition.type) {
+ case EvalTemplateTypeEnum.CODE:
+ return <CodeEvaluatorDefinitionView definition={definition} />;
+ case EvalTemplateTypeEnum.DECISION_MODEL:
+ return <DecisionModelDefinitionView definition={definition} />;
+ case EvalTemplateTypeEnum.LLM_AS_JUDGE:
+ return <LlmEvaluatorDefinitionView definition={definition} />;
+ }
}
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorVersionHistoryList/EvaluatorVersionHistoryList.tsx b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorVersionHistoryList/EvaluatorVersionHistoryList.tsx
index 60a7445c09..92cca282e6 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorVersionHistoryList/EvaluatorVersionHistoryList.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/components/EvaluatorVersionHistoryList/EvaluatorVersionHistoryList.tsx
@@ -1,4 +1,7 @@
-import { EvalTemplateTypeEnum } from "@langfuse/shared";
+import {
+ EvalTemplateTypeEnum,
+ observationVariableMappingList,
+} from "@langfuse/shared";
import { formatDistanceToNowStrict } from "date-fns";
import { RotateCcw } from "lucide-react";
@@ -25,6 +28,21 @@ function toEvaluatorDefinition(
};
}
+ if (version.type === EvalTemplateTypeEnum.DECISION_MODEL) {
+ const variableMapping = observationVariableMappingList.safeParse(
+ version.variableMapping,
+ );
+ return {
+ type: EvalTemplateTypeEnum.DECISION_MODEL,
+ questions: version.questions,
+ selectedModel:
+ version.provider && version.model
+ ? { provider: version.provider, model: version.model }
+ : null,
+ variableMapping: variableMapping.success ? variableMapping.data : [],
+ };
+ }
+
return {
type: EvalTemplateTypeEnum.LLM_AS_JUDGE,
promptMessages: version.promptMessages!,
diff --git a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/types.ts b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/types.ts
index bbf18c07f1..2709c214a0 100644
--- a/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/types.ts
+++ b/web/src/features/evals/v2/components/Evaluators/EvaluatorVersionHistorySheet/types.ts
@@ -19,5 +19,6 @@ export type EvaluatorVersion = {
vars: string[];
variableMapping: unknown;
outputDefinition: unknown;
+ questions?: unknown;
createdByUser: { name: string | null; email: string | null } | null;
};
diff --git a/web/src/features/evals/v2/components/Evaluators/Judges/ScoreOutputConfiguration/components/ScoreOutputSection/ScoreOutputSection.tsx b/web/src/features/evals/v2/components/Evaluators/Judges/ScoreOutputConfiguration/components/ScoreOutputSection/ScoreOutputSection.tsx
index 3b7a1836d8..cc8bea0adb 100644
--- a/web/src/features/evals/v2/components/Evaluators/Judges/ScoreOutputConfiguration/components/ScoreOutputSection/ScoreOutputSection.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/Judges/ScoreOutputConfiguration/components/ScoreOutputSection/ScoreOutputSection.tsx
@@ -69,16 +69,29 @@ function LabelWithTooltip({
);
}
+export type ScoreOutputConstraints = {
+ dataTypes?: ScoreOutputDataType[];
+ allowMultipleMatches?: boolean;
+};
+
export function ScoreOutputSection({
state,
onChange,
readOnly = false,
+ constraints,
}: {
state: ScoreOutputSelectorState;
onChange: (next: ScoreOutputSelectorState) => void;
readOnly?: boolean;
+ constraints?: ScoreOutputConstraints;
}) {
const boundsId = useId();
+ const dataTypeOptions = constraints?.dataTypes
+ ? DATA_TYPE_OPTIONS.filter((option) =>
+ constraints.dataTypes?.includes(option.value),
+ )
+ : DATA_TYPE_OPTIONS;
+ const allowMultipleMatches = constraints?.allowMultipleMatches ?? true;
const [addCategoryOpen, setAddCategoryOpen] = useState(false);
const [editingChoiceIndex, setEditingChoiceIndex] = useState<number | null>(
null,
@@ -152,7 +165,8 @@ export function ScoreOutputSection({
</LabelWithTooltip>
<div className="flex flex-wrap items-center gap-2 text-sm">
<span>Return</span>
- {state.dataType === ScoreDataTypeEnum.CATEGORICAL ? (
+ {state.dataType === ScoreDataTypeEnum.CATEGORICAL &&
+ allowMultipleMatches ? (
<Select
value={state.shouldAllowMultipleMatches ? "multiple" : "one"}
disabled={readOnly}
@@ -175,11 +189,11 @@ export function ScoreOutputSection({
</SelectContent>
</Select>
) : (
- <span>a</span>
+ <span>{allowMultipleMatches ? "a" : "one"}</span>
)}
<Select
value={state.dataType}
- disabled={readOnly}
+ disabled={readOnly || dataTypeOptions.length < 2}
onValueChange={(value) =>
handleDataTypeChange(value as ScoreOutputDataType)
}
@@ -188,7 +202,7 @@ export function ScoreOutputSection({
<SelectValue />
</SelectTrigger>
<SelectContent>
- {DATA_TYPE_OPTIONS.map((option) => (
+ {dataTypeOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.value === ScoreDataTypeEnum.CATEGORICAL &&
state.shouldAllowMultipleMatches
diff --git a/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx b/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx
index c380008377..7f72adb5a6 100644
--- a/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx
+++ b/web/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView.tsx
@@ -3,6 +3,10 @@ import { Clock, Coins } from "lucide-react";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import {
+ DecisionModelResultView,
+ type DecisionModelQuestionResult,
+} from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView";
import { usdFormatter } from "@/src/utils/numbers";
export type TestResultPanelState =
@@ -22,7 +26,13 @@ export type TestResultPanelState =
value: string;
comment: string | null;
}>;
- };
+ }
+ | { status: "decision-success"; results: DecisionModelQuestionResult[] };
+
+export type TestResultPanelTitle =
+ | "LLM Output"
+ | "Code Output"
+ | "Decision Model Output";
/** One measurement of the test call in the header strip. */
function ResultStat({
@@ -53,7 +63,7 @@ function TestResultHeader({
onRawOpenChange,
traceActions,
}: {
- title: "LLM Output" | "Code Output";
+ title: TestResultPanelTitle;
durationMs: number | null;
estimatedCostUsd: number | null;
rawOpen: boolean;
@@ -207,6 +217,9 @@ const RESULT_VIEWS: {
<LlmResultView score={score} reasoning={reasoning} />
),
"code-success": ({ scores }) => <CodeResultView scores={scores} />,
+ "decision-success": ({ results }) => (
+ <DecisionModelResultView results={results} />
+ ),
};
function renderResult<Status extends TestResultPanelState["status"]>(
@@ -231,7 +244,7 @@ export function TestResultPanelView({
traceActions,
rerunAction,
}: {
- title: "LLM Output" | "Code Output";
+ title: TestResultPanelTitle;
result: TestResultPanelState;
durationMs: number | null;
estimatedCostUsd: number | null;
diff --git a/web/src/features/evals/v2/components/Rules/EvaluatorMappingRow/EvaluatorMappingRow.tsx b/web/src/features/evals/v2/components/Rules/EvaluatorMappingRow/EvaluatorMappingRow.tsx
index 4bc58b4fe3..675642e81f 100644
--- a/web/src/features/evals/v2/components/Rules/EvaluatorMappingRow/EvaluatorMappingRow.tsx
+++ b/web/src/features/evals/v2/components/Rules/EvaluatorMappingRow/EvaluatorMappingRow.tsx
@@ -1,8 +1,8 @@
/* eslint-disable no-nested-ternary */
import { Check, ChevronDown, TriangleAlert, Unlink } from "lucide-react";
-import type {
- EvalTemplateType,
- ObservationVariableMapping,
+import {
+ type EvalTemplateType,
+ type ObservationVariableMapping,
} from "@langfuse/shared";
import { memo, type ReactNode, useState } from "react";
import { useStore } from "zustand";
diff --git a/web/src/features/evals/v2/components/SortableList/SortableList.tsx b/web/src/features/evals/v2/components/SortableList/SortableList.tsx
new file mode 100644
index 0000000000..7a1ed141b4
--- /dev/null
+++ b/web/src/features/evals/v2/components/SortableList/SortableList.tsx
@@ -0,0 +1,135 @@
+import { type CSSProperties, type ReactNode } from "react";
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { restrictToVerticalAxis } from "@dnd-kit/modifiers";
+import {
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { GripVertical } from "lucide-react";
+
+import { cn } from "@/src/utils/tailwind";
+
+function SortableRow({
+ id,
+ label,
+ disabled,
+ children,
+}: {
+ id: string;
+ label: string;
+ disabled: boolean;
+ children: ReactNode;
+}) {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ setActivatorNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id, disabled });
+ const style: CSSProperties = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ };
+
+ return (
+ <li
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ "grid grid-cols-[auto_1fr] items-start gap-1",
+ isDragging && "relative z-10 opacity-70",
+ )}
+ >
+ <button
+ ref={setActivatorNodeRef}
+ type="button"
+ disabled={disabled}
+ className="text-muted-foreground hover:text-foreground focus-visible:ring-ring flex h-9 w-5 cursor-grab touch-none items-center justify-center rounded focus-visible:ring-2 focus-visible:outline-hidden active:cursor-grabbing disabled:cursor-default disabled:opacity-30"
+ aria-label={`Reorder ${label}`}
+ title="Drag to reorder"
+ {...attributes}
+ {...listeners}
+ >
+ <GripVertical className="h-3.5 w-3.5" />
+ </button>
+ <div className="min-w-0">{children}</div>
+ </li>
+ );
+}
+
+/**
+ * Vertical list whose rows reorder by dragging the grip (mouse, touch, or
+ * keyboard). Rows are identified by `getId`; `onReorder` receives indices.
+ */
+export function SortableList<T>({
+ items,
+ getId,
+ getLabel,
+ onReorder,
+ renderItem,
+ gap = "sm",
+}: {
+ items: T[];
+ getId: (item: T, index: number) => string;
+ getLabel: (item: T, index: number) => string;
+ onReorder: (fromIndex: number, toIndex: number) => void;
+ renderItem: (item: T, index: number) => ReactNode;
+ /** Row spacing: `sm` for compact input rows, `md` for cards. */
+ gap?: "sm" | "md";
+}) {
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(TouchSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ }),
+ );
+ const ids = items.map(getId);
+
+ const handleDragEnd = ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ const fromIndex = ids.indexOf(String(active.id));
+ const toIndex = ids.indexOf(String(over.id));
+ if (fromIndex < 0 || toIndex < 0) return;
+ onReorder(fromIndex, toIndex);
+ };
+
+ return (
+ <DndContext
+ collisionDetection={closestCenter}
+ modifiers={[restrictToVerticalAxis]}
+ sensors={sensors}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext items={ids} strategy={verticalListSortingStrategy}>
+ <ol className={cn("flex flex-col", gap === "md" ? "gap-3" : "gap-1.5")}>
+ {items.map((item, index) => (
+ <SortableRow
+ key={ids[index]}
+ id={ids[index]!}
+ label={getLabel(item, index)}
+ disabled={items.length < 2}
+ >
+ {renderItem(item, index)}
+ </SortableRow>
+ ))}
+ </ol>
+ </SortableContext>
+ </DndContext>
+ );
+}
diff --git a/web/src/features/evals/v2/components/VariableMapping/VariableMapping.tsx b/web/src/features/evals/v2/components/VariableMapping/VariableMapping.tsx
index f4e2451b12..633e4eafd3 100644
--- a/web/src/features/evals/v2/components/VariableMapping/VariableMapping.tsx
+++ b/web/src/features/evals/v2/components/VariableMapping/VariableMapping.tsx
@@ -7,7 +7,10 @@ import {
type EditableVariableMappingProps,
} from "./components/EditableVariableMapping/EditableVariableMapping";
import { VariableMappingBinding } from "./components/VariableMappingBinding/VariableMappingBinding";
-import { ReadOnlyVariableMappingCardShell } from "./components/VariableMappingCardShell";
+import {
+ ReadOnlyVariableMappingCardShell,
+ type VariableDisplay,
+} from "./components/VariableMappingCardShell";
type VariableMappingProps = {
mappings: Array<{ variable: string; fieldState: VariableFieldState }>;
@@ -23,18 +26,22 @@ type VariableMappingProps = {
| "unvalidatedSourceColumnIds"
| "sourceUnavailableMessage"
>)
- | { mode: "read-only" }
+ | { mode: "read-only"; variableDisplay?: VariableDisplay }
);
function ReadOnlyVariableMapping({
mappings,
-}: Pick<VariableMappingProps, "mappings">) {
+ variableDisplay,
+}: Pick<VariableMappingProps, "mappings"> & {
+ variableDisplay?: VariableDisplay;
+}) {
return (
<div className="flex flex-col gap-4">
{mappings.map((mapping) => (
<ReadOnlyVariableMappingCardShell
key={mapping.variable}
variable={mapping.variable}
+ variableDisplay={variableDisplay}
mapping={
<VariableMappingBinding
columnLabel={
@@ -77,6 +84,9 @@ export function VariableMapping(props: VariableMappingProps) {
return props.mode === "editable" ? (
<EditableVariableMapping {...props} />
) : (
- <ReadOnlyVariableMapping mappings={props.mappings} />
+ <ReadOnlyVariableMapping
+ mappings={props.mappings}
+ variableDisplay={props.variableDisplay}
+ />
);
}
diff --git a/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx b/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx
index d1965141b2..ec278fead7 100644
--- a/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx
+++ b/web/src/features/evals/v2/components/VariableMapping/components/EditableVariableMapping/EditableVariableMapping.tsx
@@ -14,7 +14,11 @@ import type {
} from "@/src/features/evals/v2/types/variableMapping";
import { JsonPathEditor } from "../JsonPathEditor/JsonPathEditor";
import { SampleDataTreeSelector } from "../SampleDataTreeSelector/SampleDataTreeSelector";
-import { VariableMappingCardShell } from "../VariableMappingCardShell";
+import {
+ VariableMappingCardShell,
+ type VariableDisplay,
+ type VariableRenameControls,
+} from "../VariableMappingCardShell";
import { VariableMappingBinding } from "../VariableMappingBinding/VariableMappingBinding";
import { buildJsonPathSuggestions } from "@/src/features/evals/v2/fns/variableMapping/buildJsonPathSuggestions";
import { evalVariableColumnLabel } from "@/src/features/evals/v2/fns/variableMapping/evalVariableColumnLabel";
@@ -140,6 +144,7 @@ function MappingPreviewSurface({
*/
function TreeSelectorBody({
variable,
+ variableDisplay,
fieldState,
segments,
sourceObject,
@@ -149,6 +154,7 @@ function TreeSelectorBody({
onApplyJsonPath,
}: {
variable: string;
+ variableDisplay?: VariableDisplay;
fieldState: VariableFieldState;
segments: PathSegment[] | null;
sourceObject: Record<string, unknown> | null;
@@ -201,7 +207,9 @@ function TreeSelectorBody({
);
}
- const treeGuidance = `Click rows to open them — hover one and press "Use" to bind {{${variable}}}.`;
+ const variableLabel =
+ variableDisplay === "stateKey" ? variable : `{{${variable}}}`;
+ const treeGuidance = `Click rows to open them — hover one and press "Use" to bind ${variableLabel}.`;
return (
<>
@@ -235,7 +243,7 @@ function TreeSelectorBody({
</button>
</div>
<SampleDataTreeSelector
- variable={variable}
+ variableLabel={variableLabel}
currentColumnId={selectedColumnId}
currentSegments={segments}
roots={roots}
@@ -253,9 +261,11 @@ function TreeSelectorBody({
*/
function VariableMappingRow({
variable,
+ variableDisplay,
unmapped,
expanded,
editing,
+ rename,
onExpandedChange,
onEditingChange,
fieldState,
@@ -267,9 +277,11 @@ function VariableMappingRow({
onDelete,
}: {
variable: string;
+ variableDisplay?: VariableDisplay;
unmapped: boolean;
expanded: boolean;
editing: boolean;
+ rename?: VariableRenameControls;
onExpandedChange: (expanded: boolean) => void;
onEditingChange: (editing: boolean) => void;
fieldState: VariableFieldState;
@@ -316,6 +328,7 @@ function VariableMappingRow({
const body = editing ? (
<TreeSelectorBody
variable={variable}
+ variableDisplay={variableDisplay}
fieldState={fieldState}
segments={segments}
sourceObject={sourceObject}
@@ -389,6 +402,8 @@ function VariableMappingRow({
return (
<VariableMappingCardShell
variable={variable}
+ variableDisplay={variableDisplay}
+ rename={rename}
mapping={
!unmapped && columnLabel ? (
<VariableMappingBinding
@@ -431,6 +446,11 @@ export type EditableVariableMappingProps = {
/** Selected source columns that have no value in this sample and cannot be validated. */
unvalidatedSourceColumnIds?: string[];
sourceUnavailableMessage?: string;
+ /** Renders names as prompt templates (default) or as state keys. */
+ variableDisplay?: VariableDisplay;
+ /** Enables renaming in the card header; the name must pass `validateVariableName`. */
+ onRenameVariable?: (variable: string, next: string) => void;
+ validateVariableName?: (variable: string, next: string) => string | null;
};
export function EditableVariableMapping({
@@ -443,6 +463,9 @@ export function EditableVariableMapping({
hasMatchingObservations,
unvalidatedSourceColumnIds = [],
sourceUnavailableMessage,
+ variableDisplay,
+ onRenameVariable,
+ validateVariableName,
}: EditableVariableMappingProps) {
return (
<div data-variable-mapping-root="" className="flex flex-col gap-4">
@@ -450,6 +473,7 @@ export function EditableVariableMapping({
<VariableMappingRow
key={item.variable}
variable={item.variable}
+ variableDisplay={variableDisplay}
unmapped={!item.fieldState.selectedColumnId}
expanded={
activeMapping?.variable === item.variable &&
@@ -459,6 +483,24 @@ export function EditableVariableMapping({
activeMapping?.variable === item.variable &&
activeMapping.state === "editing"
}
+ rename={
+ onRenameVariable && validateVariableName
+ ? {
+ isRenaming:
+ activeMapping?.variable === item.variable &&
+ activeMapping.state === "renaming",
+ onRenamingChange: (renaming) =>
+ onActiveMappingChange(
+ renaming
+ ? { variable: item.variable, state: "renaming" }
+ : null,
+ ),
+ onRename: (next) => onRenameVariable(item.variable, next),
+ validateName: (next) =>
+ validateVariableName(item.variable, next),
+ }
+ : undefined
+ }
onExpandedChange={(expanded) =>
onActiveMappingChange(
expanded ? { variable: item.variable, state: "preview" } : null,
diff --git a/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.stories.tsx b/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.stories.tsx
index 06d158b20b..10ae95b5e6 100644
--- a/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.stories.tsx
+++ b/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.stories.tsx
@@ -27,7 +27,7 @@ const meta = preview.meta({ component: SampleDataTreeSelector });
export const Default = meta.story({
args: {
- variable: "input",
+ variableLabel: "{{input}}",
roots,
currentColumnId: null,
currentSegments: null,
@@ -37,7 +37,7 @@ export const Default = meta.story({
export const CurrentMapping = meta.story({
args: {
- variable: "input",
+ variableLabel: "{{input}}",
roots,
currentColumnId: "input",
currentSegments: ["messages", WILDCARD, "content"],
@@ -47,7 +47,7 @@ export const CurrentMapping = meta.story({
export const MediaReference = meta.story({
args: {
- variable: "input",
+ variableLabel: "{{input}}",
roots: [
{
id: "input",
diff --git a/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.tsx b/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.tsx
index 43cdce9c3c..292669e702 100644
--- a/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.tsx
+++ b/web/src/features/evals/v2/components/VariableMapping/components/SampleDataTreeSelector/SampleDataTreeSelector.tsx
@@ -110,7 +110,7 @@ function wildcardRepresentative(entries: unknown[]) {
}
function TreeRow({
- variable,
+ variableLabel,
columnId,
segments,
label,
@@ -124,7 +124,8 @@ function TreeRow({
onSelect,
currentKey,
}: {
- variable: string;
+ /** How the caller names the target, e.g. `{{input}}` or `input`. */
+ variableLabel: string;
columnId: string;
segments: PathSegment[];
label: string;
@@ -187,7 +188,7 @@ function TreeRow({
? undefined
: expandable
? preview
- : `Pull {{${variable}}} from here`
+ : `Pull ${variableLabel} from here`
}
>
{expandable ? (
@@ -230,7 +231,7 @@ function TreeRow({
{isCurrent ? (
<span
className="text-primary-accent bg-primary-accent/10 shrink-0 self-center rounded border border-transparent px-1.5 py-px text-[10px] font-bold"
- title={`{{${variable}}} currently maps to here`}
+ title={`${variableLabel} currently maps to here`}
>
current
</span>
@@ -239,7 +240,7 @@ function TreeRow({
type="button"
data-tree-row-action=""
className="bg-primary text-primary-foreground hover:bg-primary/90 hidden shrink-0 self-center rounded px-2 py-0.5 text-xs font-bold shadow-sm group-focus-within/row:inline-flex group-hover/row:inline-flex"
- title={`Pull {{${variable}}} from here`}
+ title={`Pull ${variableLabel} from here`}
onClick={() => onSelect(columnId, segments)}
>
Use
@@ -253,7 +254,7 @@ function TreeRow({
return (
<>
<TreeRow
- variable={variable}
+ variableLabel={variableLabel}
columnId={columnId}
segments={[...segments, WILDCARD]}
label="[*]"
@@ -267,7 +268,7 @@ function TreeRow({
currentKey={currentKey}
/>
<TreeRow
- variable={variable}
+ variableLabel={variableLabel}
columnId={columnId}
segments={[...segments, LAST]}
label="last"
@@ -282,7 +283,7 @@ function TreeRow({
{value.slice(0, MAX_CONCRETE_ENTRIES).map((entry, index) => (
<TreeRow
key={index}
- variable={variable}
+ variableLabel={variableLabel}
columnId={columnId}
segments={[...segments, index]}
label={`[${index}]`}
@@ -314,7 +315,7 @@ function TreeRow({
{entries.map(([childKey, childValue]) => (
<TreeRow
key={childKey}
- variable={variable}
+ variableLabel={variableLabel}
columnId={columnId}
segments={[...segments, childKey]}
label={childKey}
@@ -345,13 +346,14 @@ function TreeRow({
/** Selects one sample-observation field or nested path for a prompt variable. */
export function SampleDataTreeSelector({
- variable,
+ variableLabel,
roots,
currentColumnId,
currentSegments,
onSelect,
}: {
- variable: string;
+ /** How the caller names the target, e.g. `{{input}}` or `input`. */
+ variableLabel: string;
roots: Array<{ id: string; label: string; value: unknown }>;
currentColumnId: string | null;
currentSegments: PathSegment[] | null;
@@ -376,7 +378,7 @@ export function SampleDataTreeSelector({
{roots.map((root) => (
<TreeRow
key={root.id}
- variable={variable}
+ variableLabel={variableLabel}
columnId={root.id}
segments={[]}
label={root.label}
diff --git a/web/src/features/evals/v2/components/VariableMapping/components/StateKeyNameInput/StateKeyNameInput.tsx b/web/src/features/evals/v2/components/VariableMapping/components/StateKeyNameInput/StateKeyNameInput.tsx
new file mode 100644
index 0000000000..cd986b10e2
--- /dev/null
+++ b/web/src/features/evals/v2/components/VariableMapping/components/StateKeyNameInput/StateKeyNameInput.tsx
@@ -0,0 +1,70 @@
+import { useState } from "react";
+
+import { Input } from "@/src/components/ui/input";
+import { cn } from "@/src/utils/tailwind";
+
+/**
+ * Inline editor for a state key in a mapping card header. Enter or blur
+ * commits a valid name; Escape, or blurring an invalid one, keeps the old name.
+ */
+export function StateKeyNameInput({
+ value,
+ validate,
+ onCommit,
+ onCancel,
+}: {
+ value: string;
+ validate: (next: string) => string | null;
+ onCommit: (next: string) => void;
+ onCancel: () => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const trimmed = draft.trim();
+ const error = trimmed === value ? null : validate(trimmed);
+
+ const commit = () => {
+ if (trimmed === value || trimmed === "") {
+ onCancel();
+ return;
+ }
+ if (error) return;
+ onCommit(trimmed);
+ };
+
+ return (
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <Input
+ autoFocus
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ onFocus={(event) => event.target.select()}
+ onBlur={() => (error ? onCancel() : commit())}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ commit();
+ } else if (event.key === "Escape") {
+ event.preventDefault();
+ onCancel();
+ }
+ }}
+ aria-label="Field name"
+ aria-invalid={Boolean(error)}
+ placeholder="field_name"
+ className={cn(
+ "h-7 w-56 font-mono text-sm",
+ error && "border-destructive",
+ )}
+ />
+ {error ? (
+ <span className="text-destructive truncate text-xs" title={error}>
+ {error}
+ </span>
+ ) : (
+ <span className="text-muted-foreground shrink-0 text-xs">
+ Enter to save, Esc to cancel
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/web/src/features/evals/v2/components/VariableMapping/components/VariableMappingCardShell.tsx b/web/src/features/evals/v2/components/VariableMapping/components/VariableMappingCardShell.tsx
index bb6284da5c..5f3c57ebe6 100644
--- a/web/src/features/evals/v2/components/VariableMapping/components/VariableMappingCardShell.tsx
+++ b/web/src/features/evals/v2/components/VariableMapping/components/VariableMappingCardShell.tsx
@@ -1,24 +1,43 @@
/* eslint-disable no-nested-ternary */
-import { Pencil, Trash2, TriangleAlert, X } from "lucide-react";
+import {
+ Pencil,
+ TextCursorInput,
+ Trash2,
+ TriangleAlert,
+ X,
+} from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { CollapsibleCard } from "@/src/features/evals/v2/components/CollapsibleCard/CollapsibleCard";
+import { StateKeyNameInput } from "./StateKeyNameInput/StateKeyNameInput";
+
+/**
+ * How the mapped name is rendered: as a prompt template `{{variable}}`, or as
+ * a state key for evaluators whose mapping builds a JSON object.
+ */
+export type VariableDisplay = "template" | "stateKey";
function VariableMappingCardHeaderContent({
variable,
+ variableDisplay = "template",
mapping,
isUnmapped,
warningMessage,
}: {
variable: string;
+ variableDisplay?: VariableDisplay;
mapping: React.ReactNode;
isUnmapped: boolean;
warningMessage?: string | null;
}) {
return (
<>
- <span className="text-primary-accent shrink-0 font-mono font-bold">{`{{${variable}}}`}</span>
- <span className="text-muted-foreground shrink-0">maps to</span>
+ <span className="text-primary-accent shrink-0 font-mono font-bold">
+ {variableDisplay === "stateKey" ? variable : `{{${variable}}}`}
+ </span>
+ <span className="text-muted-foreground shrink-0">
+ {variableDisplay === "stateKey" ? "from" : "maps to"}
+ </span>
{isUnmapped ? (
<span className="text-dark-yellow flex min-w-0 items-center gap-1.5 font-bold">
<TriangleAlert className="h-4 w-4 shrink-0" />
@@ -42,9 +61,18 @@ function VariableMappingCardHeaderContent({
);
}
+/** Renaming a state key: the header swaps the name for an input. */
+export type VariableRenameControls = {
+ isRenaming: boolean;
+ onRenamingChange: (renaming: boolean) => void;
+ onRename: (next: string) => void;
+ validateName: (next: string) => string | null;
+};
+
/** Presentational shell for one editable prompt-variable mapping. */
function VariableMappingCardShell({
variable,
+ variableDisplay,
mapping,
isUnmapped,
warningMessage,
@@ -53,9 +81,11 @@ function VariableMappingCardShell({
onExpandedChange,
onEditingChange,
onDelete,
+ rename,
children,
}: {
variable: string;
+ variableDisplay?: VariableDisplay;
mapping?: React.ReactNode;
isUnmapped: boolean;
warningMessage?: string | null;
@@ -64,9 +94,11 @@ function VariableMappingCardShell({
onExpandedChange: (expanded: boolean) => void;
onEditingChange: (editing: boolean) => void;
onDelete?: () => void;
+ rename?: VariableRenameControls;
children?: React.ReactNode;
}) {
- const canToggle = !isEditing;
+ const isRenaming = rename?.isRenaming ?? false;
+ const canToggle = !isEditing && !isRenaming;
const bodyVisible = isExpanded || isEditing;
return (
@@ -74,6 +106,7 @@ function VariableMappingCardShell({
open={bodyVisible}
onOpenChange={onExpandedChange}
disabled={!canToggle}
+ headerInteractive={!isRenaming}
triggerTitle={
isEditing
? "Finish editing before collapsing this mapping"
@@ -82,15 +115,37 @@ function VariableMappingCardShell({
: `Expand {{${variable}}} mapping`
}
header={
- <VariableMappingCardHeaderContent
- variable={variable}
- mapping={mapping}
- isUnmapped={isUnmapped}
- warningMessage={warningMessage}
- />
+ isRenaming && rename ? (
+ <StateKeyNameInput
+ key={variable}
+ value={variable}
+ validate={rename.validateName}
+ onCommit={rename.onRename}
+ onCancel={() => rename.onRenamingChange(false)}
+ />
+ ) : (
+ <VariableMappingCardHeaderContent
+ variable={variable}
+ variableDisplay={variableDisplay}
+ mapping={mapping}
+ isUnmapped={isUnmapped}
+ warningMessage={warningMessage}
+ />
+ )
}
actions={
<span className="flex shrink-0 items-center pr-1">
+ {rename && !isRenaming ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ title={`Rename ${variable}`}
+ onClick={() => rename.onRenamingChange(true)}
+ >
+ <TextCursorInput className="h-3.5 w-3.5" />
+ </Button>
+ ) : null}
<Button
type="button"
variant="ghost"
@@ -101,6 +156,7 @@ function VariableMappingCardShell({
: "Change the mapping"
}
aria-expanded={isEditing}
+ disabled={isRenaming}
onClick={() => onEditingChange(!isEditing)}
>
{isEditing ? (
@@ -115,7 +171,11 @@ function VariableMappingCardShell({
variant="ghost"
size="icon-xs"
className="hover:text-destructive"
- title={`Remove {{${variable}}} from the prompt`}
+ title={
+ variableDisplay === "stateKey"
+ ? `Remove ${variable} from the state`
+ : `Remove {{${variable}}} from the prompt`
+ }
onClick={onDelete}
>
<Trash2 className="h-3.5 w-3.5" />
@@ -132,9 +192,11 @@ function VariableMappingCardShell({
/** Static card shell used when a saved mapping is displayed read-only. */
function ReadOnlyVariableMappingCardShell({
variable,
+ variableDisplay,
mapping,
}: {
variable: string;
+ variableDisplay?: VariableDisplay;
mapping: React.ReactNode;
}) {
return (
@@ -142,6 +204,7 @@ function ReadOnlyVariableMappingCardShell({
<div className="bg-secondary text-secondary-foreground flex min-h-9 min-w-0 items-center gap-2 px-3 py-1.5 text-sm">
<VariableMappingCardHeaderContent
variable={variable}
+ variableDisplay={variableDisplay}
mapping={mapping}
isUnmapped={false}
/>
diff --git a/web/src/features/evals/v2/constants/tableFilterColumns.ts b/web/src/features/evals/v2/constants/tableFilterColumns.ts
index 711e52261b..1d9231a344 100644
--- a/web/src/features/evals/v2/constants/tableFilterColumns.ts
+++ b/web/src/features/evals/v2/constants/tableFilterColumns.ts
@@ -13,6 +13,10 @@ const evaluatorTypeOptions = [
displayValue: "LLM as a judge",
},
{ value: EvalTemplateType.CODE, displayValue: "Code" },
+ {
+ value: EvalTemplateType.DECISION_MODEL,
+ displayValue: "Decision model (experimental)",
+ },
];
export const evaluatorTableFilterColumns: ColumnDefinition[] = [
diff --git a/web/src/features/evals/v2/fns/evaluatorTesting/toDecisionModelResults.ts b/web/src/features/evals/v2/fns/evaluatorTesting/toDecisionModelResults.ts
new file mode 100644
index 0000000000..3a86f99189
--- /dev/null
+++ b/web/src/features/evals/v2/fns/evaluatorTesting/toDecisionModelResults.ts
@@ -0,0 +1,82 @@
+import type { DecisionModelQuestionResult } from "@/src/features/evals/v2/components/Evaluators/DecisionModel/DecisionModelResultView/DecisionModelResultView";
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const toProbabilities = (value: unknown): Record<string, number> =>
+ isRecord(value)
+ ? Object.fromEntries(
+ Object.entries(value).filter(
+ (entry): entry is [string, number] => typeof entry[1] === "number",
+ ),
+ )
+ : {};
+
+/**
+ * Reads the scores of a decision-model test run into one row per question.
+ * Values come from the score itself; distributions and confidence from the
+ * `typesafe` metadata namespace the executor writes; the question text from
+ * the request that was sent.
+ */
+export function toDecisionModelResults(
+ response: Record<string, unknown>,
+): DecisionModelQuestionResult[] {
+ const scores = Array.isArray(response.scores) ? response.scores : [];
+ const requestQuestions =
+ isRecord(response.request) && isRecord(response.request.questions)
+ ? response.request.questions
+ : {};
+
+ return scores.flatMap((score, index): DecisionModelQuestionResult[] => {
+ if (!isRecord(score)) return [];
+ const typesafe = isRecord(score.metadata) ? score.metadata.typesafe : null;
+ if (!isRecord(typesafe)) return [];
+
+ const questionId = String(typesafe.questionId ?? index);
+ const question = requestQuestions[questionId];
+ const common = {
+ questionId,
+ scoreName: String(score.name ?? questionId),
+ instructions:
+ isRecord(question) && typeof question.instructions === "string"
+ ? question.instructions
+ : "",
+ };
+ const confidence =
+ typeof typesafe.confidence === "number" ? typesafe.confidence : null;
+
+ switch (typesafe.type) {
+ case "choice":
+ return [
+ {
+ ...common,
+ type: "choice",
+ choice: String(score.value ?? typesafe.choice ?? ""),
+ probabilities: toProbabilities(typesafe.probabilities),
+ confidence,
+ },
+ ];
+ case "score": {
+ const legend = isRecord(typesafe.legend) ? typesafe.legend : {};
+ return [
+ {
+ ...common,
+ type: "score",
+ score: Number(score.value ?? 0),
+ levels: Object.keys(legend)
+ .sort((a, b) => Number(a) - Number(b))
+ .map((level) => String(legend[level] ?? "")),
+ probabilities: toProbabilities(typesafe.probabilities),
+ confidence,
+ },
+ ];
+ }
+ case "noul":
+ return [
+ { ...common, type: "noul", probability: Number(score.value ?? 0) },
+ ];
+ default:
+ return [];
+ }
+ });
+}
diff --git a/web/src/features/evals/v2/fns/evaluatorTesting/toTestResultPanelState.ts b/web/src/features/evals/v2/fns/evaluatorTesting/toTestResultPanelState.ts
index 0b153d5004..0819305e83 100644
--- a/web/src/features/evals/v2/fns/evaluatorTesting/toTestResultPanelState.ts
+++ b/web/src/features/evals/v2/fns/evaluatorTesting/toTestResultPanelState.ts
@@ -1,5 +1,6 @@
import type { EvalTemplateType } from "@langfuse/shared";
import type { TestResultPanelState } from "@/src/features/evals/v2/components/Evaluators/Testing/components/TestResultPanelView/TestResultPanelView";
+import { toDecisionModelResults } from "@/src/features/evals/v2/fns/evaluatorTesting/toDecisionModelResults";
export function toTestResultPanelState(params: {
type: EvalTemplateType;
@@ -27,6 +28,13 @@ export function toTestResultPanelState(params: {
};
}
+ if (params.type === "DECISION_MODEL") {
+ return {
+ status: "decision-success",
+ results: toDecisionModelResults(response),
+ };
+ }
+
if (params.type === "CODE") {
const scores = Array.isArray(response.scores) ? response.scores : [];
return {
diff --git a/web/src/features/evals/v2/fns/evaluators/decisionModelQuestions.ts b/web/src/features/evals/v2/fns/evaluators/decisionModelQuestions.ts
new file mode 100644
index 0000000000..958f99ef2e
--- /dev/null
+++ b/web/src/features/evals/v2/fns/evaluators/decisionModelQuestions.ts
@@ -0,0 +1,175 @@
+import {
+ DECISION_MODEL_LIMITS,
+ DecisionModelQuestionType,
+ DecisionModelQuestionsSchema,
+ type DecisionModelEntry,
+ type DecisionModelQuestion,
+ type DecisionModelQuestions,
+} from "@langfuse/shared";
+
+import type {
+ DecisionModelQuestionDraft,
+ DecisionModelQuestionDraftErrors,
+} from "@/src/features/evals/v2/types/decisionModel";
+import { safeRandomUUID } from "@/src/utils/safe-random-uuid";
+
+/** The editor authors plain text; persisted JSON entries are shown serialized. */
+function entryToText(entry: DecisionModelEntry | null | undefined): string {
+ if (entry == null) return "";
+ return typeof entry === "string" ? entry : JSON.stringify(entry);
+}
+
+export function createEmptyQuestion(
+ type: DecisionModelQuestionType = DecisionModelQuestionType.CHOICE,
+): DecisionModelQuestionDraft {
+ return {
+ id: safeRandomUUID(),
+ type,
+ scoreName: "",
+ instructions: "",
+ options: [
+ { value: "", description: "" },
+ { value: "", description: "" },
+ ],
+ levels: [{ description: "" }, { description: "" }],
+ criteria: { true: "", false: "" },
+ };
+}
+
+/** Reads persisted questions into editor drafts; unparsable input yields none. */
+export function questionsToDrafts(
+ questions: unknown,
+): DecisionModelQuestionDraft[] {
+ const parsed = DecisionModelQuestionsSchema.safeParse(questions);
+ if (!parsed.success) return [];
+ return parsed.data.map((question) => {
+ const empty = createEmptyQuestion(question.type);
+ const draft: DecisionModelQuestionDraft = {
+ ...empty,
+ id: question.id,
+ scoreName: question.scoreName,
+ instructions: entryToText(question.instructions),
+ };
+ switch (question.type) {
+ case DecisionModelQuestionType.CHOICE:
+ draft.options = question.options.map((option) => ({
+ value: option.value,
+ description: entryToText(option.description),
+ }));
+ break;
+ case DecisionModelQuestionType.SCORE:
+ draft.levels = question.levels.map((level) => ({
+ description: entryToText(level.description),
+ }));
+ break;
+ case DecisionModelQuestionType.NOUL:
+ draft.criteria = {
+ true: entryToText(question.criteria?.true),
+ false: entryToText(question.criteria?.false),
+ };
+ break;
+ }
+ return draft;
+ });
+}
+
+/**
+ * Field-level problems per question, keyed by question id. Mirrors what the
+ * server schema rejects so the form can point at the offending field.
+ */
+export function getQuestionDraftErrors(
+ drafts: DecisionModelQuestionDraft[],
+): Record<string, DecisionModelQuestionDraftErrors> {
+ const scoreNameCounts = new Map<string, number>();
+ for (const draft of drafts) {
+ const name = draft.scoreName.trim();
+ if (name) scoreNameCounts.set(name, (scoreNameCounts.get(name) ?? 0) + 1);
+ }
+
+ const errors: Record<string, DecisionModelQuestionDraftErrors> = {};
+ for (const draft of drafts) {
+ const own: DecisionModelQuestionDraftErrors = {};
+ if (!draft.instructions.trim()) {
+ own.instructions = "Every question needs instructions.";
+ }
+ const scoreName = draft.scoreName.trim();
+ if (!scoreName) {
+ own.scoreName = "Every question needs a score name.";
+ } else if ((scoreNameCounts.get(scoreName) ?? 0) > 1) {
+ own.scoreName = `Another question already writes “${scoreName}”.`;
+ }
+ if (draft.type === DecisionModelQuestionType.CHOICE) {
+ const values = draft.options.map((option) => option.value.trim());
+ if (values.length < DECISION_MODEL_LIMITS.minChoiceOptions) {
+ own.options = `Add at least ${DECISION_MODEL_LIMITS.minChoiceOptions} options.`;
+ } else if (values.some((value) => !value)) {
+ own.options = "Every option needs a label.";
+ } else if (new Set(values).size !== values.length) {
+ own.options = "Option labels must be unique.";
+ }
+ }
+ if (draft.type === DecisionModelQuestionType.SCORE) {
+ const descriptions = draft.levels.map((level) =>
+ level.description.trim(),
+ );
+ if (descriptions.length < DECISION_MODEL_LIMITS.minScoreLevels) {
+ own.levels = `Add at least ${DECISION_MODEL_LIMITS.minScoreLevels} levels.`;
+ } else if (descriptions.some((description) => !description)) {
+ own.levels = "Every level needs a description.";
+ }
+ }
+ if (Object.keys(own).length > 0) errors[draft.id] = own;
+ }
+ return errors;
+}
+
+/** Persistable questions, or null while any draft is incomplete. */
+export function draftsToQuestions(
+ drafts: DecisionModelQuestionDraft[],
+): DecisionModelQuestions | null {
+ if (
+ drafts.length === 0 ||
+ Object.keys(getQuestionDraftErrors(drafts)).length > 0
+ ) {
+ return null;
+ }
+ const questions = drafts.map((draft): DecisionModelQuestion => {
+ const base = {
+ id: draft.id,
+ scoreName: draft.scoreName.trim(),
+ instructions: draft.instructions.trim(),
+ };
+ switch (draft.type) {
+ case DecisionModelQuestionType.CHOICE:
+ return {
+ ...base,
+ type: draft.type,
+ options: draft.options.map((option) => ({
+ value: option.value.trim(),
+ description: option.description.trim() || undefined,
+ })),
+ };
+ case DecisionModelQuestionType.SCORE:
+ return {
+ ...base,
+ type: draft.type,
+ levels: draft.levels.map((level) => ({
+ description: level.description.trim(),
+ })),
+ };
+ case DecisionModelQuestionType.NOUL: {
+ const criteria = {
+ true: draft.criteria.true.trim() || undefined,
+ false: draft.criteria.false.trim() || undefined,
+ };
+ return {
+ ...base,
+ type: draft.type,
+ criteria: criteria.true || criteria.false ? criteria : undefined,
+ };
+ }
+ }
+ });
+ const parsed = DecisionModelQuestionsSchema.safeParse(questions);
+ return parsed.success ? parsed.data : null;
+}
diff --git a/web/src/features/evals/v2/fns/evaluators/evaluatorTypeLabel.ts b/web/src/features/evals/v2/fns/evaluators/evaluatorTypeLabel.ts
new file mode 100644
index 0000000000..4deabacb3d
--- /dev/null
+++ b/web/src/features/evals/v2/fns/evaluators/evaluatorTypeLabel.ts
@@ -0,0 +1,13 @@
+import { EvalTemplateTypeEnum, type EvalTemplateType } from "@langfuse/shared";
+
+/** Product wording for each evaluator type, shared by badges and filters. */
+export function evaluatorTypeLabel(type: EvalTemplateType): string {
+ switch (type) {
+ case EvalTemplateTypeEnum.CODE:
+ return "Code";
+ case EvalTemplateTypeEnum.DECISION_MODEL:
+ return "Decision model (experimental)";
+ case EvalTemplateTypeEnum.LLM_AS_JUDGE:
+ return "LLM as a judge";
+ }
+}
diff --git a/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.clienttest.ts b/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.clienttest.ts
index cc1fe69dab..5985ba86a8 100644
--- a/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.clienttest.ts
+++ b/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.clienttest.ts
@@ -1,4 +1,4 @@
-import { ScoreDataTypeEnum } from "@langfuse/shared";
+import { DecisionModelQuestionType, ScoreDataTypeEnum } from "@langfuse/shared";
import { describe, expect, it } from "vitest";
import { prepareEvaluatorDraft } from "./prepareEvaluatorDraft";
@@ -24,6 +24,9 @@ describe("prepareEvaluatorDraft", () => {
prepareEvaluatorDraft({
type: "LLM_AS_JUDGE",
promptMessages: [{ role: "user", content: "Judge {{output}}" }],
+ questions: [],
+ stateKeys: [],
+ name: "",
sourceCode: "",
sourceCodeLanguage: "TYPESCRIPT",
scoreOutput: {
@@ -70,6 +73,9 @@ describe("prepareEvaluatorDraft", () => {
{ role: "user", content: "Judge {{output}}" },
{ role: "system", content: "Be strict" },
],
+ questions: [],
+ stateKeys: [],
+ name: "",
sourceCode: "",
sourceCodeLanguage: "TYPESCRIPT",
scoreOutput: {
@@ -100,6 +106,9 @@ describe("prepareEvaluatorDraft", () => {
{ role: "user", content: "Judge {{output}}" },
{ role: "assistant", content: " " },
],
+ questions: [],
+ stateKeys: [],
+ name: "",
sourceCode: "",
sourceCodeLanguage: "TYPESCRIPT",
scoreOutput: {
@@ -122,4 +131,85 @@ describe("prepareEvaluatorDraft", () => {
expect(result.definition).toBeNull();
});
+
+ it("prepares a decision-model definition from questions and state", () => {
+ const base = {
+ type: "DECISION_MODEL" as const,
+ promptMessages: [],
+ questions: [
+ {
+ id: "q1",
+ type: DecisionModelQuestionType.CHOICE,
+ scoreName: "verdict",
+ instructions: "Is `output` ready to send?",
+ options: [
+ { value: "ready", description: "" },
+ { value: "not_ready", description: "Needs edits" },
+ ],
+ levels: [],
+ criteria: { true: "", false: "" },
+ },
+ ],
+ stateKeys: ["input", "output"],
+ name: "",
+ sourceCode: "",
+ sourceCodeLanguage: "TYPESCRIPT" as const,
+ scoreOutput: {
+ dataType: ScoreDataTypeEnum.NUMERIC,
+ scoreDescription: "",
+ reasoningDescription: "",
+ choices: [],
+ shouldAllowMultipleMatches: false,
+ minValue: "",
+ maxValue: "",
+ },
+ variableFields: {
+ output: { selectedColumnId: "output", jsonSelector: "$.answer" },
+ },
+ modelMode: "custom" as const,
+ selectedModel: { provider: "typesafe", model: "jev-latest" },
+ modelParams: null,
+ initialDefinition: undefined,
+ };
+
+ expect(prepareEvaluatorDraft(base).definition).toEqual({
+ type: "DECISION_MODEL",
+ questions: [
+ {
+ id: "q1",
+ type: "choice",
+ scoreName: "verdict",
+ instructions: "Is `output` ready to send?",
+ options: [
+ { value: "ready" },
+ { value: "not_ready", description: "Needs edits" },
+ ],
+ },
+ ],
+ modelConfig: { provider: "typesafe", model: "jev-latest" },
+ variableMapping: [
+ {
+ templateVariable: "input",
+ selectedColumnId: "input",
+ jsonSelector: null,
+ },
+ {
+ templateVariable: "output",
+ selectedColumnId: "output",
+ jsonSelector: "$.answer",
+ },
+ ],
+ });
+
+ // An unmapped state key blocks saving; the model would never see it.
+ expect(
+ prepareEvaluatorDraft({
+ ...base,
+ variableFields: {
+ ...base.variableFields,
+ input: { selectedColumnId: null, jsonSelector: null },
+ },
+ }).definition,
+ ).toBeNull();
+ });
});
diff --git a/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.ts b/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.ts
index 327f15cefd..aa10f81246 100644
--- a/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.ts
+++ b/web/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft.ts
@@ -3,11 +3,16 @@ import { getPromptMessagesValidationError } from "@/src/features/evals/v2/fns/pr
import { buildScoreOutputDefinition } from "@/src/features/evals/v2/fns/scoreOutput/buildScoreOutputDefinition";
import { buildEvaluatorVariableMappings } from "@/src/features/evals/v2/fns/variableMapping/buildEvaluatorVariableMappings";
import type { EvaluatorSetupStoreState } from "@/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore";
+import { draftsToQuestions } from "@/src/features/evals/v2/fns/evaluators/decisionModelQuestions";
+import { buildDecisionModelStateFields } from "@/src/features/evals/v2/fns/variableMapping/buildDecisionModelStateFields";
type EvaluatorSetupDraftState = Pick<
EvaluatorSetupStoreState,
| "type"
+ | "name"
| "promptMessages"
+ | "questions"
+ | "stateKeys"
| "sourceCode"
| "sourceCodeLanguage"
| "scoreOutput"
@@ -28,7 +33,45 @@ export function prepareEvaluatorDraft(params: EvaluatorSetupDraftState) {
promptMessages: params.promptMessages,
variableFields: params.variableFields,
})
- : [];
+ : params.type === "DECISION_MODEL"
+ ? buildDecisionModelStateFields({
+ stateKeys: params.stateKeys,
+ variableFields: params.variableFields,
+ })
+ : [];
+
+ if (params.type === "DECISION_MODEL") {
+ const questions = draftsToQuestions(params.questions);
+ // Every state key has to resolve to data, or the state the model sees
+ // would silently miss a field the questions refer to.
+ const variableMapping = mappings.flatMap(({ variable, fieldState }) =>
+ fieldState.selectedColumnId
+ ? [
+ {
+ templateVariable: variable,
+ selectedColumnId: fieldState.selectedColumnId,
+ jsonSelector: fieldState.jsonSelector,
+ },
+ ]
+ : [],
+ );
+ const stateComplete =
+ mappings.length > 0 && variableMapping.length === mappings.length;
+ const definition =
+ questions && params.selectedModel && stateComplete
+ ? {
+ type: params.type,
+ questions,
+ modelConfig: {
+ provider: params.selectedModel.provider,
+ model: params.selectedModel.model,
+ },
+ variableMapping,
+ }
+ : null;
+ return { definition, mappings };
+ }
+
const definition =
params.type === "LLM_AS_JUDGE"
? outputDefinition && promptMessagesValid
diff --git a/web/src/features/evals/v2/fns/moveItem.ts b/web/src/features/evals/v2/fns/moveItem.ts
new file mode 100644
index 0000000000..5929716017
--- /dev/null
+++ b/web/src/features/evals/v2/fns/moveItem.ts
@@ -0,0 +1,16 @@
+/** Returns a copy of `items` with the element at `from` moved to `to`. */
+export function moveItem<T>(items: T[], from: number, to: number): T[] {
+ if (
+ from === to ||
+ from < 0 ||
+ to < 0 ||
+ from >= items.length ||
+ to >= items.length
+ ) {
+ return items;
+ }
+ const next = [...items];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item!);
+ return next;
+}
diff --git a/web/src/features/evals/v2/fns/variableMapping/buildDecisionModelStateFields.ts b/web/src/features/evals/v2/fns/variableMapping/buildDecisionModelStateFields.ts
new file mode 100644
index 0000000000..9a7cc62e86
--- /dev/null
+++ b/web/src/features/evals/v2/fns/variableMapping/buildDecisionModelStateFields.ts
@@ -0,0 +1,19 @@
+import { inferDefaultMapping } from "@/src/features/evals/utils/evaluator-form-utils";
+import type { VariableFieldState } from "@/src/features/evals/v2/types/variableMapping";
+
+/** The decision-model state, one mapping per key in declared order. */
+export function buildDecisionModelStateFields({
+ stateKeys,
+ variableFields,
+}: {
+ stateKeys: string[];
+ variableFields: Record<string, VariableFieldState>;
+}) {
+ return stateKeys.map((variable) => ({
+ variable,
+ fieldState: variableFields[variable] ?? {
+ selectedColumnId: inferDefaultMapping(variable).selectedColumnId ?? null,
+ jsonSelector: null,
+ },
+ }));
+}
diff --git a/web/src/features/evals/v2/pages/EvaluatorDetailPage.tsx b/web/src/features/evals/v2/pages/EvaluatorDetailPage.tsx
index 41fcf50640..25e4385658 100644
--- a/web/src/features/evals/v2/pages/EvaluatorDetailPage.tsx
+++ b/web/src/features/evals/v2/pages/EvaluatorDetailPage.tsx
@@ -1,9 +1,47 @@
import { useRouter } from "next/router";
+import type { EvalTemplateType } from "@langfuse/shared";
import { Skeleton } from "@/src/components/ui/skeleton";
-import { api } from "@/src/utils/api";
+import { api, type RouterOutputs } from "@/src/utils/api";
import type { NormalizedEvaluatorDefinition } from "../server/evaluators/evaluatorTypes";
import { EvaluatorSetupPage } from "./EvaluatorSetupPage";
+type EvaluatorVersionRow = RouterOutputs["evalsV2"]["get"]["versions"][number];
+
+// Stored JSON columns are typed loosely; the setup page owns their parsing.
+function toSetupDefinition(
+ type: EvalTemplateType,
+ latest: EvaluatorVersionRow,
+): NormalizedEvaluatorDefinition {
+ switch (type) {
+ case "LLM_AS_JUDGE":
+ return {
+ type,
+ promptMessages: latest.promptMessages!,
+ provider: latest.provider,
+ model: latest.model,
+ modelParams: latest.modelParams,
+ vars: latest.vars,
+ variableMapping: latest.variableMapping,
+ outputDefinition: latest.outputDefinition,
+ } as NormalizedEvaluatorDefinition;
+ case "DECISION_MODEL":
+ return {
+ type,
+ questions: latest.questions,
+ provider: latest.provider ?? "",
+ model: latest.model ?? "",
+ vars: latest.vars,
+ variableMapping: latest.variableMapping,
+ } as NormalizedEvaluatorDefinition;
+ case "CODE":
+ return {
+ type,
+ sourceCode: latest.sourceCode ?? "",
+ sourceCodeLanguage: latest.sourceCodeLanguage ?? "TYPESCRIPT",
+ };
+ }
+}
+
export default function EvaluatorDetailPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
@@ -21,24 +59,7 @@ export default function EvaluatorDetailPage() {
}
const latest = evaluator.data.versions[0];
- const definition =
- evaluator.data.type === "LLM_AS_JUDGE"
- ? {
- type: "LLM_AS_JUDGE" as const,
- promptMessages: latest.promptMessages!,
- provider: latest.provider,
- model: latest.model,
- modelParams: latest.modelParams,
- vars: latest.vars,
- variableMapping: latest.variableMapping,
- outputDefinition: latest.outputDefinition,
- }
- : {
- type: "CODE" as const,
- sourceCode: latest.sourceCode ?? "",
- sourceCodeLanguage: latest.sourceCodeLanguage ?? "TYPESCRIPT",
- };
-
+ const definition = toSetupDefinition(evaluator.data.type, latest);
return (
<EvaluatorSetupPage
mode="edit"
@@ -49,7 +70,7 @@ export default function EvaluatorDetailPage() {
name: evaluator.data.name,
description: evaluator.data.description,
type: evaluator.data.type,
- definition: definition as NormalizedEvaluatorDefinition,
+ definition,
blockedAt: evaluator.data.blockedAt,
blockReason: evaluator.data.blockReason,
blockMessage: evaluator.data.blockMessage,
diff --git a/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx b/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
index 0543aecb89..cdab9b7c57 100644
--- a/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
+++ b/web/src/features/evals/v2/pages/EvaluatorSetupPage.tsx
@@ -28,6 +28,7 @@ import { EvaluatorSetupFooter } from "@/src/features/evals/v2/components/Evaluat
import { SampleObservationSelectorContainer } from "@/src/features/evals/v2/components/EvaluatorTestPanel/components/SampleObservationSelectorContainer/SampleObservationSelectorContainer";
import { EvaluatorTestPanelContainer } from "@/src/features/evals/v2/components/EvaluatorTestPanel/components/EvaluatorTestPanelContainer/EvaluatorTestPanelContainer";
import { prepareEvaluatorDraft } from "@/src/features/evals/v2/fns/evaluators/prepareEvaluatorDraft";
+import { draftsToQuestions } from "@/src/features/evals/v2/fns/evaluators/decisionModelQuestions";
import type { NormalizedEvaluatorDefinition } from "../server/evaluators/evaluatorTypes";
import { api } from "@/src/utils/api";
import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
@@ -109,6 +110,22 @@ export function getEvaluatorVersionDefinition(
{ type: "LLM_AS_JUDGE" }
>;
+ if (version.type === "DECISION_MODEL") {
+ type DecisionModelDefinition = Extract<
+ NormalizedEvaluatorDefinition,
+ { type: "DECISION_MODEL" }
+ >;
+ return {
+ type: version.type,
+ questions: version.questions as DecisionModelDefinition["questions"],
+ provider: version.provider ?? "",
+ model: version.model ?? "",
+ vars: version.vars,
+ variableMapping:
+ version.variableMapping as DecisionModelDefinition["variableMapping"],
+ };
+ }
+
return {
type: version.type,
promptMessages: version.promptMessages!,
@@ -181,14 +198,15 @@ export function EvaluatorSetupPage(
projectId,
evaluatorId: initialEvaluator?.id ?? null,
});
- const scoreDataType = initialEvaluator
- ? initialEvaluator.definition.type === "LLM_AS_JUDGE"
- ? toScoreOutputFormState(initialEvaluator.definition.outputDefinition)
- .dataType
- : getFirstCodeEvaluatorScoreDataType(
+ const scoreDataType =
+ initialEvaluator?.definition.type === "CODE"
+ ? getFirstCodeEvaluatorScoreDataType(
initialEvaluator.definition.sourceCode,
)
- : undefined;
+ : initialEvaluator?.definition.type === "LLM_AS_JUDGE"
+ ? toScoreOutputFormState(initialEvaluator.definition.outputDefinition)
+ .dataType
+ : undefined;
const projectDefaultModel = useProjectDefaultModel({
projectId,
source: "editor",
@@ -296,13 +314,14 @@ export function EvaluatorSetupPage(
sourceCode: version.sourceCode,
sourceCodeLanguage: version.sourceCodeLanguage,
promptMessages:
- initialEvaluator?.type === "LLM_AS_JUDGE" ? version.promptMessages : null,
+ initialEvaluator?.type === "CODE" ? null : version.promptMessages,
provider: version.provider,
model: version.model,
modelParams: version.modelParams as EvaluatorVersion["modelParams"],
vars: version.vars,
variableMapping: version.variableMapping,
outputDefinition: version.outputDefinition,
+ questions: version.questions,
createdByUser: version.createdByUser,
}));
@@ -362,9 +381,17 @@ export function EvaluatorSetupPage(
const getSuggestionDefinition = () => {
const state = evaluatorSetupStore.getState();
- return state.type === "LLM_AS_JUDGE"
- ? { type: state.type, promptMessages: state.promptMessages }
- : { type: state.type, sourceCode: state.sourceCode };
+ switch (state.type) {
+ case "LLM_AS_JUDGE":
+ return { type: state.type, promptMessages: state.promptMessages };
+ case "CODE":
+ return { type: state.type, sourceCode: state.sourceCode };
+ case "DECISION_MODEL":
+ return {
+ type: state.type,
+ questions: draftsToQuestions(state.questions) ?? [],
+ };
+ }
};
const generateNameSuggestion = async () => {
@@ -574,7 +601,11 @@ export function EvaluatorSetupPage(
type: state.type,
defaultVariableMapping: observationVariableMappingList
.catch([])
- .parse(definition.variableMapping),
+ .parse(
+ definition.type === "LLM_AS_JUDGE"
+ ? definition.variableMapping
+ : undefined,
+ ),
sampleFilter: state.sampleFilter,
hasCompletedTestCall,
testRunCostUsd: lastTestRunCostUsd,
diff --git a/web/src/features/evals/v2/pages/NewEvaluatorPage.tsx b/web/src/features/evals/v2/pages/NewEvaluatorPage.tsx
index 6d76f7df9f..beb64a5f35 100644
--- a/web/src/features/evals/v2/pages/NewEvaluatorPage.tsx
+++ b/web/src/features/evals/v2/pages/NewEvaluatorPage.tsx
@@ -9,7 +9,9 @@ import { EvaluatorSetupPage } from "./EvaluatorSetupPage";
function requestedEvaluatorType(value: string | string[] | undefined) {
return value === EvalTemplateTypeEnum.CODE
? EvalTemplateTypeEnum.CODE
- : EvalTemplateTypeEnum.LLM_AS_JUDGE;
+ : value === EvalTemplateTypeEnum.DECISION_MODEL
+ ? EvalTemplateTypeEnum.DECISION_MODEL
+ : EvalTemplateTypeEnum.LLM_AS_JUDGE;
}
export default function NewEvaluatorPage() {
diff --git a/web/src/features/evals/v2/server/evaluators/decisionModelAccess.ts b/web/src/features/evals/v2/server/evaluators/decisionModelAccess.ts
new file mode 100644
index 0000000000..57696cbd66
--- /dev/null
+++ b/web/src/features/evals/v2/server/evaluators/decisionModelAccess.ts
@@ -0,0 +1,35 @@
+import { EvalTemplateType, ForbiddenError } from "@langfuse/shared";
+import type { Session } from "next-auth";
+
+import { env } from "@/src/env.mjs";
+import { getContextualFeatureFlags } from "@/src/features/feature-flags/utils";
+
+/**
+ * Server-side counterpart of the `decisionModelEvaluators` flag check in the
+ * UI: the experimental type is only accepted for admins, deployments with
+ * experimental features enabled, or users/organizations carrying the flag.
+ */
+function isDecisionModelEvaluatorEnabled(params: {
+ session: Session;
+ projectId: string;
+}): boolean {
+ if (env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true") return true;
+ if (params.session.user?.admin === true) return true;
+ return (
+ getContextualFeatureFlags(params.session.user, {
+ projectId: params.projectId,
+ })?.decisionModelEvaluators === true
+ );
+}
+
+export function assertDecisionModelEvaluatorAllowed(params: {
+ session: Session;
+ projectId: string;
+ definition: { type: EvalTemplateType };
+}) {
+ if (params.definition.type !== EvalTemplateType.DECISION_MODEL) return;
+ if (isDecisionModelEvaluatorEnabled(params)) return;
+ throw new ForbiddenError(
+ "Decision-model evaluators are experimental and not enabled for this project.",
+ );
+}
diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorRepository.ts b/web/src/features/evals/v2/server/evaluators/evaluatorRepository.ts
index bae99b0597..fa16130e65 100644
--- a/web/src/features/evals/v2/server/evaluators/evaluatorRepository.ts
+++ b/web/src/features/evals/v2/server/evaluators/evaluatorRepository.ts
@@ -85,8 +85,9 @@ function versionData(
: (definition.variableMapping as Prisma.InputJsonValue),
};
- return definition.type === EvalTemplateType.LLM_AS_JUDGE
- ? {
+ switch (definition.type) {
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return {
...commonVersionData,
prompt: definition.prompt,
promptMessages: definition.promptMessages,
@@ -98,12 +99,22 @@ function versionData(
: (definition.modelParams as Prisma.InputJsonValue),
vars: definition.vars,
outputDefinition: definition.outputDefinition as Prisma.InputJsonValue,
- }
- : {
+ };
+ case EvalTemplateType.DECISION_MODEL:
+ return {
+ ...commonVersionData,
+ provider: definition.provider,
+ model: definition.model,
+ vars: definition.vars,
+ questions: definition.questions as Prisma.InputJsonValue,
+ };
+ case EvalTemplateType.CODE:
+ return {
...commonVersionData,
sourceCode: definition.sourceCode,
sourceCodeLanguage: definition.sourceCodeLanguage,
};
+ }
}
type EvaluatorModelFilter = Extract<
@@ -129,6 +140,8 @@ async function evaluatorIdsMatchingModelFilters(params: {
CASE
WHEN evaluator.type = 'LLM_AS_JUDGE'
THEN COALESCE(latest_version.model, default_model.model)
+ WHEN evaluator.type = 'DECISION_MODEL'
+ THEN latest_version.model
ELSE NULL
END
`;
@@ -318,23 +331,41 @@ export async function listEvaluators(params: {
hasActiveRules: assignments.some(
({ evaluationRule }) => evaluationRule.status === "ACTIVE",
),
- effectiveModel:
- evaluator.type === EvalTemplateType.LLM_AS_JUDGE
- ? (evaluator.versions[0]?.model ?? defaultModel?.model ?? null)
- : null,
+ effectiveModel: getEffectiveModel(evaluator, defaultModel?.model),
})),
totalItems,
};
}
+function getEffectiveModel(
+ evaluator: {
+ type: EvalTemplateType;
+ versions: Array<{ model: string | null }>;
+ },
+ defaultModel: string | null | undefined,
+): string | null {
+ switch (evaluator.type) {
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return evaluator.versions[0]?.model ?? defaultModel ?? null;
+ case EvalTemplateType.DECISION_MODEL:
+ return evaluator.versions[0]?.model ?? null;
+ case EvalTemplateType.CODE:
+ return null;
+ }
+}
+
export async function listEvaluatorsCursor(params: {
prisma: PrismaClient;
projectId: string;
limit: number;
cursor?: { createdAt: Date; id: string };
search?: string;
+ types?: EvalTemplateType[];
}) {
- const baseWhere = await evaluatorWhere(params);
+ const baseWhere: Prisma.EvaluatorWhereInput = {
+ ...(await evaluatorWhere(params)),
+ ...(params.types ? { type: { in: params.types } } : {}),
+ };
const where: Prisma.EvaluatorWhereInput = params.cursor
? {
AND: [
@@ -415,9 +446,8 @@ export async function listEvaluatorFilterOptions(params: {
].sort(),
model: [
...new Set(
- evaluators.flatMap(({ type, versions }) => {
- if (type !== EvalTemplateType.LLM_AS_JUDGE) return [];
- const model = versions[0]?.model ?? defaultModel?.model;
+ evaluators.flatMap((evaluator) => {
+ const model = getEffectiveModel(evaluator, defaultModel?.model);
return model ? [model] : [];
}),
),
diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorRouter.ts b/web/src/features/evals/v2/server/evaluators/evaluatorRouter.ts
index 9c5e014eea..3de11041a6 100644
--- a/web/src/features/evals/v2/server/evaluators/evaluatorRouter.ts
+++ b/web/src/features/evals/v2/server/evaluators/evaluatorRouter.ts
@@ -20,6 +20,7 @@ import {
SuggestEvaluatorTextSchema,
UpdateEvaluatorSchema,
} from "./evaluatorTypes";
+import { assertDecisionModelEvaluatorAllowed } from "./decisionModelAccess";
import { EvaluatorService } from "./evaluatorService";
import { ruleRouter } from "../rules/ruleRouter";
import { getActivationCostEstimates } from "./activationCostService";
@@ -198,6 +199,11 @@ export const evaluatorRouter = createTRPCRouter({
projectId: ctx.session.projectId,
scope: "evaluator:CUD",
});
+ assertDecisionModelEvaluatorAllowed({
+ session: ctx.session,
+ projectId: ctx.session.projectId,
+ definition: input.definition,
+ });
const service = serviceForContext(ctx);
return service.create(
{ ...input, projectId: ctx.session.projectId },
@@ -213,6 +219,11 @@ export const evaluatorRouter = createTRPCRouter({
projectId: ctx.session.projectId,
scope: "evaluator:CUD",
});
+ assertDecisionModelEvaluatorAllowed({
+ session: ctx.session,
+ projectId: ctx.session.projectId,
+ definition: input.definition,
+ });
const service = serviceForContext(ctx);
return service.update(
{ ...input, projectId: ctx.session.projectId },
@@ -271,6 +282,11 @@ export const evaluatorRouter = createTRPCRouter({
projectId: ctx.session.projectId,
scope: "evaluator:CUD",
});
+ assertDecisionModelEvaluatorAllowed({
+ session: ctx.session,
+ projectId: ctx.session.projectId,
+ definition: input.definition,
+ });
return serviceForContext(ctx).testEvaluator({
orgId: ctx.session.orgId,
projectId: ctx.session.projectId,
diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorService.ts b/web/src/features/evals/v2/server/evaluators/evaluatorService.ts
index 7329e1a150..69c71cf413 100644
--- a/web/src/features/evals/v2/server/evaluators/evaluatorService.ts
+++ b/web/src/features/evals/v2/server/evaluators/evaluatorService.ts
@@ -47,7 +47,10 @@ import {
EvaluatorModelConfigurationError,
EvaluatorVersionConflictError,
} from "./evaluatorErrors";
-import { assertEvaluatorConfigurationValid } from "./evaluatorValidation";
+import {
+ assertEvaluatorConfigurationValid,
+ getDecisionModelConfigurationError,
+} from "./evaluatorValidation";
type SuggestEvaluatorTextParams = {
projectId: string;
@@ -59,6 +62,10 @@ type SuggestEvaluatorTextParams = {
"promptMessages"
>
| { sourceCode: string }
+ | Pick<
+ Extract<EvaluatorDefinition, { type: "DECISION_MODEL" }>,
+ "questions"
+ >
);
};
@@ -112,6 +119,10 @@ function prepareEvaluatorDefinitionForPersistence(
};
}
+ if (definition.type === EvalTemplateType.DECISION_MODEL) {
+ return definition;
+ }
+
return {
...definition,
prompt: getLegacyEvaluatorPrompt(definition.promptMessages),
@@ -164,6 +175,7 @@ export class EvaluatorService {
limit: number;
cursor?: { createdAt: Date; id: string };
search?: string;
+ types?: EvalTemplateType[];
}) {
const page = await repository.listEvaluatorsCursor({
prisma: this.prisma,
@@ -488,22 +500,29 @@ export class EvaluatorService {
if (!version)
throw new LangfuseNotFoundError("Evaluator version not found");
const definition = toEvaluatorDefinition(evaluator.type, version);
- if (definition.type !== EvalTemplateType.LLM_AS_JUDGE) {
+ if (definition.type === EvalTemplateType.CODE) {
throw new EvaluatorConfigurationError(
- "Only LLM evaluators can be reactivated with a model test.",
+ "Only LLM and decision-model evaluators can be reactivated with a model test.",
);
}
- const error = await getEvaluatorDefinitionPreflightError({
- projectId,
- template: {
- name: evaluator.name,
- type: definition.type,
- provider: definition.provider,
- model: definition.model,
- modelParams: definition.modelParams,
- outputDefinition: definition.outputDefinition,
- },
- });
+ const error =
+ definition.type === EvalTemplateType.DECISION_MODEL
+ ? await getDecisionModelConfigurationError({
+ projectId,
+ name: evaluator.name,
+ definition,
+ })
+ : await getEvaluatorDefinitionPreflightError({
+ projectId,
+ template: {
+ name: evaluator.name,
+ type: definition.type,
+ provider: definition.provider,
+ model: definition.model,
+ modelParams: definition.modelParams,
+ outputDefinition: definition.outputDefinition,
+ },
+ });
if (error) {
const reason = getBlockReasonForInvalidModelConfig({
templateProvider: definition.provider,
@@ -915,36 +934,63 @@ export function toEvaluatorDefinition(
outputDefinition: unknown;
sourceCode: string | null;
sourceCodeLanguage: "PYTHON" | "TYPESCRIPT" | null;
+ questions?: unknown;
},
): NormalizedEvaluatorDefinition {
- const definition = EvaluatorDefinitionSchema.parse(
- type === EvalTemplateType.LLM_AS_JUDGE
- ? {
- type,
- promptMessages: reconcileEvaluatorPromptMessages({
- prompt: version.prompt,
- promptMessages: version.promptMessages,
- }),
- provider: version.provider,
- model: version.model,
- modelParams: version.modelParams,
- vars: version.vars,
- variableMapping: version.variableMapping,
- outputDefinition: version.outputDefinition,
- }
- : {
- type,
- sourceCode: version.sourceCode ?? "",
- sourceCodeLanguage: version.sourceCodeLanguage ?? "PYTHON",
- },
+ return EvaluatorDefinitionSchema.parse(
+ toEvaluatorDefinitionInput(type, version),
);
- return definition;
+}
+
+function toEvaluatorDefinitionInput(
+ type: EvalTemplateType,
+ version: Parameters<typeof toEvaluatorDefinition>[1],
+) {
+ switch (type) {
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return {
+ type,
+ promptMessages: reconcileEvaluatorPromptMessages({
+ prompt: version.prompt,
+ promptMessages: version.promptMessages,
+ }),
+ provider: version.provider,
+ model: version.model,
+ modelParams: version.modelParams,
+ vars: version.vars,
+ variableMapping: version.variableMapping,
+ outputDefinition: version.outputDefinition,
+ };
+ case EvalTemplateType.DECISION_MODEL:
+ return {
+ type,
+ questions: version.questions,
+ provider: version.provider ?? "",
+ model: version.model ?? "",
+ vars: version.vars,
+ variableMapping: version.variableMapping,
+ };
+ case EvalTemplateType.CODE:
+ return {
+ type,
+ sourceCode: version.sourceCode ?? "",
+ sourceCodeLanguage: version.sourceCodeLanguage ?? "PYTHON",
+ };
+ }
}
function getSuggestionDefinitionText(params: SuggestEvaluatorTextParams) {
- return "promptMessages" in params.definition
- ? getLegacyEvaluatorPrompt(params.definition.promptMessages)
- : params.definition.sourceCode;
+ if ("promptMessages" in params.definition) {
+ return getLegacyEvaluatorPrompt(params.definition.promptMessages);
+ }
+ if ("sourceCode" in params.definition) return params.definition.sourceCode;
+ return params.definition.questions
+ .map((question) =>
+ typeof question.instructions === "string"
+ ? question.instructions
+ : JSON.stringify(question.instructions),
+ )
+ .join("\n\n");
}
async function defaultNameGenerator(
diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorTypes.ts b/web/src/features/evals/v2/server/evaluators/evaluatorTypes.ts
index fd48167b2f..404d9ce900 100644
--- a/web/src/features/evals/v2/server/evaluators/evaluatorTypes.ts
+++ b/web/src/features/evals/v2/server/evaluators/evaluatorTypes.ts
@@ -1,5 +1,7 @@
/* eslint-disable no-nested-ternary */
import {
+ DecisionModelQuestionsSchema,
+ DecisionModelStateKeySchema,
EvalOutputDefinitionSchema,
EvalTemplateType,
EvaluatorPromptMessagesSchema,
@@ -9,6 +11,7 @@ import {
PersistedEvalOutputDefinitionSchema,
ZodModelConfig,
jsonSchema,
+ observationVariableMappingList,
paginationLimitZod,
singleFilterList,
type ObservationVariableMapping,
@@ -69,9 +72,25 @@ export const CodeEvaluatorDefinitionSchema = z.object({
variableMapping: z.never().optional(),
});
+/**
+ * Decision-model evaluators (experimental): the state is the JSON object
+ * built from the variable mapping (key → extractor), `questions` are the
+ * typed questions asked about it, and each question writes its own score.
+ * The model connection is always explicit; there is no project default.
+ */
+const DecisionModelEvaluatorDefinitionSchema =
+ EvaluatorVersionBaseSchema.extend({
+ type: z.literal(EvalTemplateType.DECISION_MODEL),
+ questions: DecisionModelQuestionsSchema,
+ provider: z.string().min(1),
+ model: z.string().min(1),
+ vars: z.array(DecisionModelStateKeySchema),
+ });
+
export const EvaluatorDefinitionSchema = z.discriminatedUnion("type", [
LlmEvaluatorDefinitionSchema,
CodeEvaluatorDefinitionSchema,
+ DecisionModelEvaluatorDefinitionSchema,
]);
export const EvaluatorModelConfigSchema = z.object({
@@ -87,32 +106,54 @@ const LlmEvaluatorDefinitionInputSchema = EvaluatorVersionBaseSchema.extend({
outputDefinition: EvalOutputDefinitionSchema,
});
+const DecisionModelEvaluatorDefinitionInputSchema = z.object({
+ type: z.literal(EvalTemplateType.DECISION_MODEL),
+ questions: DecisionModelQuestionsSchema,
+ modelConfig: EvaluatorModelConfigSchema.pick({ provider: true, model: true }),
+ /** The state: one entry per key. Required, unlike LLM judges. */
+ variableMapping: observationVariableMappingList.min(1),
+});
+
export const EvaluatorDefinitionInputSchema = z
.discriminatedUnion("type", [
LlmEvaluatorDefinitionInputSchema,
CodeEvaluatorDefinitionSchema,
+ DecisionModelEvaluatorDefinitionInputSchema,
])
- .transform(
- (definition): z.infer<typeof EvaluatorDefinitionSchema> =>
- definition.type === EvalTemplateType.CODE
- ? definition
- : {
- type: EvalTemplateType.LLM_AS_JUDGE,
- promptMessages: definition.promptMessages,
- provider: definition.modelConfig?.provider ?? null,
- model: definition.modelConfig?.model ?? null,
- modelParams: definition.modelConfig?.modelParams ?? null,
- vars: [
- ...new Set(
- definition.promptMessages.flatMap(({ content }) =>
- extractVariables(content),
- ),
+ .transform((definition): z.infer<typeof EvaluatorDefinitionSchema> => {
+ switch (definition.type) {
+ case EvalTemplateType.CODE:
+ return definition;
+ case EvalTemplateType.DECISION_MODEL:
+ return {
+ type: EvalTemplateType.DECISION_MODEL,
+ questions: definition.questions,
+ provider: definition.modelConfig.provider,
+ model: definition.modelConfig.model,
+ vars: definition.variableMapping.map(
+ ({ templateVariable }) => templateVariable,
+ ),
+ variableMapping: definition.variableMapping,
+ };
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return {
+ type: EvalTemplateType.LLM_AS_JUDGE,
+ promptMessages: definition.promptMessages,
+ provider: definition.modelConfig?.provider ?? null,
+ model: definition.modelConfig?.model ?? null,
+ modelParams: definition.modelConfig?.modelParams ?? null,
+ vars: [
+ ...new Set(
+ definition.promptMessages.flatMap(({ content }) =>
+ extractVariables(content),
),
- ],
- variableMapping: definition.variableMapping,
- outputDefinition: definition.outputDefinition,
- },
- );
+ ),
+ ],
+ variableMapping: definition.variableMapping,
+ outputDefinition: definition.outputDefinition,
+ };
+ }
+ });
export const CreateEvaluatorSchema = EvaluatorMetadataSchema.extend({
projectId: z.string(),
@@ -258,6 +299,10 @@ export const SuggestEvaluatorTextSchema = z.object({
type: z.literal(EvalTemplateType.CODE),
sourceCode: z.string().min(1),
}),
+ z.object({
+ type: z.literal(EvalTemplateType.DECISION_MODEL),
+ questions: DecisionModelQuestionsSchema,
+ }),
]),
});
@@ -270,7 +315,8 @@ export type EvaluatorDefinitionForPersistence =
})
| (Omit<Extract<EvaluatorDefinition, { type: "CODE" }>, "variableMapping"> & {
variableMapping: ObservationVariableMapping[];
- });
+ })
+ | Extract<EvaluatorDefinition, { type: "DECISION_MODEL" }>;
export type CreateEvaluatorInput = z.infer<typeof CreateEvaluatorSchema>;
export type UpdateEvaluatorInput = z.infer<typeof UpdateEvaluatorSchema>;
export type PatchEvaluatorInput = Pick<
diff --git a/web/src/features/evals/v2/server/evaluators/evaluatorValidation.ts b/web/src/features/evals/v2/server/evaluators/evaluatorValidation.ts
index 808defbe29..3b072f8157 100644
--- a/web/src/features/evals/v2/server/evaluators/evaluatorValidation.ts
+++ b/web/src/features/evals/v2/server/evaluators/evaluatorValidation.ts
@@ -4,6 +4,10 @@ import {
InvalidRequestError,
observationVariableMappingList,
} from "@langfuse/shared";
+import {
+ DefaultEvalModelService,
+ isDecisionModelAdapter,
+} from "@langfuse/shared/src/server";
import { getEvaluatorDefinitionConfigurationError } from "@/src/features/evals/server/evaluator-preflight";
import { getPromptMessagesValidationError } from "@/src/features/evals/v2/fns/promptMessages/hasInvalidSystemPromptMessage";
import {
@@ -117,6 +121,15 @@ export async function assertEvaluatorConfigurationValid(params: {
return;
}
+ if (params.definition.type === EvalTemplateType.DECISION_MODEL) {
+ await assertDecisionModelDefinitionValid({
+ projectId: params.projectId,
+ name: params.name,
+ definition: params.definition,
+ });
+ return;
+ }
+
const promptMessagesValidationError = getPromptMessagesValidationError(
params.definition.promptMessages,
);
@@ -138,6 +151,22 @@ export async function assertEvaluatorConfigurationValid(params: {
});
}
+ if (params.definition.provider !== null) {
+ const connection = await DefaultEvalModelService.fetchValidModelConfig(
+ params.projectId,
+ params.definition.provider,
+ params.definition.model ?? undefined,
+ );
+ if (
+ connection.valid &&
+ isDecisionModelAdapter(connection.config.apiKey.adapter)
+ ) {
+ throw new EvaluatorModelConfigurationError(
+ `Connection "${params.definition.provider}" is a decision-model connection and cannot be used for LLM-as-a-judge. Choose a text-generation model or switch the evaluator type to decision model.`,
+ );
+ }
+ }
+
const error = await getEvaluatorDefinitionConfigurationError({
projectId: params.projectId,
template: {
@@ -151,3 +180,44 @@ export async function assertEvaluatorConfigurationValid(params: {
});
if (error) throw new EvaluatorModelConfigurationError(error);
}
+
+export async function getDecisionModelConfigurationError(params: {
+ projectId: string;
+ name: string;
+ definition: Pick<
+ Extract<EvaluatorDefinition, { type: "DECISION_MODEL" }>,
+ "provider" | "model"
+ >;
+}): Promise<string | null> {
+ const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(
+ params.projectId,
+ params.definition.provider,
+ params.definition.model,
+ );
+ if (!modelConfig.valid) {
+ return `No decision-model connection found for evaluator "${params.name}". ${modelConfig.error}. Add a TypeSafe connection under Settings → LLM Connections (/project/${params.projectId}/settings/llm-connections) first.`;
+ }
+ if (!isDecisionModelAdapter(modelConfig.config.apiKey.adapter)) {
+ return `Connection "${params.definition.provider}" is not a decision-model connection. Decision-model evaluators need a TypeSafe connection.`;
+ }
+ return null;
+}
+
+async function assertDecisionModelDefinitionValid(params: {
+ projectId: string;
+ name: string;
+ definition: Extract<EvaluatorDefinition, { type: "DECISION_MODEL" }>;
+}) {
+ if (params.definition.vars.length === 0) {
+ throw new InvalidRequestError(
+ "Decision-model evaluators need at least one state field",
+ );
+ }
+ assertCompleteEvaluatorVariableMapping({
+ promptVariables: params.definition.vars,
+ variableMapping: params.definition.variableMapping,
+ });
+
+ const error = await getDecisionModelConfigurationError(params);
+ if (error) throw new EvaluatorModelConfigurationError(error);
+}
diff --git a/web/src/features/evals/v2/server/evaluators/testEvaluator.ts b/web/src/features/evals/v2/server/evaluators/testEvaluator.ts
index a83d722343..0cf5815c49 100644
--- a/web/src/features/evals/v2/server/evaluators/testEvaluator.ts
+++ b/web/src/features/evals/v2/server/evaluators/testEvaluator.ts
@@ -2,21 +2,26 @@ import {
getCodeEvalVariableMapping,
observationVariableMappingList,
} from "@langfuse/shared";
+import { decrypt } from "@langfuse/shared/encryption";
import {
buildEvalExecutionData,
compileLangfuseMediaMessages,
+ createTypeSafeDecisionModelClient,
createW3CTraceId,
DefaultEvalModelService,
createLLMOutput,
+ executeDecisionModelEvaluator,
executeLlmEvaluator,
extractObservationVariables,
findModel,
generateLLMText,
+ isDecisionModelAdapter,
LangfuseInternalTraceEnvironment,
mapLegacyLLMCompletionParams,
matchPricingTier,
resolveConfiguredCodeEvalDispatcher,
runCodeBasedEvaluationDispatch,
+ type DecisionModelRequest,
type ExtractedVariable,
} from "@langfuse/shared/src/server";
import { getObservationForEvalById } from "@/src/features/evals/server/getObservationForEvalById";
@@ -48,6 +53,14 @@ export async function testEvaluator(params: {
let variableMapping;
if (params.definition.type === "CODE") {
variableMapping = getCodeEvalVariableMapping();
+ } else if (params.definition.type === "DECISION_MODEL") {
+ assertCompleteEvaluatorVariableMapping({
+ promptVariables: params.definition.vars,
+ variableMapping: params.definition.variableMapping,
+ });
+ variableMapping = observationVariableMappingList.parse(
+ params.definition.variableMapping,
+ );
} else {
const llmVariableMapping = params.definition.variableMapping ?? [];
assertCompleteEvaluatorVariableMapping({
@@ -70,27 +83,110 @@ export async function testEvaluator(params: {
targetObservationId: params.observationId,
});
- const result =
- params.definition.type === "CODE"
- ? await testCodeEvaluator({
- orgId: params.orgId,
- projectId: params.projectId,
- evaluatorId: params.evaluatorId,
- definition: params.definition,
- variables,
- ...executionData,
- })
- : await testLlmEvaluator({
- projectId: params.projectId,
- evaluatorId: params.evaluatorId,
- definition: params.definition,
- variables,
- ...executionData,
- });
+ const result = await runEvaluatorTest({
+ ...params,
+ variables,
+ ...executionData,
+ });
return { ...result, durationMs: Date.now() - startedAt };
}
+async function runEvaluatorTest(params: {
+ orgId: string;
+ projectId: string;
+ evaluatorId: string;
+ definition: NormalizedEvaluatorDefinition;
+ variables: ExtractedVariable[];
+ executionMetadata: Record<string, string>;
+ evaluationContext: ReturnType<
+ typeof buildEvalExecutionData
+ >["evaluationContext"];
+}) {
+ switch (params.definition.type) {
+ case "CODE":
+ return testCodeEvaluator({ ...params, definition: params.definition });
+ case "DECISION_MODEL":
+ return testDecisionModelEvaluator({
+ projectId: params.projectId,
+ definition: params.definition,
+ variables: params.variables,
+ });
+ case "LLM_AS_JUDGE":
+ return testLlmEvaluator({ ...params, definition: params.definition });
+ }
+}
+
+async function testDecisionModelEvaluator(params: {
+ projectId: string;
+ definition: Extract<
+ NormalizedEvaluatorDefinition,
+ { type: "DECISION_MODEL" }
+ >;
+ variables: ExtractedVariable[];
+}) {
+ const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(
+ params.projectId,
+ params.definition.provider,
+ params.definition.model,
+ );
+ if (!modelConfig.valid) {
+ return { success: false as const, error: modelConfig.error };
+ }
+ if (!isDecisionModelAdapter(modelConfig.config.apiKey.adapter)) {
+ return {
+ success: false as const,
+ error: `Connection "${params.definition.provider}" is not a decision-model connection.`,
+ };
+ }
+
+ const executionTraceId = createW3CTraceId();
+ let request: DecisionModelRequest | undefined;
+ try {
+ const client = createTypeSafeDecisionModelClient({
+ apiKey: decrypt(modelConfig.config.apiKey.secretKey),
+ model: modelConfig.config.model,
+ });
+ const execution = await executeDecisionModelEvaluator({
+ variables: params.variables,
+ questions: params.definition.questions,
+ client: {
+ evaluate: (sent) => {
+ request = sent;
+ return client.evaluate(sent);
+ },
+ },
+ });
+
+ const usage = execution.evaluation.usage;
+ return {
+ success: true as const,
+ scores: execution.scores,
+ request: execution.request,
+ model: execution.evaluation.model,
+ provider: modelConfig.config.provider,
+ executionTraceId,
+ estimatedCostUsd: usage
+ ? await calculateTestRunCost({
+ projectId: params.projectId,
+ model: execution.evaluation.model,
+ usage: {
+ input: usage.inputTokens ?? 0,
+ output: usage.outputTokens ?? 0,
+ },
+ })
+ : null,
+ };
+ } catch (error) {
+ return {
+ success: false as const,
+ error: error instanceof Error ? error.message : String(error),
+ request,
+ executionTraceId,
+ };
+ }
+}
+
async function testLlmEvaluator(params: {
projectId: string;
evaluatorId: string;
diff --git a/web/src/features/evals/v2/server/rules/ruleService.ts b/web/src/features/evals/v2/server/rules/ruleService.ts
index b9017d4124..b39801f3f7 100644
--- a/web/src/features/evals/v2/server/rules/ruleService.ts
+++ b/web/src/features/evals/v2/server/rules/ruleService.ts
@@ -1,6 +1,6 @@
import {
- EvalTemplateType,
EvalTargetObject,
+ EvalTemplateType,
InvalidRequestError,
isExperimentEvaluationRule,
LangfuseConflictError,
@@ -794,12 +794,17 @@ export class RuleService {
);
const storedVariableMapping =
assignment.variableMapping ?? prepared.initialVariableMapping;
- const promptMessages = reconcileEvaluatorPromptMessages({
- prompt: latestVersion.prompt,
- promptMessages: latestVersion.promptMessages,
- });
+ const requiredVariables =
+ evaluator.type === EvalTemplateType.DECISION_MODEL
+ ? latestVersion.vars
+ : extractEvaluatorPromptVariables(
+ reconcileEvaluatorPromptMessages({
+ prompt: latestVersion.prompt,
+ promptMessages: latestVersion.promptMessages,
+ }),
+ );
assertCompleteEvaluatorVariableMapping({
- promptVariables: extractEvaluatorPromptVariables(promptMessages),
+ promptVariables: requiredVariables,
variableMapping:
storedVariableMapping ?? prepared.defaultVariableMapping,
});
diff --git a/web/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore.ts b/web/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore.ts
index e45a31da38..b448402b79 100644
--- a/web/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore.ts
+++ b/web/src/features/evals/v2/store/evaluatorSetupStore/evaluatorSetupStore.ts
@@ -1,5 +1,6 @@
import {
EvalTemplateTypeEnum,
+ experimentTargetEvalVariableColumns,
observationVariableMappingList,
type FilterState,
type ModelConfig,
@@ -21,6 +22,9 @@ import type { JudgeModel } from "@/src/features/evals/v2/judgeModel";
import type { ScoreOutputFormState } from "@/src/features/evals/v2/scoreOutputTypes";
import type { NormalizedEvaluatorDefinition } from "@/src/features/evals/v2/server/evaluators/evaluatorTypes";
import { toScoreOutputFormState } from "@/src/features/evals/v2/fns/scoreOutput/toScoreOutputFormState";
+import { questionsToDrafts } from "@/src/features/evals/v2/fns/evaluators/decisionModelQuestions";
+import type { DecisionModelQuestionDraft } from "@/src/features/evals/v2/types/decisionModel";
+import { moveItem } from "@/src/features/evals/v2/fns/moveItem";
import { safeRandomUUID } from "@/src/utils/safe-random-uuid";
const DEFAULT_PROMPT = `Evaluate the quality of the response.
@@ -28,10 +32,25 @@ const DEFAULT_PROMPT = `Evaluate the quality of the response.
Input: {{input}}
Response: {{output}}`;
+const DEFAULT_STATE_KEYS = ["input", "output"];
+
+function buildInitialStateKeys(
+ definition: NormalizedEvaluatorDefinition | null | undefined,
+): string[] {
+ return definition?.type === "DECISION_MODEL"
+ ? definition.vars
+ : DEFAULT_STATE_KEYS;
+}
+
function buildInitialVariableFields(
definition: NormalizedEvaluatorDefinition | null | undefined,
): Record<string, VariableFieldState> {
- if (definition?.type !== "LLM_AS_JUDGE") return {};
+ if (
+ definition?.type !== "LLM_AS_JUDGE" &&
+ definition?.type !== "DECISION_MODEL"
+ ) {
+ return {};
+ }
const parsed = observationVariableMappingList.safeParse(
definition.variableMapping,
@@ -55,8 +74,32 @@ function buildInitialVariableFields(
);
}
+function buildInitialScoreOutput(
+ definition: NormalizedEvaluatorDefinition | null | undefined,
+): ScoreOutputFormState {
+ return toScoreOutputFormState(
+ definition?.type === "LLM_AS_JUDGE" ? definition.outputDefinition : null,
+ );
+}
+
+function buildInitialQuestions(
+ definition: NormalizedEvaluatorDefinition | null | undefined,
+): DecisionModelQuestionDraft[] {
+ return definition?.type === "DECISION_MODEL"
+ ? questionsToDrafts(definition.questions)
+ : [];
+}
+
type EvaluatorSetupStoreActions = {
setType: (type: EvalTemplateType) => void;
+ setQuestion: (question: DecisionModelQuestionDraft) => void;
+ addQuestion: (question: DecisionModelQuestionDraft) => void;
+ removeQuestion: (id: string) => void;
+ reorderQuestion: (fromIndex: number, toIndex: number) => void;
+ setExpandedQuestionId: (id: string | null) => void;
+ addStateKey: () => void;
+ renameStateKey: (key: string, next: string) => void;
+ removeStateKey: (key: string) => void;
setPromptMessage: (index: number, message: EvaluatorPromptMessage) => void;
addPromptMessage: () => void;
removePromptMessage: (index: number) => void;
@@ -91,6 +134,9 @@ export type EvaluatorSetupStoreState = {
promptMessages: EvaluatorPromptMessage[];
/** Stable client-only ids used by drag-and-drop; never persisted. */
promptMessageIds: string[];
+ questions: DecisionModelQuestionDraft[];
+ expandedQuestionId: string | null;
+ stateKeys: string[];
sourceCode: string;
sourceCodeLanguage: EvalTemplateSourceCodeLanguage;
sourceCodeDrafts: Partial<Record<EvalTemplateSourceCodeLanguage, string>>;
@@ -114,11 +160,17 @@ export type EvaluatorSetupStoreState = {
export type EvaluatorSetupStore = StoreApi<EvaluatorSetupStoreState>;
-export const selectHasValidModel = (state: EvaluatorSetupStoreState) =>
- state.type !== EvalTemplateTypeEnum.LLM_AS_JUDGE ||
- Boolean(
- state.modelMode === "custom" ? state.selectedModel : state.defaultModel,
- );
+export const selectHasValidModel = (state: EvaluatorSetupStoreState) => {
+ if (state.type === EvalTemplateTypeEnum.LLM_AS_JUDGE) {
+ return Boolean(
+ state.modelMode === "custom" ? state.selectedModel : state.defaultModel,
+ );
+ }
+ if (state.type === EvalTemplateTypeEnum.DECISION_MODEL) {
+ return Boolean(state.selectedModel);
+ }
+ return true;
+};
export function createEvaluatorSetupStore({
initialEvaluator,
@@ -150,25 +202,27 @@ export function createEvaluatorSetupStore({
initialDefinition?.type === "LLM_AS_JUDGE"
? initialDefinition.promptMessages
: [{ role: "user" as const, content: DEFAULT_PROMPT }];
+ const type =
+ initialDefinition?.type ?? initialType ?? EvalTemplateTypeEnum.LLM_AS_JUDGE;
+ const hasModelSelection =
+ initialDefinition?.type === "LLM_AS_JUDGE" ||
+ initialDefinition?.type === "DECISION_MODEL";
+ const initialQuestions = buildInitialQuestions(initialDefinition);
return createStore<EvaluatorSetupStoreState>((set) => ({
initialDefinition,
- type:
- initialDefinition?.type ??
- initialType ??
- EvalTemplateTypeEnum.LLM_AS_JUDGE,
+ type,
promptMessages: initialPromptMessages,
promptMessageIds: initialPromptMessages.map(() => safeRandomUUID()),
+ questions: initialQuestions,
+ expandedQuestionId: initialQuestions[0]?.id ?? null,
+ stateKeys: buildInitialStateKeys(initialDefinition),
sourceCode: initialSourceCode,
sourceCodeLanguage: initialSourceCodeLanguage,
sourceCodeDrafts: {
[initialSourceCodeLanguage]: initialSourceCode,
},
- scoreOutput: toScoreOutputFormState(
- initialDefinition?.type === "LLM_AS_JUDGE"
- ? initialDefinition.outputDefinition
- : null,
- ),
+ scoreOutput: buildInitialScoreOutput(initialDefinition),
name: initialEvaluator?.name ?? "",
description: initialEvaluator?.description ?? "",
openSteps: { 1: true, 2: true, 3: true },
@@ -176,14 +230,13 @@ export function createEvaluatorSetupStore({
activeMapping: null,
modelPickerOpen: false,
modelMode:
- initialDefinition?.type === "LLM_AS_JUDGE" && initialDefinition.model
+ (initialDefinition?.type === "LLM_AS_JUDGE" && initialDefinition.model) ||
+ type === EvalTemplateTypeEnum.DECISION_MODEL
? "custom"
: "default",
defaultModel,
selectedModel:
- initialDefinition?.type === "LLM_AS_JUDGE" &&
- initialDefinition.provider &&
- initialDefinition.model
+ hasModelSelection && initialDefinition.provider && initialDefinition.model
? {
provider: initialDefinition.provider,
model: initialDefinition.model,
@@ -200,7 +253,128 @@ export function createEvaluatorSetupStore({
promptPreviewEnabled: false,
testPanelOpen: true,
actions: {
- setType: (type) => set({ type }),
+ setType: (type) =>
+ set((state) => {
+ if (type === state.type) return state;
+ if (type === EvalTemplateTypeEnum.DECISION_MODEL) {
+ return {
+ type,
+ modelMode: "custom",
+ selectedModel: null,
+ modelParams: null,
+ };
+ }
+ if (state.type === EvalTemplateTypeEnum.DECISION_MODEL) {
+ return {
+ type,
+ modelMode: "default",
+ selectedModel: null,
+ modelParams: null,
+ };
+ }
+ return { type };
+ }),
+ setQuestion: (question) =>
+ set((state) => ({
+ questions: state.questions.map((current) =>
+ current.id === question.id ? question : current,
+ ),
+ })),
+ addQuestion: (question) =>
+ set((state) => ({
+ questions: [...state.questions, question],
+ expandedQuestionId: question.id,
+ })),
+ removeQuestion: (id) =>
+ set((state) => ({
+ questions: state.questions.filter((question) => question.id !== id),
+ expandedQuestionId:
+ state.expandedQuestionId === id ? null : state.expandedQuestionId,
+ })),
+ reorderQuestion: (fromIndex, toIndex) =>
+ set((state) => ({
+ questions: moveItem(state.questions, fromIndex, toIndex),
+ })),
+ setExpandedQuestionId: (expandedQuestionId) =>
+ set({ expandedQuestionId }),
+ addStateKey: () =>
+ set((state) => {
+ let index = state.stateKeys.length + 1;
+ while (state.stateKeys.includes(`field_${index}`)) index += 1;
+ const key = `field_${index}`;
+ return {
+ stateKeys: [...state.stateKeys, key],
+ variableFields: {
+ ...state.variableFields,
+ [key]: { selectedColumnId: null, jsonSelector: null },
+ },
+ activeMapping: { variable: key, state: "renaming" },
+ };
+ }),
+ renameStateKey: (key, next) =>
+ set((state) => {
+ if (
+ key === next ||
+ !state.stateKeys.includes(key) ||
+ state.stateKeys.includes(next)
+ ) {
+ return state;
+ }
+ const current = state.variableFields[key] ?? {
+ selectedColumnId: null,
+ jsonSelector: null,
+ };
+ const fieldState = current.selectedColumnId
+ ? current
+ : {
+ selectedColumnId: experimentTargetEvalVariableColumns.some(
+ (column) => column.id === next,
+ )
+ ? next
+ : null,
+ jsonSelector: null,
+ };
+ // Plain string replacement: the token is a literal, so no regex is
+ // built from user input.
+ const oldReference = `\`${key}\``;
+ const nextReference = `\`${next}\``;
+ return {
+ stateKeys: state.stateKeys.map((current) =>
+ current === key ? next : current,
+ ),
+ variableFields: Object.fromEntries(
+ Object.entries(state.variableFields).map(([variable, value]) =>
+ variable === key ? [next, fieldState] : [variable, value],
+ ),
+ ),
+ questions: state.questions.map((question) => ({
+ ...question,
+ instructions: question.instructions.replaceAll(
+ oldReference,
+ nextReference,
+ ),
+ })),
+ activeMapping: {
+ variable: next,
+ state: fieldState.selectedColumnId ? "preview" : "editing",
+ },
+ };
+ }),
+ removeStateKey: (key) =>
+ set((state) => {
+ return {
+ stateKeys: state.stateKeys.filter((current) => current !== key),
+ variableFields: Object.fromEntries(
+ Object.entries(state.variableFields).filter(
+ ([variable]) => variable !== key,
+ ),
+ ),
+ activeMapping:
+ state.activeMapping?.variable === key
+ ? null
+ : state.activeMapping,
+ };
+ }),
setPromptMessage: (index, message) =>
set((state) => {
const promptMessages = state.promptMessages.map((current, i) =>
@@ -329,6 +503,21 @@ export function createEvaluatorSetupStore({
}
: null;
+ if (definition.type === EvalTemplateTypeEnum.DECISION_MODEL) {
+ const questions = questionsToDrafts(definition.questions);
+ return {
+ type: definition.type,
+ questions,
+ expandedQuestionId: questions[0]?.id ?? null,
+ stateKeys: buildInitialStateKeys(definition),
+ variableFields: buildInitialVariableFields(definition),
+ activeMapping: null,
+ modelMode: "custom",
+ selectedModel,
+ modelParams: null,
+ };
+ }
+
return {
type: definition.type,
promptMessages: definition.promptMessages,
diff --git a/web/src/features/evals/v2/types/decisionModel.ts b/web/src/features/evals/v2/types/decisionModel.ts
new file mode 100644
index 0000000000..991adaef08
--- /dev/null
+++ b/web/src/features/evals/v2/types/decisionModel.ts
@@ -0,0 +1,66 @@
+import type { DecisionModelQuestionType } from "@langfuse/shared";
+
+export type DecisionModelQuestionDraft = {
+ id: string;
+ type: DecisionModelQuestionType;
+ scoreName: string;
+ instructions: string;
+ options: Array<{ value: string; description: string }>;
+ levels: Array<{ description: string }>;
+ criteria: { true: string; false: string };
+};
+
+export type DecisionModelQuestionDraftErrors = Partial<
+ Record<"scoreName" | "instructions" | "options" | "levels", string>
+>;
+
+/** Reads the state keys a question refers to in backticks. */
+export function extractReferencedStateKeys(instructions: string): string[] {
+ return [
+ ...new Set(
+ Array.from(instructions.matchAll(/`([A-Za-z_][A-Za-z0-9_.[\]-]*)`/g)).map(
+ ([, key]) => key.split(/[.[]/)[0]!,
+ ),
+ ),
+ ];
+}
+
+/** Turns a question into a snake_case score name suggestion. */
+export function suggestScoreName(instructions: string): string {
+ return instructions
+ .toLowerCase()
+ .replace(/`[^`]*`/g, " ")
+ .replace(/[^a-z0-9]+/g, " ")
+ .trim()
+ .split(" ")
+ .filter((word) => !STOP_WORDS.has(word))
+ .slice(0, 3)
+ .join("_");
+}
+
+const STOP_WORDS = new Set([
+ "a",
+ "an",
+ "the",
+ "is",
+ "are",
+ "does",
+ "do",
+ "did",
+ "to",
+ "of",
+ "in",
+ "on",
+ "for",
+ "this",
+ "that",
+ "it",
+ "as",
+ "how",
+ "should",
+ "can",
+ "what",
+ "which",
+ "and",
+ "or",
+]);
diff --git a/web/src/features/evals/v2/types/variableMapping.ts b/web/src/features/evals/v2/types/variableMapping.ts
index 31bfba415a..7d3e1951a3 100644
--- a/web/src/features/evals/v2/types/variableMapping.ts
+++ b/web/src/features/evals/v2/types/variableMapping.ts
@@ -9,5 +9,5 @@ export type VariableFieldState = {
export type ActiveVariableMapping = {
variable: string;
- state: "preview" | "editing";
+ state: "preview" | "editing" | "renaming";
} | null;
diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.ts
index 8533eade3b..49231fb5b8 100644
--- a/web/src/features/feature-flags/available-flags.ts
+++ b/web/src/features/feature-flags/available-flags.ts
@@ -71,4 +71,5 @@ export const availableFlags = [
"v4BetaToggleVisible",
"observationEvals",
"experimentsV4Enabled",
+ "decisionModelEvaluators",
] as const;
diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.ts
index 92de9f3910..8abd4fb1c9 100644
--- a/web/src/features/feature-flags/types.ts
+++ b/web/src/features/feature-flags/types.ts
@@ -9,6 +9,7 @@ export type Flags = {
| "aiGateway"
| "sessionTimeline"
| "traceMessages"
+ | "decisionModelEvaluators"
>]: boolean;
} & {
// Optional while older sessions and test fixtures roll across new flags.
@@ -17,4 +18,5 @@ export type Flags = {
aiGateway?: boolean;
sessionTimeline?: boolean;
traceMessages?: boolean;
+ decisionModelEvaluators?: boolean;
};
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index 0799160883..c1b2b5c7ea 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -32,8 +32,11 @@ import {
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
ChatMessageType,
+ createTypeSafeDecisionModelClient,
+ DECISION_MODEL_ADAPTERS,
generateLLMText,
getClientInitiatedNonStreamingLlmTimeoutMs,
+ isDecisionModelAdapter,
LLMAdapter,
logger,
mapLegacyLLMCompletionParams,
@@ -104,6 +107,55 @@ type TestLLMConnectionParams = {
config?: unknown;
};
+function assertDecisionModelConnectionInput(input: {
+ adapter: LLMAdapter;
+ baseURL?: string | null;
+ extraHeaders?: Record<string, string | null | undefined> | null;
+}) {
+ if (!isDecisionModelAdapter(input.adapter)) return;
+ if (input.baseURL) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Decision-model connections do not support a custom base URL.",
+ });
+ }
+ if (input.extraHeaders && Object.keys(input.extraHeaders).length > 0) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Decision-model connections do not support extra headers.",
+ });
+ }
+}
+
+async function testDecisionModelConnection(params: {
+ secretKey: string;
+ model: string;
+}): Promise<{ success: boolean; error?: string }> {
+ try {
+ const client = createTypeSafeDecisionModelClient({
+ apiKey: params.secretKey,
+ model: params.model,
+ });
+ await client.evaluate({
+ state: { message: "Hello, is anyone there?" },
+ questions: {
+ kind: {
+ type: "choice",
+ instructions: "What kind of message is `message`?",
+ criteria: { greeting: null, other: null },
+ },
+ },
+ });
+ return { success: true };
+ } catch (err) {
+ logger.error(err);
+ return {
+ success: false,
+ error: err instanceof Error ? err.message : "Unknown error",
+ };
+ }
+}
+
async function testLLMConnection(
params: TestLLMConnectionParams,
): Promise<{ success: boolean; error?: string }> {
@@ -114,6 +166,13 @@ async function testLLMConnection(
if (!model) throw Error("No model found");
+ if (isDecisionModelAdapter(params.adapter)) {
+ return await testDecisionModelConnection({
+ secretKey: params.secretKey,
+ model,
+ });
+ }
+
if (params.adapter === LLMAdapter.VertexAI) {
// Skip validation if using ADC (Application Default Credentials)
if (params.secretKey !== VERTEXAI_USE_DEFAULT_CREDENTIALS) {
@@ -211,6 +270,8 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:create",
});
+ assertDecisionModelConnectionInput(input);
+
await validateBaseURLForWrite({
baseURL: input.baseURL,
});
@@ -379,6 +440,7 @@ export const llmApiKeyRouter = createTRPCRouter({
.input(
z.object({
projectId: z.string(),
+ includeDecisionModels: z.boolean().optional().default(false),
}),
)
.query(async ({ input, ctx }) => {
@@ -388,6 +450,13 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:read",
});
+ const where = {
+ projectId: input.projectId,
+ ...(input.includeDecisionModels
+ ? {}
+ : { adapter: { notIn: [...DECISION_MODEL_ADAPTERS] } }),
+ };
+
const storedApiKeys = await ctx.prisma.llmApiKeys.findMany({
// secretKey is selected server-side only to derive a safe auth-method enum for Bedrock
select: {
@@ -405,9 +474,7 @@ export const llmApiKeyRouter = createTRPCRouter({
config: true,
secretKey: true,
},
- where: {
- projectId: input.projectId,
- },
+ where,
});
const apiKeys = z.array(SafeLlmApiKeySchema).parse(
@@ -422,11 +489,7 @@ export const llmApiKeyRouter = createTRPCRouter({
})),
);
- const count = await ctx.prisma.llmApiKeys.count({
- where: {
- projectId: input.projectId,
- },
- });
+ const count = await ctx.prisma.llmApiKeys.count({ where });
return {
data: apiKeys, // does not contain the secret key
@@ -443,6 +506,8 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:create",
});
+ assertDecisionModelConnectionInput(input);
+
if (input.baseURL) {
try {
await validateLlmConnectionBaseURL(input.baseURL);
@@ -581,6 +646,8 @@ export const llmApiKeyRouter = createTRPCRouter({
});
}
+ assertDecisionModelConnectionInput(input);
+
// Validate that default credentials sentinel is only allowed for Bedrock/VertexAI in self-hosted deployments
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
const isBaseURLChanged =
diff --git a/web/src/features/mcp/server/evals/rule-service.ts b/web/src/features/mcp/server/evals/rule-service.ts
index 75732f6709..843cd12f9f 100644
--- a/web/src/features/mcp/server/evals/rule-service.ts
+++ b/web/src/features/mcp/server/evals/rule-service.ts
@@ -1,11 +1,13 @@
import { auditLog } from "@/src/features/audit-logs/server";
import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
import {
+ isPublicApiEvaluatorType,
toApiReadMappings,
toPublicEvaluatorType,
toStoredMappingList,
} from "@/src/features/public-api/server";
import { RuleService } from "@/src/features/evals/v2/server/rules/ruleService";
+import { InvalidRequestError } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import type { z } from "zod";
import type { ServerContext } from "../../types";
@@ -42,6 +44,22 @@ export function toStoredAssignments(
type StoredRule = Awaited<ReturnType<RuleService["get"]>>;
+export async function assertRuleAssignmentsReplaceableViaMcp(
+ service: RuleService,
+ projectId: string,
+ ruleId: string,
+) {
+ const rule = await service.get(projectId, ruleId);
+ const hidden = rule.assignments.filter(
+ (assignment) => !isPublicApiEvaluatorType(assignment.evaluator.type),
+ );
+ if (hidden.length > 0) {
+ throw new InvalidRequestError(
+ "This rule uses experimental evaluators that are not visible through MCP. Update its evaluator assignments in the Langfuse UI.",
+ );
+ }
+}
+
export function toMcpEvaluationRule(
rule: StoredRule,
): z.infer<typeof EvaluationRuleResponseSchema> {
@@ -51,15 +69,19 @@ export function toMcpEvaluationRule(
enabled: rule.enabled,
sampling: rule.sampling,
filter: rule.filter,
- evaluators: rule.assignments.map((assignment) => ({
- evaluatorId: assignment.evaluator.id,
- evaluatorName: assignment.evaluator.name,
- evaluatorType: toPublicEvaluatorType(assignment.evaluator.type),
- variableMapping:
- assignment.variableMapping === null
- ? null
- : toApiReadMappings(assignment.variableMapping),
- })),
+ evaluators: rule.assignments
+ .filter((assignment) =>
+ isPublicApiEvaluatorType(assignment.evaluator.type),
+ )
+ .map((assignment) => ({
+ evaluatorId: assignment.evaluator.id,
+ evaluatorName: assignment.evaluator.name,
+ evaluatorType: toPublicEvaluatorType(assignment.evaluator.type),
+ variableMapping:
+ assignment.variableMapping === null
+ ? null
+ : toApiReadMappings(assignment.variableMapping),
+ })),
createdAt: rule.createdAt,
updatedAt: rule.updatedAt,
});
diff --git a/web/src/features/mcp/server/evals/tools/updateEvaluationRule.ts b/web/src/features/mcp/server/evals/tools/updateEvaluationRule.ts
index c2af17db56..a5d4e7647f 100644
--- a/web/src/features/mcp/server/evals/tools/updateEvaluationRule.ts
+++ b/web/src/features/mcp/server/evals/tools/updateEvaluationRule.ts
@@ -5,6 +5,7 @@ import {
UpdateEvaluationRuleInputSchema,
} from "../rule-schema";
import {
+ assertRuleAssignmentsReplaceableViaMcp,
createMcpRuleService,
toMcpEvaluationRule,
toStoredAssignments,
@@ -25,7 +26,15 @@ export const [updateEvaluationRuleTool, handleUpdateEvaluationRule] =
attributes: { "mcp.evaluation_rule_id": input.evaluationRuleId },
fn: async () => {
const { evaluationRuleId, evaluatorAssignments, ...patch } = input;
- const rule = await createMcpRuleService(context).update({
+ const service = createMcpRuleService(context);
+ if (evaluatorAssignments !== undefined) {
+ await assertRuleAssignmentsReplaceableViaMcp(
+ service,
+ context.projectId,
+ evaluationRuleId,
+ );
+ }
+ const rule = await service.update({
projectId: context.projectId,
ruleId: evaluationRuleId,
...patch,
diff --git a/web/src/features/playground/page/hooks/useModelParams.ts b/web/src/features/playground/page/hooks/useModelParams.ts
index 4a51b2fd83..e0ac8ba0dd 100644
--- a/web/src/features/playground/page/hooks/useModelParams.ts
+++ b/web/src/features/playground/page/hooks/useModelParams.ts
@@ -391,5 +391,19 @@ function getDefaultAdapterParams(
maxReasoningTokens: { value: 0, enabled: false },
providerOptions: { value: {}, enabled: false },
};
+
+ case LLMAdapter.TypeSafe:
+ return {
+ adapter: {
+ value: adapter,
+ enabled: true,
+ },
+ temperature: { value: 0, enabled: false },
+ maxTemperature: { value: 0, enabled: false },
+ max_tokens: { value: 0, enabled: false },
+ top_p: { value: 1, enabled: false },
+ maxReasoningTokens: { value: 0, enabled: false },
+ providerOptions: { value: {}, enabled: false },
+ };
}
}
diff --git a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
index 9fea3fa26f..2dfef98c97 100644
--- a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
+++ b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
@@ -11,7 +11,9 @@ import {
LLMAdapter,
BEDROCK_USE_DEFAULT_CREDENTIALS,
VERTEXAI_USE_DEFAULT_CREDENTIALS,
+ isDecisionModelAdapter,
} from "@langfuse/shared";
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
import { ChevronDown, PlusIcon, TrashIcon } from "lucide-react";
import { z } from "zod";
import { Button } from "@/src/components/ui/button";
@@ -275,9 +277,20 @@ export function CreateLLMApiKeyForm({
const existingKeys = api.llmApiKey.all.useQuery(
{
projectId: projectId as string,
+ includeDecisionModels: true,
},
{ enabled: Boolean(projectId) },
);
+ const isDecisionModelEnabled = useIsFeatureEnabled(
+ "decisionModelEvaluators",
+ { projectId },
+ );
+ const adapterOptions = Object.values(LLMAdapter).filter(
+ (adapter) =>
+ isDecisionModelEnabled ||
+ !isDecisionModelAdapter(adapter) ||
+ existingKey?.adapter === adapter,
+ );
const mutCreateLlmApiKey = api.llmApiKey.create.useMutation({
onSuccess: () => utils.llmApiKey.invalidate(),
@@ -711,9 +724,11 @@ export function CreateLLMApiKeyForm({
</SelectTrigger>
</FormControl>
<SelectContent>
- {Object.values(LLMAdapter).map((provider) => (
+ {adapterOptions.map((provider) => (
<SelectItem value={provider} key={provider}>
- {provider}
+ {isDecisionModelAdapter(provider)
+ ? `${provider} (experimental)`
+ : provider}
</SelectItem>
))}
{mode === "create" && (
diff --git a/web/src/features/public-api/components/LLMApiKeySettingsTable/ConnectedLLMApiKeySettingsTable.tsx b/web/src/features/public-api/components/LLMApiKeySettingsTable/ConnectedLLMApiKeySettingsTable.tsx
index fdbadcef37..1bca9f1309 100644
--- a/web/src/features/public-api/components/LLMApiKeySettingsTable/ConnectedLLMApiKeySettingsTable.tsx
+++ b/web/src/features/public-api/components/LLMApiKeySettingsTable/ConnectedLLMApiKeySettingsTable.tsx
@@ -29,7 +29,10 @@ export function ConnectedLLMApiKeySettingsTable({
scope: "llmApiKeys:update",
});
- const apiKeys = api.llmApiKey.all.useQuery({ projectId });
+ const apiKeys = api.llmApiKey.all.useQuery({
+ projectId,
+ includeDecisionModels: true,
+ });
const deleteApiKey = api.llmApiKey.delete.useMutation({
onSuccess: () => utils.llmApiKey.invalidate(),
});
diff --git a/web/src/features/public-api/server/evaluation/evaluationAdapters.ts b/web/src/features/public-api/server/evaluation/evaluationAdapters.ts
index 22fec7d264..72adf362d5 100644
--- a/web/src/features/public-api/server/evaluation/evaluationAdapters.ts
+++ b/web/src/features/public-api/server/evaluation/evaluationAdapters.ts
@@ -3,6 +3,7 @@ import {
EvalTemplateType,
extractVariables,
InternalServerError,
+ InvalidRequestError,
observationVariableMappingList,
PersistedEvalOutputDefinitionSchema,
resolvePersistedEvalOutputDefinition,
@@ -66,10 +67,26 @@ const INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE: Record<
experiment_item_metadata: "experiment_item_metadata",
};
+export const PUBLIC_API_EVALUATOR_TYPES: EvalTemplateType[] = [
+ EvalTemplateType.LLM_AS_JUDGE,
+ EvalTemplateType.CODE,
+];
+
+export function isPublicApiEvaluatorType(type: EvalTemplateType) {
+ return PUBLIC_API_EVALUATOR_TYPES.includes(type);
+}
+
export function toPublicEvaluatorType(type: EvalTemplateType) {
- return type === EvalTemplateType.CODE
- ? PUBLIC_EVALUATOR_TYPE_CODE
- : PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE;
+ switch (type) {
+ case EvalTemplateType.CODE:
+ return PUBLIC_EVALUATOR_TYPE_CODE;
+ case EvalTemplateType.LLM_AS_JUDGE:
+ return PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE;
+ case EvalTemplateType.DECISION_MODEL:
+ throw new InvalidRequestError(
+ "Decision-model evaluators are experimental and not available through the public API",
+ );
+ }
}
export function toStoredMappingList(
@@ -267,6 +284,12 @@ export function toPublicEvaluatorVersion(
createdBy: toCreator(version.createdByUser),
};
+ if (evaluatorType === EvalTemplateType.DECISION_MODEL) {
+ throw new InvalidRequestError(
+ "Decision-model evaluators are experimental and not available through the public API",
+ );
+ }
+
if (evaluatorType === EvalTemplateType.CODE) {
if (!version.sourceCode || !version.sourceCodeLanguage) {
throw new InternalServerError("Code evaluator definition is corrupted");
diff --git a/web/src/features/public-api/server/evaluation/evaluatorApiService.ts b/web/src/features/public-api/server/evaluation/evaluatorApiService.ts
index a319e4836f..995846dfcf 100644
--- a/web/src/features/public-api/server/evaluation/evaluatorApiService.ts
+++ b/web/src/features/public-api/server/evaluation/evaluatorApiService.ts
@@ -1,4 +1,8 @@
-import { EvalTemplateType, ZodModelConfig } from "@langfuse/shared";
+import {
+ EvalTemplateType,
+ InvalidRequestError,
+ ZodModelConfig,
+} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import type { ApiAccessScope } from "@langfuse/shared/src/server";
import { auditLog } from "@/src/features/audit-logs/server";
@@ -13,11 +17,26 @@ import {
type UpdateEvaluatorBodyType,
} from "@/src/features/public-api/types/evaluation/evaluators";
import {
+ isPublicApiEvaluatorType,
+ PUBLIC_API_EVALUATOR_TYPES,
toEvaluatorServiceDefinition,
toPublicEvaluator,
toPublicEvaluatorVersion,
} from "./evaluationAdapters";
+async function assertPublicApiEvaluator(
+ service: EvaluatorService,
+ projectId: string,
+ evaluatorId: string,
+) {
+ const evaluator = await service.get(projectId, evaluatorId);
+ if (!isPublicApiEvaluatorType(evaluator.type)) {
+ throw new InvalidRequestError(
+ "This evaluator type is experimental and not available through the public API",
+ );
+ }
+}
+
function evaluatorService(auditScope: ApiAccessScope) {
return new EvaluatorService(prisma, ({ action, evaluatorId, projectId }) =>
auditLog({
@@ -40,6 +59,7 @@ export async function listEvaluatorsForPublicApi(params: {
const result = await evaluatorService(params.auditScope).listCursor({
projectId: params.projectId,
limit: params.limit,
+ types: PUBLIC_API_EVALUATOR_TYPES,
cursor: params.cursor
? {
createdAt: new Date(params.cursor.lastCreatedAt),
@@ -99,6 +119,7 @@ export async function updateEvaluatorForPublicApi(params: {
auditScope: ApiAccessScope;
}) {
const service = evaluatorService(params.auditScope);
+ await assertPublicApiEvaluator(service, params.projectId, params.evaluatorId);
let definition =
"type" in params.input
? toEvaluatorServiceDefinition(params.input)
@@ -141,10 +162,9 @@ export async function deleteEvaluatorForPublicApi(params: {
evaluatorId: string;
auditScope: ApiAccessScope;
}) {
- await evaluatorService(params.auditScope).delete(
- params.projectId,
- params.evaluatorId,
- );
+ const service = evaluatorService(params.auditScope);
+ await assertPublicApiEvaluator(service, params.projectId, params.evaluatorId);
+ await service.delete(params.projectId, params.evaluatorId);
return { id: params.evaluatorId };
}
diff --git a/web/src/features/public-api/server/index.ts b/web/src/features/public-api/server/index.ts
index c63c5a8c7b..41c3008cd3 100644
--- a/web/src/features/public-api/server/index.ts
+++ b/web/src/features/public-api/server/index.ts
@@ -164,6 +164,7 @@ export {
} from "../types/unstable-dashboards";
export { __dangerouslySkipAuthz, type ApiAction } from "./enforceAuth";
export {
+ isPublicApiEvaluatorType,
toApiReadMappings,
toPublicEvaluatorType,
toStoredMappingList,
diff --git a/web/src/features/public-api/types/llm-connections.ts b/web/src/features/public-api/types/llm-connections.ts
index 9d5d9f802a..3224531799 100644
--- a/web/src/features/public-api/types/llm-connections.ts
+++ b/web/src/features/public-api/types/llm-connections.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import {
publicApiPaginationZod,
+ isDecisionModelAdapter,
LLMAdapter,
type JSONValue,
BedrockConfigSchema,
@@ -48,10 +49,15 @@ export const GetLlmConnectionsV1Response = z
})
.strict();
+// Decision-model adapters are experimental and not part of the public contract.
+const PUBLIC_LLM_ADAPTERS = Object.values(LLMAdapter).filter(
+ (adapter) => !isDecisionModelAdapter(adapter),
+) as [LLMAdapter, ...LLMAdapter[]];
+
// Base request schema (before adapter-specific validation)
const PutLlmConnectionV1BodyBase = z.object({
provider: z.string().min(1),
- adapter: z.enum(LLMAdapter),
+ adapter: z.enum(PUBLIC_LLM_ADAPTERS),
secretKey: z.string().min(1),
baseURL: z.url().nullable().optional(),
customModels: z.array(z.string().min(1)).optional(),
diff --git a/worker/src/constants/default-model-prices.json b/worker/src/constants/default-model-prices.json
index d819ce0c98..6746e4d847 100644
--- a/worker/src/constants/default-model-prices.json
+++ b/worker/src/constants/default-model-prices.json
@@ -7407,5 +7407,25 @@
}
}
]
+ },
+ {
+ "id": "7f3c9a2e-5b1d-4e8f-9a6c-2d4b8e1f0a3c",
+ "modelName": "jev",
+ "matchPattern": "(?i)^(typesafe(-ai)?\\/)?jev(-[0-9]+(\\.[0-9]+)*|-latest|-preview)?$",
+ "createdAt": "2026-09-22T00:00:00.000Z",
+ "updatedAt": "2026-09-22T00:00:00.000Z",
+ "pricingTiers": [
+ {
+ "id": "7f3c9a2e-5b1d-4e8f-9a6c-2d4b8e1f0a3c_tier_default",
+ "name": "Standard",
+ "isDefault": true,
+ "priority": 0,
+ "conditions": [],
+ "prices": {
+ "input": 4.2e-8,
+ "output": 0
+ }
+ }
+ ]
}
]
diff --git a/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.test.ts b/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.test.ts
new file mode 100644
index 0000000000..f26065415b
--- /dev/null
+++ b/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.test.ts
@@ -0,0 +1,290 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { JobExecutionStatus } from "@prisma/client";
+
+const mocks = vi.hoisted(() => ({
+ blockEvaluator: vi.fn().mockResolvedValue({ blockedEvaluatorIds: [] }),
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@langfuse/shared/src/server")>();
+ return {
+ ...actual,
+ blockEvaluator: mocks.blockEvaluator,
+ instrumentAsync: vi.fn(
+ async (
+ _options: { name: string },
+ callback: (span: {
+ setAttribute: () => unknown;
+ setAttributes: () => unknown;
+ }) => Promise<unknown>,
+ ) => {
+ const span = {
+ setAttribute: () => span,
+ setAttributes: () => span,
+ };
+ return callback(span);
+ },
+ ),
+ };
+});
+
+import { EvalTargetObject, EvalTemplateType } from "@langfuse/shared";
+import {
+ EvaluatorBlockSource,
+ LLMValidationError,
+} from "@langfuse/shared/src/server";
+import { UnrecoverableError } from "../../../errors/UnrecoverableError";
+import { createMockEvalExecutionDeps } from "../evalExecutionDeps";
+import { runDecisionModelEvaluation } from "./runDecisionModelEvaluation";
+
+describe("runDecisionModelEvaluation", () => {
+ const projectId = "project-1";
+ const jobExecutionId = "job-execution-1";
+
+ beforeEach(() => {
+ mocks.blockEvaluator.mockClear();
+ });
+
+ const job = {
+ id: jobExecutionId,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId,
+ status: JobExecutionStatus.PENDING,
+ startTime: new Date(),
+ endTime: null,
+ jobConfigurationId: "rule-1",
+ jobInputTraceId: "trace-1",
+ jobInputTraceTimestamp: new Date(),
+ jobInputObservationId: "observation-1",
+ jobInputDatasetItemId: null,
+ jobInputDatasetItemValidFrom: null,
+ jobTemplateId: "version-1",
+ error: null,
+ jobOutputScoreId: null,
+ executionTraceId: null,
+ };
+
+ const config = {
+ id: "rule-1",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId,
+ jobType: "EVAL" as const,
+ evalTemplateId: "version-1",
+ scoreName: "send_ready",
+ targetObject: EvalTargetObject.EVENT,
+ filter: [],
+ variableMapping: [],
+ sampling: "1.0",
+ delay: 0,
+ status: "ACTIVE" as const,
+ blockedAt: null,
+ blockReason: null,
+ blockMessage: null,
+ timeScope: ["NEW" as const],
+ };
+
+ const template = {
+ id: "version-1",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId,
+ name: "Send readiness",
+ version: 1,
+ type: EvalTemplateType.DECISION_MODEL,
+ prompt: null,
+ partner: null,
+ model: "jev-1.13.0",
+ provider: "typesafe",
+ modelParams: null,
+ vars: ["input", "output"],
+ outputDefinition: null,
+ sourceCode: null,
+ sourceCodeLanguage: null,
+ questions: [
+ {
+ id: "readiness",
+ scoreName: "send_readiness",
+ type: "choice",
+ instructions: "Is `output` ready to send as an answer to `input`?",
+ options: [{ value: "ready" }, { value: "needs_revision" }],
+ },
+ {
+ id: "refund",
+ scoreName: "refund_requested",
+ type: "noul",
+ instructions: "Does `input` request a refund?",
+ },
+ ],
+ };
+
+ const typeSafeModelConfig = {
+ valid: true as const,
+ config: {
+ provider: "typesafe",
+ model: "jev-1.13.0",
+ apiKey: { adapter: "typesafe", secretKey: "encrypted" },
+ adapter: undefined as never,
+ modelParams: {},
+ },
+ };
+
+ const baseParams = {
+ projectId,
+ jobExecutionId,
+ job: job as never,
+ config: config as never,
+ template,
+ extractedVariables: [
+ { var: "input", value: "Can I get a refund?" },
+ { var: "output", value: "Yes, unused items within 30 days." },
+ ],
+ executionMetadata: { job_execution_id: jobExecutionId },
+ evaluationContext: {
+ evaluationRuleId: "rule-1",
+ evaluatorExecutionIsTest: false,
+ },
+ evaluatorId: "evaluator-1",
+ };
+
+ it("writes one score per question carrying the probability distribution", async () => {
+ const callDecisionModel = vi.fn().mockResolvedValue({
+ model: "jev-1.13.0",
+ answers: {
+ readiness: {
+ type: "choice",
+ choice: "ready",
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ confidence: 0.82,
+ },
+ refund: { type: "boolean", probability: 0.97 },
+ },
+ usage: { inputTokens: 200, outputTokens: 3 },
+ });
+ const writeInternalTrace = vi.fn().mockResolvedValue(undefined);
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue(typeSafeModelConfig),
+ callDecisionModel,
+ writeInternalTrace,
+ });
+
+ const result = await runDecisionModelEvaluation({ ...baseParams, deps });
+
+ // The persisted execution trace id must resolve to a written trace.
+ expect(writeInternalTrace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ rootSpanId: result.executionTraceId,
+ eventInputs: [
+ expect.objectContaining({
+ traceId: result.executionTraceId,
+ name: "Execute evaluator: Send readiness",
+ modelName: "jev-1.13.0",
+ }),
+ ],
+ }),
+ );
+
+ expect(callDecisionModel).toHaveBeenCalledWith({
+ modelConfig: typeSafeModelConfig.config,
+ request: {
+ state: {
+ input: "Can I get a refund?",
+ output: "Yes, unused items within 30 days.",
+ },
+ questions: {
+ readiness: {
+ type: "choice",
+ instructions: "Is `output` ready to send as an answer to `input`?",
+ criteria: { ready: null, needs_revision: null },
+ },
+ refund: {
+ type: "boolean",
+ instructions: "Does `input` request a refund?",
+ },
+ },
+ },
+ });
+ expect(result.scores).toEqual([
+ expect.objectContaining({
+ name: "send_readiness",
+ dataType: "CATEGORICAL",
+ value: "ready",
+ metadata: {
+ typesafe: expect.objectContaining({
+ questionId: "readiness",
+ type: "choice",
+ choice: "ready",
+ confidence: 0.82,
+ probabilities: { ready: 0.91, needs_revision: 0.09 },
+ }),
+ },
+ }),
+ expect.objectContaining({
+ name: "refund_requested",
+ dataType: "NUMERIC",
+ value: 0.97,
+ }),
+ ]);
+ expect(mocks.blockEvaluator).not.toHaveBeenCalled();
+ });
+
+ it("pauses the evaluator when the connection is not a decision-model connection", async () => {
+ const deps = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue({
+ ...typeSafeModelConfig,
+ config: {
+ ...typeSafeModelConfig.config,
+ provider: "openai",
+ apiKey: { adapter: "openai", secretKey: "encrypted" },
+ },
+ }),
+ callDecisionModel: vi.fn(),
+ });
+
+ await expect(
+ runDecisionModelEvaluation({ ...baseParams, deps }),
+ ).rejects.toBeInstanceOf(UnrecoverableError);
+ expect(mocks.blockEvaluator).toHaveBeenCalledWith(
+ expect.objectContaining({
+ evaluatorId: "evaluator-1",
+ source: EvaluatorBlockSource.INVALID_MODEL_CONFIG,
+ }),
+ );
+ expect(deps.callDecisionModel).not.toHaveBeenCalled();
+ });
+
+ it("applies the LLM error policy to provider failures", async () => {
+ // A connection-level failure pauses the evaluator like an LLM judge would.
+ const unreachable = new LLMValidationError({
+ code: "endpoint-unreachable",
+ message: "Cannot reach TypeSafe",
+ });
+ const blocked = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue(typeSafeModelConfig),
+ callDecisionModel: vi.fn().mockRejectedValue(unreachable),
+ });
+ await expect(
+ runDecisionModelEvaluation({ ...baseParams, deps: blocked }),
+ ).rejects.toBe(unreachable);
+ expect(mocks.blockEvaluator).toHaveBeenCalledWith(
+ expect.objectContaining({
+ evaluatorId: "evaluator-1",
+ source: EvaluatorBlockSource.LLM_COMPLETION_ERROR,
+ }),
+ );
+
+ // Anything else propagates untouched so the queue decides on retries.
+ mocks.blockEvaluator.mockClear();
+ const transient = new Error("socket hang up");
+ const failing = createMockEvalExecutionDeps({
+ fetchModelConfig: vi.fn().mockResolvedValue(typeSafeModelConfig),
+ callDecisionModel: vi.fn().mockRejectedValue(transient),
+ });
+ await expect(
+ runDecisionModelEvaluation({ ...baseParams, deps: failing }),
+ ).rejects.toBe(transient);
+ expect(mocks.blockEvaluator).not.toHaveBeenCalled();
+ });
+});
diff --git a/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.ts b/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.ts
new file mode 100644
index 0000000000..0b6bd02edd
--- /dev/null
+++ b/worker/src/features/evaluation/decisionModel/runDecisionModelEvaluation.ts
@@ -0,0 +1,237 @@
+import {
+ type EvaluatorBlockReason,
+ type JobConfiguration,
+ type JobExecution,
+} from "@prisma/client";
+import {
+ getBlockReasonForInvalidModelConfig,
+ getEvaluatorBlockMetadata,
+ parseDecisionModelQuestions,
+ type EvalExecutionContext,
+ type EvalTemplateDecisionModel,
+} from "@langfuse/shared";
+import {
+ blockEvaluator,
+ buildDecisionModelTraceInput,
+ classifyEvaluatorLlmError,
+ DecisionModelEvaluatorError,
+ EvaluatorBlockSource,
+ executeDecisionModelEvaluator,
+ instrumentAsync,
+ isDecisionModelAdapter,
+ logger,
+ type ExtractedVariable,
+} from "@langfuse/shared/src/server";
+import { UnrecoverableError } from "../../../errors/UnrecoverableError";
+import { createW3CTraceId } from "../../utils";
+import { type EvalExecutionResult } from "../evalCompletion";
+import { type EvalExecutionDeps } from "../evalExecutionDeps";
+import {
+ buildEvalExecutionSpanAttributes,
+ buildEvaluatorLlmErrorSpanAttributes,
+} from "../evalSpanAttributes";
+
+export async function runDecisionModelEvaluation({
+ projectId,
+ jobExecutionId,
+ job,
+ config,
+ template,
+ extractedVariables,
+ executionMetadata,
+ evaluationContext,
+ deps,
+ evaluatorId,
+}: {
+ projectId: string;
+ jobExecutionId: string;
+ job: JobExecution;
+ config: JobConfiguration;
+ template: EvalTemplateDecisionModel;
+ extractedVariables: ExtractedVariable[];
+ executionMetadata: Record<string, string>;
+ evaluationContext: EvalExecutionContext;
+ deps: EvalExecutionDeps;
+ evaluatorId?: string;
+}): Promise<EvalExecutionResult> {
+ const pauseEvaluator = async (
+ blockReason: EvaluatorBlockReason,
+ source: EvaluatorBlockSource,
+ ) => {
+ if (!evaluatorId) {
+ throw new UnrecoverableError(
+ `Evaluator identity missing for job ${jobExecutionId}`,
+ );
+ }
+ await blockEvaluator({
+ projectId,
+ evaluatorId,
+ blockReason,
+ blockMessage: getEvaluatorBlockMetadata(blockReason).message,
+ source,
+ });
+ };
+
+ return instrumentAsync(
+ { name: "eval.execute-decision-model" },
+ async (span) => {
+ span.setAttribute("langfuse.project.id", projectId);
+ span.setAttribute("eval.job_execution.id", jobExecutionId);
+ span.setAttribute("eval.template.name", template.name);
+ span.setAttribute("eval.template.id", template.id);
+ span.setAttribute("eval.template.version", template.version);
+ span.setAttributes(buildEvalExecutionSpanAttributes({ config }));
+ if (job.jobInputTraceId) {
+ span.setAttribute("eval.target.trace_id", job.jobInputTraceId);
+ }
+ if (job.jobInputObservationId) {
+ span.setAttribute(
+ "eval.target.observation_id",
+ job.jobInputObservationId,
+ );
+ }
+
+ span.setAttribute("eval.execution.stage", "validate_template");
+ const parsedQuestions = parseDecisionModelQuestions(template.questions);
+ if (!parsedQuestions.success) {
+ span.setAttribute("eval.execution.outcome", "invalid_template");
+ throw new UnrecoverableError(
+ `Decision-model questions are invalid: ${parsedQuestions.error}`,
+ );
+ }
+ const questions = parsedQuestions.data;
+ span.setAttribute("eval.decision_model.question_count", questions.length);
+
+ span.setAttribute("eval.execution.stage", "resolve_model_config");
+ const modelConfig = await deps.fetchModelConfig({
+ projectId,
+ provider: template.provider ?? undefined,
+ model: template.model ?? undefined,
+ modelParams: null,
+ });
+
+ let modelConfigError: string | null = null;
+ if (!modelConfig.valid) {
+ modelConfigError = modelConfig.error;
+ } else if (!isDecisionModelAdapter(modelConfig.config.apiKey.adapter)) {
+ modelConfigError = `Connection "${modelConfig.config.provider}" is not a decision-model connection`;
+ }
+ if (!modelConfig.valid || modelConfigError !== null) {
+ const blockReason = getBlockReasonForInvalidModelConfig({
+ templateProvider: template.provider,
+ templateModel: template.model,
+ error: modelConfigError ?? "",
+ });
+ span.setAttributes({
+ "eval.execution.outcome": "blocked",
+ "eval.llm.blocked": true,
+ "eval.llm.block.reason": blockReason,
+ "eval.llm.block.source": EvaluatorBlockSource.INVALID_MODEL_CONFIG,
+ });
+ await pauseEvaluator(
+ blockReason,
+ EvaluatorBlockSource.INVALID_MODEL_CONFIG,
+ );
+ logger.warn(
+ `Eval job ${jobExecutionId} will fail. ${modelConfigError}`,
+ );
+ throw new UnrecoverableError(
+ `Invalid model configuration for job ${jobExecutionId}: ${modelConfigError}`,
+ );
+ }
+
+ span.setAttribute("eval.model.provider", modelConfig.config.provider);
+ span.setAttribute("eval.model.name", modelConfig.config.model);
+ span.setAttribute(
+ "eval.model.adapter",
+ modelConfig.config.apiKey.adapter,
+ );
+
+ const executionTraceId = createW3CTraceId(jobExecutionId);
+ span.setAttributes({
+ "eval.execution.trace_id": executionTraceId,
+ "eval.execution.stage": "call_decision_model",
+ });
+
+ const traceStartTime = new Date();
+ let execution: Awaited<ReturnType<typeof executeDecisionModelEvaluator>>;
+ try {
+ execution = await executeDecisionModelEvaluator({
+ variables: extractedVariables,
+ questions,
+ client: {
+ evaluate: (request) =>
+ deps.callDecisionModel({
+ modelConfig: modelConfig.config,
+ request,
+ }),
+ },
+ });
+ } catch (e) {
+ if (e instanceof DecisionModelEvaluatorError) {
+ span.setAttribute("eval.execution.outcome", "invalid_model_output");
+ throw new UnrecoverableError(e.message);
+ }
+
+ const classification = classifyEvaluatorLlmError(e);
+ span.setAttributes(
+ buildEvaluatorLlmErrorSpanAttributes(classification),
+ );
+ span.setAttribute(
+ "eval.execution.outcome",
+ classification?.blockReason ? "blocked" : "llm_error",
+ );
+ if (classification?.blockReason) {
+ await pauseEvaluator(
+ classification.blockReason,
+ EvaluatorBlockSource.LLM_COMPLETION_ERROR,
+ );
+ span.setAttribute("eval.llm.block.applied", true);
+ }
+ throw e;
+ }
+
+ span.setAttribute(
+ "eval.decision_model.model",
+ execution.evaluation.model,
+ );
+ logger.debug(
+ `Job ${jobExecutionId} received ${execution.scores.length} decision-model answer(s) from ${execution.evaluation.model}`,
+ );
+
+ try {
+ await deps.writeInternalTrace(
+ buildDecisionModelTraceInput({
+ projectId,
+ executionTraceId,
+ traceStartTime,
+ traceName: `Execute evaluator: ${template.name}`,
+ request: execution.request,
+ evaluation: execution.evaluation,
+ metadata: executionMetadata,
+ evaluationContext,
+ }),
+ );
+ } catch (error) {
+ logger.warn("Failed to write decision-model execution trace", {
+ jobExecutionId,
+ executionTraceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ span.setAttribute("eval.score.count", execution.scores.length);
+ span.setAttributes({
+ "eval.execution.stage": "completed",
+ "eval.execution.outcome": "success",
+ });
+
+ return {
+ scores: execution.scores,
+ executionTraceId,
+ metadata: executionMetadata,
+ evaluationContext,
+ };
+ },
+ );
+}
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
index 1f56973181..d9a1123663 100644
--- a/worker/src/features/evaluation/evalExecutionDeps.ts
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -3,10 +3,12 @@ import { z } from "zod";
import { JobExecutionStatus } from "@prisma/client";
import type { EvalExecutionContext } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
+import { decrypt } from "@langfuse/shared/encryption";
import {
buildEventBucketPrefix,
compileLangfuseMediaMessages,
createLLMOutput,
+ createTypeSafeDecisionModelClient,
DefaultEvalModelService,
generateLLMText,
IngestionQueue,
@@ -16,7 +18,12 @@ import {
ScoreEventType,
UNKNOWN_INGESTION_SDK_VALUE,
type ChatMessage,
+ type DecisionModelEvaluation,
+ type DecisionModelRequest,
+ type InternalTraceWriter,
+ writeInternalTraceViaOtelIngestion,
} from "@langfuse/shared/src/server";
+import { UnrecoverableError } from "../../errors/UnrecoverableError";
import { getEvalS3StorageClient } from "./s3StorageClient";
import { createInternalEventsWriter } from "../internal-tracing/createInternalEventsWriter";
import { recordExportVolume } from "../../services/exportVolumeMetric";
@@ -68,6 +75,14 @@ interface LLMCallParams {
};
}
+/**
+ * Parameters for asking a decision model one Choice question.
+ */
+interface DecisionModelCallParams {
+ modelConfig: Extract<ModelConfigResult, { valid: true }>["config"];
+ request: DecisionModelRequest;
+}
+
/**
* Update data for job execution status.
*/
@@ -140,6 +155,12 @@ export interface EvalExecutionDeps {
fetchModelConfig: (
params: FetchModelConfigParams,
) => Promise<ModelConfigResult>;
+
+ // Decision-model operations (experimental)
+ callDecisionModel: (
+ params: DecisionModelCallParams,
+ ) => Promise<DecisionModelEvaluation>;
+ writeInternalTrace: InternalTraceWriter;
}
// Measure the schema as the JSON Schema LangChain ships, not Zod's _def.
@@ -313,6 +334,39 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
// Cast to our simplified ModelConfigResult type for the interface
return result as ModelConfigResult;
},
+
+ callDecisionModel: async (params) => {
+ const { apiKey } = params.modelConfig;
+ if (apiKey.adapter !== LLMAdapter.TypeSafe) {
+ throw new Error(
+ `Decision-model adapter is not supported: ${apiKey.adapter}`,
+ );
+ }
+ const secretKey = apiKey.secretKey;
+ if (typeof secretKey !== "string") {
+ throw new UnrecoverableError(
+ "TypeSafe connection is missing its secret key",
+ );
+ }
+
+ let decryptedSecretKey: string;
+ try {
+ decryptedSecretKey = decrypt(secretKey);
+ } catch {
+ throw new UnrecoverableError(
+ "TypeSafe connection secret could not be decrypted",
+ );
+ }
+
+ const client = createTypeSafeDecisionModelClient({
+ apiKey: decryptedSecretKey,
+ model: params.modelConfig.model,
+ });
+
+ return client.evaluate(params.request);
+ },
+
+ writeInternalTrace: (trace) => writeInternalTraceViaOtelIngestion(trace),
};
}
@@ -333,6 +387,36 @@ export function createMockEvalExecutionDeps(
valid: false,
error: "Mock - no config",
}),
+ callDecisionModel: async ({ request }) => ({
+ model: "mock-decision-model",
+ answers: Object.fromEntries(
+ Object.entries(request.questions).map(([id, question]) => {
+ switch (question.type) {
+ case "choice": {
+ const [choice = "mock"] = Object.keys(question.criteria);
+ return [
+ id,
+ {
+ type: "choice",
+ choice,
+ probabilities: { [choice]: 1 },
+ confidence: 1,
+ },
+ ];
+ }
+ case "score":
+ return [
+ id,
+ { type: "score", score: 0, probabilities: {}, confidence: 1 },
+ ];
+ case "boolean":
+ return [id, { type: "boolean", probability: 1 }];
+ }
+ }),
+ ),
+ usage: null,
+ }),
+ writeInternalTrace: async () => {},
};
return { ...defaultMock, ...overrides };
diff --git a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
index f6070cbad3..6e28937eaf 100644
--- a/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
+++ b/worker/src/features/evaluation/observationEval/__tests__/observationEvalProcessor.test.ts
@@ -312,7 +312,10 @@ describe("processObservationEval", () => {
projectId,
evaluationRuleId: rule.id,
evaluatorId: evaluator.id,
- evaluator: { projectId, type: "LLM_AS_JUDGE" },
+ evaluator: {
+ projectId,
+ type: { in: ["LLM_AS_JUDGE", "DECISION_MODEL"] },
+ },
},
}),
);
@@ -913,7 +916,12 @@ describe("processObservationEval", () => {
evaluationRuleId: config.id,
evaluator: {
projectId,
- type: EvalTemplateType.LLM_AS_JUDGE,
+ type: {
+ in: [
+ EvalTemplateType.LLM_AS_JUDGE,
+ EvalTemplateType.DECISION_MODEL,
+ ],
+ },
},
}),
}),
diff --git a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
index 6e8ac66e9f..c0a87bd3ba 100644
--- a/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
+++ b/worker/src/features/evaluation/observationEval/observationEvalProcessor.ts
@@ -35,6 +35,7 @@ import {
} from "../evalExecutionDeps";
import { runLLMAsJudgeEvaluation } from "../evalService";
import { executeCodeBasedEvaluation } from "../codeBased";
+import { runDecisionModelEvaluation } from "../decisionModel/runDecisionModelEvaluation";
import { getEvalS3StorageClient } from "../s3StorageClient";
import { type ObservationForEval } from "./types";
@@ -75,6 +76,17 @@ type ObservationEvalExecutionType =
| typeof EvalTemplateType.LLM_AS_JUDGE
| typeof EvalTemplateType.CODE;
+const EVALUATOR_TYPES_BY_EXECUTION_TYPE: Record<
+ ObservationEvalExecutionType,
+ EvalTemplateType[]
+> = {
+ [EvalTemplateType.LLM_AS_JUDGE]: [
+ EvalTemplateType.LLM_AS_JUDGE,
+ EvalTemplateType.DECISION_MODEL,
+ ],
+ [EvalTemplateType.CODE]: [EvalTemplateType.CODE],
+};
+
export type ObservationEvalProcessorOutcome =
| "completed"
| "cancelled"
@@ -274,6 +286,15 @@ export async function processObservationEval(
: {}),
});
break;
+ case EvalTemplateType.DECISION_MODEL:
+ executionResult = await runDecisionModelEvaluation({
+ ...executionParams,
+ template,
+ ...(resolved.type === "v2"
+ ? { evaluatorId: resolved.evaluatorId }
+ : {}),
+ });
+ break;
}
await completeEvalExecution({
@@ -320,6 +341,9 @@ async function resolveObservationEvalExecution(params: {
}) {
const { event, job, executionType } = params;
const { projectId, evaluatorId, evaluationRuleId } = event;
+ const evaluatorTypeFilter = {
+ in: EVALUATOR_TYPES_BY_EXECUTION_TYPE[executionType],
+ };
if (!evaluatorId) {
const migratedAssignment =
@@ -327,7 +351,7 @@ async function resolveObservationEvalExecution(params: {
where: {
projectId,
evaluationRuleId: job.jobConfigurationId,
- evaluator: { projectId, type: executionType },
+ evaluator: { projectId, type: evaluatorTypeFilter },
},
include: {
evaluationRule: true,
@@ -355,7 +379,7 @@ async function resolveObservationEvalExecution(params: {
// the user's selection already authorized the run.
if (!evaluationRuleId) {
const evaluator = await prisma.evaluator.findFirst({
- where: { id: evaluatorId, projectId, type: executionType },
+ where: { id: evaluatorId, projectId, type: evaluatorTypeFilter },
include: evaluatorInclude,
});
if (!evaluator) {
@@ -381,7 +405,7 @@ async function resolveObservationEvalExecution(params: {
projectId,
evaluationRuleId,
evaluatorId,
- evaluator: { projectId, type: executionType },
+ evaluator: { projectId, type: evaluatorTypeFilter },
},
include: {
evaluationRule: true,
@@ -410,13 +434,13 @@ const evaluatorInclude = {
} satisfies Prisma.EvaluatorInclude;
function normalizeEvalTemplate(
- template: EvalTemplate & { promptMessages?: unknown },
- executionType: ObservationEvalExecutionType,
+ template: EvalTemplate & { promptMessages?: unknown; questions?: unknown },
+ evaluatorType: EvalTemplateType,
): EvalTemplateWithType {
- switch (executionType) {
+ switch (evaluatorType) {
case EvalTemplateType.LLM_AS_JUDGE:
if (
- template.type !== executionType ||
+ template.type !== evaluatorType ||
template.prompt === null ||
template.outputDefinition === null
) {
@@ -426,7 +450,7 @@ function normalizeEvalTemplate(
}
return {
...template,
- type: executionType,
+ type: evaluatorType,
prompt: template.prompt,
outputDefinition: template.outputDefinition,
sourceCode: null,
@@ -434,7 +458,7 @@ function normalizeEvalTemplate(
};
case EvalTemplateType.CODE:
if (
- template.type !== executionType ||
+ template.type !== evaluatorType ||
template.sourceCode === null ||
template.sourceCodeLanguage === null
) {
@@ -444,12 +468,31 @@ function normalizeEvalTemplate(
}
return {
...template,
- type: executionType,
+ type: evaluatorType,
prompt: null,
outputDefinition: null,
sourceCode: template.sourceCode,
sourceCodeLanguage: template.sourceCodeLanguage,
};
+ case EvalTemplateType.DECISION_MODEL:
+ if (
+ template.type !== evaluatorType ||
+ template.questions === null ||
+ template.questions === undefined
+ ) {
+ throw new UnrecoverableError(
+ "Evaluator template is incomplete for DECISION_MODEL execution",
+ );
+ }
+ return {
+ ...template,
+ type: evaluatorType,
+ prompt: null,
+ outputDefinition: null,
+ sourceCode: null,
+ sourceCodeLanguage: null,
+ questions: template.questions,
+ };
}
}
@@ -525,6 +568,7 @@ function buildV2Execution(params: {
outputDefinition: version.outputDefinition,
sourceCode: version.sourceCode,
sourceCodeLanguage: version.sourceCodeLanguage,
+ questions: version.questions,
};
return {